ldapconnection.cpp 243 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. // LDAP prototypes use char* where they should be using const char *, resulting in lots of spurious warnings
  14. #pragma warning( disable : 4786 )
  15. #ifdef __GNUC__
  16. #pragma GCC diagnostic ignored "-Wwrite-strings"
  17. #endif
  18. #include "permissions.ipp"
  19. #include "aci.ipp"
  20. #include "ldapsecurity.ipp"
  21. #include "jsmartsock.hpp"
  22. #include "jrespool.tpp"
  23. #include "mpbase.hpp"
  24. #include "dautils.hpp"
  25. #include "dasds.hpp"
  26. #include "workunit.hpp"
  27. #include <map>
  28. #include <string>
  29. #include <set>
  30. #ifdef _WIN32
  31. #include <lm.h>
  32. #define LdapRename ldap_rename_ext_s
  33. LDAPMessage* (*LdapFirstEntry)(LDAP*, LDAPMessage*) = &ldap_first_entry;
  34. LDAPMessage* (*LdapNextEntry)(LDAP* ld, LDAPMessage* entry) = &ldap_next_entry;
  35. #else
  36. #define LdapRename ldap_rename_s
  37. LDAPMessage* (__stdcall *LdapFirstEntry)(LDAP*, LDAPMessage*) = &ldap_first_message;
  38. LDAPMessage* (__stdcall *LdapNextEntry)(LDAP* ld, LDAPMessage* entry) = &ldap_next_message;
  39. #endif
  40. #define LDAPSEC_MAX_RETRIES 2
  41. #define LDAPSEC_RETRY_WAIT 3
  42. #ifdef _WIN32
  43. #define LDAP_NO_ATTRS "1.1"
  44. #endif
  45. #define PWD_NEVER_EXPIRES (__int64)0x8000000000000000
  46. //Ldap extended control identifier LDAP_SERVER_SD_FLAGS_OID
  47. #define AAD_LDAP_SERVER_SD_FLAGS_OID "1.2.840.113556.1.4.801"
  48. #define UNK_PERM_VALUE (SecAccessFlags)-2 //used to initialize "default" permission, which we later try to deduce
  49. const char* UserFieldNames[] = { "@id", "@name", "@fullname", "@passwordexpiration", "@employeeid", "@employeenumber" };
  50. const char* getUserFieldNames(UserField field)
  51. {
  52. if (field < UFterm)
  53. return UserFieldNames[field];
  54. return NULL;
  55. }
  56. const char* GroupFieldNames[] = { "@name", "@groupOwner", "@desc" };
  57. const char* getGroupFieldNames(GroupField field)
  58. {
  59. if (field < GFterm)
  60. return GroupFieldNames[field];
  61. return NULL;
  62. }
  63. const char* ResourceFieldNames[] = { "@name", "@desc" };
  64. const char* getResourceFieldNames(ResourceField field)
  65. {
  66. if (field < RFterm)
  67. return ResourceFieldNames[field];
  68. return NULL;
  69. }
  70. const char* ResourcePermissionFieldNames[] = { "@name", "@type", "@allow", "@deny" };
  71. const char* getResourcePermissionFieldNames(ResourcePermissionField field)
  72. {
  73. if (field < RPFterm)
  74. return ResourcePermissionFieldNames[field];
  75. return NULL;
  76. }
  77. class CSecItemIterator: public CInterfaceOf<ISecItemIterator>
  78. {
  79. IArrayOf<IPropertyTree> attrs;
  80. unsigned index;
  81. public:
  82. CSecItemIterator(IArrayOf<IPropertyTree>& trees)
  83. {
  84. ForEachItemIn(t, trees)
  85. attrs.append(*LINK(&trees.item(t)));
  86. index = 0;
  87. }
  88. virtual ~CSecItemIterator()
  89. {
  90. attrs.kill();
  91. }
  92. bool first()
  93. {
  94. index = 0;
  95. return (attrs.ordinality()!=0);
  96. }
  97. bool next()
  98. {
  99. index++;
  100. return (index<attrs.ordinality());
  101. }
  102. bool isValid()
  103. {
  104. return (index<attrs.ordinality());
  105. }
  106. IPropertyTree & query()
  107. {
  108. return attrs.item(index);
  109. }
  110. };
  111. class CHostManager
  112. {
  113. private:
  114. StringArray m_hostArray;
  115. Mutex m_HMMutex;
  116. unsigned m_curHostIdx;
  117. bool m_populated;
  118. public:
  119. CHostManager()
  120. {
  121. m_populated = false;
  122. m_curHostIdx = 0;
  123. }
  124. void populateHosts(const char* addrlist)
  125. {
  126. if (m_populated)
  127. return;
  128. synchronized block(m_HMMutex);
  129. if (!m_populated)
  130. {
  131. char *copyFullText = strdup(addrlist);
  132. char *saveptr;
  133. char *ip = strtok_r(copyFullText, "|,", &saveptr);//multiple LDAP IP separators ("ldapAddress=x.x.x.x,y.y.y.y")
  134. while (ip != NULL)
  135. {
  136. if (isdigit(*ip))
  137. {
  138. char *dash = strrchr(ip, '-');
  139. if (dash)
  140. {
  141. *dash = 0;
  142. int last = atoi(dash+1);
  143. char *dot = strrchr(ip, '.');
  144. *dot = 0;
  145. int first = atoi(dot+1);
  146. for (int i = first; i <= last; i++)
  147. {
  148. StringBuffer t;
  149. t.append(ip).append('.').append(i);
  150. m_hostArray.append(t.str());
  151. }
  152. }
  153. else
  154. {
  155. m_hostArray.append(ip);
  156. }
  157. }
  158. else
  159. {
  160. m_hostArray.append(ip);
  161. }
  162. DBGLOG("Added ldap server %s", m_hostArray.item(m_hostArray.ordinality()-1));
  163. ip = strtok_r(NULL, "|,", &saveptr);
  164. }
  165. free(copyFullText);
  166. if(m_hostArray.length() == 0)
  167. {
  168. throw MakeStringException(-1, "No valid ldap server address specified");
  169. }
  170. m_curHostIdx = 0;
  171. m_populated = true;
  172. }
  173. }
  174. int queryNumHosts()
  175. {
  176. return m_hostArray.ordinality();
  177. }
  178. const char * queryCurrentHost()
  179. {
  180. synchronized block(m_HMMutex);
  181. return m_hostArray.item(m_curHostIdx);
  182. }
  183. void rejectHost(const char * rejectedHost)
  184. {
  185. if (m_hostArray.ordinality() == 1)
  186. {
  187. DBGLOG("Cannot reject the only configured LDAP AD server %s", m_hostArray.item(m_curHostIdx));
  188. return;
  189. }
  190. //If rejectedHost is not already rejected, do so
  191. synchronized block(m_HMMutex);
  192. if (0 == strcmp(rejectedHost, m_hostArray.item(m_curHostIdx)))
  193. {
  194. DBGLOG("Temporarily rejecting LDAP AD server %s", m_hostArray.item(m_curHostIdx));
  195. if (++m_curHostIdx == m_hostArray.ordinality())
  196. m_curHostIdx = 0;//start over at begin of host array
  197. }
  198. }
  199. } s_hostManager;
  200. inline bool LdapServerDown(int rc)
  201. {
  202. return rc==LDAP_SERVER_DOWN||rc==LDAP_UNAVAILABLE||rc==LDAP_TIMEOUT;
  203. }
  204. class CLdapConfig : implements ILdapConfig, public CInterface
  205. {
  206. private:
  207. LdapServerType m_serverType;
  208. StringAttr m_cfgServerType;//LDAP Server type name (ActiveDirectory, Fedora389, etc)
  209. Owned<IPropertyTree> m_cfg;
  210. int m_ldapport;
  211. int m_ldap_secure_port;
  212. StringBuffer m_adminGroupDN;//fully qualified DN of the HPCC administrator
  213. StringBuffer m_protocol;
  214. StringBuffer m_basedn;
  215. StringBuffer m_domain;
  216. StringBuffer m_authmethod;
  217. StringBuffer m_user_basedn;
  218. StringBuffer m_group_basedn;
  219. StringBuffer m_resource_basedn;
  220. StringBuffer m_filescope_basedn;
  221. StringBuffer m_view_basedn;
  222. StringBuffer m_workunitscope_basedn;
  223. StringBuffer m_sudoers_basedn;
  224. StringBuffer m_template_name;
  225. StringBuffer m_sysuser;
  226. StringBuffer m_sysuser_commonname;
  227. StringBuffer m_sysuser_password;
  228. StringBuffer m_sysuser_basedn;
  229. bool m_sysuser_specified;
  230. StringBuffer m_sysuser_dn;
  231. int m_maxConnections;
  232. StringBuffer m_sdfieldname;
  233. int m_timeout;
  234. bool m_isAzureAD = false;
  235. public:
  236. IMPLEMENT_IINTERFACE
  237. CLdapConfig(IPropertyTree* cfg)
  238. {
  239. int version = LDAP_VERSION3;
  240. ldap_set_option( NULL, LDAP_OPT_PROTOCOL_VERSION, &version);
  241. m_cfg.set(cfg);
  242. //Check for LDAP Server type in config
  243. m_serverType = LDAPSERVER_UNKNOWN;
  244. m_cfgServerType.set(cfg->queryProp(".//@serverType"));
  245. if (m_cfgServerType.length())
  246. {
  247. PROGLOG("LDAP Server Type from config: %s", m_cfgServerType.str());
  248. if (0 == stricmp(m_cfgServerType, "ActiveDirectory"))
  249. m_serverType = ACTIVE_DIRECTORY;
  250. else if (strieq(m_cfgServerType, "AzureActiveDirectory"))
  251. {
  252. m_serverType = ACTIVE_DIRECTORY;
  253. m_isAzureAD = true;
  254. }
  255. else if (0 == stricmp(m_cfgServerType, "389DirectoryServer"))//uses iPlanet style ACI
  256. m_serverType = OPEN_LDAP;
  257. else if (0 == stricmp(m_cfgServerType, "OpenLDAP"))
  258. m_serverType = OPEN_LDAP;
  259. else if (0 == stricmp(m_cfgServerType, "Fedora389"))
  260. m_serverType = OPEN_LDAP;
  261. else if (0 == stricmp(m_cfgServerType, "iPlanet"))
  262. m_serverType = IPLANET;
  263. else
  264. throw MakeStringException(-1, "Unknown LDAP serverType '%s' specified",m_cfgServerType.get());
  265. }
  266. else
  267. {
  268. DBGLOG("LDAP serverType not specified, will try to deduce");
  269. }
  270. StringBuffer hostsbuf;
  271. cfg->getProp(".//@ldapAddress", hostsbuf);
  272. if(hostsbuf.length() == 0)
  273. {
  274. throw MakeStringException(-1, "ldapAddress not found in config");
  275. }
  276. s_hostManager.populateHosts(hostsbuf.str());
  277. cfg->getProp(".//@ldapProtocol", m_protocol);
  278. if(m_protocol.length() == 0)
  279. {
  280. m_protocol.append("ldap");
  281. }
  282. StringBuffer portbuf;
  283. cfg->getProp(".//@ldapPort", portbuf);
  284. if(portbuf.length() == 0)
  285. m_ldapport = 389;
  286. else
  287. m_ldapport = atoi(portbuf.str());
  288. portbuf.clear();
  289. cfg->getProp(".//@ldapSecurePort", portbuf);
  290. if(portbuf.length() == 0)
  291. m_ldap_secure_port = 636;
  292. else
  293. m_ldap_secure_port = atoi(portbuf.str());
  294. m_timeout = cfg->getPropInt(".//@ldapTimeoutSecs", LDAPTIMEOUT);
  295. int rc = LDAP_OTHER;
  296. StringBuffer hostbuf, dcbuf;
  297. const char * ldapDomain = cfg->queryProp(".//@ldapDomain");
  298. for (int numHosts=0; numHosts < getHostCount(); numHosts++)
  299. {
  300. getLdapHost(hostbuf);
  301. unsigned port = strieq("ldaps",m_protocol) ? m_ldap_secure_port : m_ldapport;
  302. StringBuffer sysUserDN, decPwd;
  303. {
  304. StringBuffer pwd;
  305. cfg->getProp(".//@systemPassword", pwd);
  306. if (pwd.isEmpty())
  307. throw MakeStringException(-1, "systemPassword is empty");
  308. decrypt(decPwd, pwd.str());
  309. StringBuffer sysUserCN;
  310. cfg->getProp(".//@systemCommonName", sysUserCN);
  311. if (sysUserCN.isEmpty())
  312. throw MakeStringException(-1, "systemCommonName is empty");
  313. StringBuffer sysBasedn;
  314. cfg->getProp(".//@systemBasedn", sysBasedn);
  315. if (sysBasedn.isEmpty())
  316. throw MakeStringException(-1, "systemBasedn is empty");
  317. //Guesstimate system user baseDN based on config settings. It will be used if anonymous bind fails
  318. sysUserDN.append("cn=").append(sysUserCN.str()).append(",").append(sysBasedn.str());
  319. }
  320. for(int retries = 0; retries <= LDAPSEC_MAX_RETRIES; retries++)
  321. {
  322. rc = LdapUtils::getServerInfo(hostbuf.str(), sysUserDN.str(), decPwd.str(), m_protocol, port, dcbuf, m_serverType, ldapDomain, m_timeout);
  323. if(!LdapServerDown(rc) || retries >= LDAPSEC_MAX_RETRIES)
  324. break;
  325. sleep(LDAPSEC_RETRY_WAIT);
  326. if(retries < LDAPSEC_MAX_RETRIES)
  327. {
  328. DBGLOG("Server %s temporarily unreachable, retrying...", hostbuf.str());
  329. }
  330. }
  331. if (rc != LDAP_SUCCESS)
  332. {
  333. rejectHost(hostbuf);
  334. }
  335. else
  336. break;
  337. }
  338. if(rc != LDAP_SUCCESS)
  339. {
  340. throw MakeStringException(-1, "getServerInfo error - %s", ldap_err2string(rc));
  341. }
  342. const char* basedn = cfg->queryProp(".//@commonBasedn");
  343. if(basedn == NULL || *basedn == '\0')
  344. {
  345. basedn = dcbuf.str();
  346. }
  347. LdapUtils::cleanupDn(basedn, m_basedn);
  348. StringBuffer user_basedn;
  349. cfg->getProp(".//@usersBasedn", user_basedn);
  350. if(user_basedn.length() == 0)
  351. {
  352. throw MakeStringException(-1, "users basedn not found in config");
  353. }
  354. LdapUtils::normalizeDn(user_basedn.str(), m_basedn.str(), m_user_basedn);
  355. StringBuffer group_basedn;
  356. cfg->getProp(".//@groupsBasedn", group_basedn);
  357. if(group_basedn.length() == 0)
  358. {
  359. throw MakeStringException(-1, "groups basedn not found in config");
  360. }
  361. LdapUtils::normalizeDn(group_basedn.str(), m_basedn.str(), m_group_basedn);
  362. StringBuffer adminGrp;
  363. cfg->getProp(".//@adminGroupName", adminGrp);
  364. if(adminGrp.isEmpty())
  365. {
  366. if (m_isAzureAD)
  367. adminGrp.clear().appendf("cn=%s,ou=%s", AAD_ADMINISTRATORS_GROUP, AAD_USERS_GROUPS_OU);
  368. else
  369. adminGrp.set(m_serverType == ACTIVE_DIRECTORY ? "cn=Administrators,cn=Builtin" : "cn=Directory Administrators");
  370. }
  371. else if (0 == stricmp("Administrators", adminGrp.str()))
  372. {
  373. adminGrp.set("cn=Administrators,cn=Builtin");//Active Directory
  374. }
  375. else if (0 == stricmp("Directory Administrators", adminGrp.str()))
  376. {
  377. adminGrp.set("cn=Directory Administrators");//389 DirectoryServer
  378. }
  379. else if (nullptr == strstr(adminGrp.str(), "CN=") && nullptr == strstr(adminGrp.str(), "cn="))
  380. {
  381. //Group name only. Add group OU
  382. StringBuffer sb;
  383. sb.appendf("cn=%s,%s", adminGrp.str(), group_basedn.str());
  384. adminGrp.set(sb);
  385. }
  386. //If fully qualified group OU name entered, no changes necessary
  387. if (nullptr == strstr(adminGrp.str(), "DC=") && nullptr == strstr(adminGrp.str(), "dc="))
  388. adminGrp.appendf(",%s", m_basedn.str());//add DC (Domain Component)
  389. LdapUtils::cleanupDn(adminGrp, m_adminGroupDN);
  390. PROGLOG("adminGroupName '%s'", m_adminGroupDN.str());
  391. StringBuffer dnbuf;
  392. cfg->getProp(".//@modulesBasedn", dnbuf);
  393. if(dnbuf.length() == 0)
  394. cfg->getProp(".//@resourcesBasedn", dnbuf);
  395. if(dnbuf.length() > 0)
  396. LdapUtils::normalizeDn(dnbuf.str(), m_basedn.str(), m_resource_basedn);
  397. dnbuf.clear();
  398. cfg->getProp(".//@filesBasedn", dnbuf);
  399. if(dnbuf.length() > 0)
  400. LdapUtils::normalizeDn(dnbuf.str(), m_basedn.str(), m_filescope_basedn);
  401. dnbuf.clear();
  402. cfg->getProp(".//@viewsBasedn", dnbuf);
  403. if(dnbuf.length() == 0)
  404. dnbuf.append("ou=views,ou=ecl");//viewsBasedn will not exist in legacy environment files
  405. LdapUtils::normalizeDn(dnbuf.str(), m_basedn.str(), m_view_basedn);
  406. dnbuf.clear();
  407. cfg->getProp(".//@workunitsBasedn", dnbuf);
  408. if(dnbuf.length() > 0)
  409. LdapUtils::normalizeDn(dnbuf.str(), m_basedn.str(), m_workunitscope_basedn);
  410. if(m_resource_basedn.length() + m_filescope_basedn.length() + m_workunitscope_basedn.length() == 0)
  411. {
  412. throw MakeStringException(-1, "One of the following basedns need to be defined: modulesBasedn, resourcesBasedn, filesBasedn or workunitScopesBasedn.");
  413. }
  414. dnbuf.clear();
  415. cfg->getProp(".//@sudoersBasedn", dnbuf);
  416. if(dnbuf.length() == 0)
  417. dnbuf.append("ou=SUDOers");
  418. LdapUtils::normalizeDn(dnbuf.str(), m_basedn.str(), m_sudoers_basedn);
  419. cfg->getProp(".//@templateName", m_template_name);
  420. cfg->getProp(".//@authMethod", m_authmethod);
  421. cfg->getProp(".//@ldapDomain", m_domain);
  422. if(m_domain.length() == 0)
  423. {
  424. const char* dptr = strchr(m_basedn.str(), '=');
  425. if(dptr != NULL)
  426. {
  427. dptr++;
  428. while(*dptr != 0 && *dptr != ',')
  429. {
  430. char c = *dptr++;
  431. m_domain.append(c);
  432. }
  433. }
  434. }
  435. m_sysuser_specified = true;
  436. cfg->getProp(".//@systemUser", m_sysuser);
  437. if(m_sysuser.length() == 0)
  438. {
  439. m_sysuser_specified = false;
  440. }
  441. cfg->getProp(".//@systemCommonName", m_sysuser_commonname);
  442. if(m_sysuser_specified && (m_sysuser_commonname.length() == 0))
  443. {
  444. throw MakeStringException(-1, "SystemUser commonname is empty");
  445. }
  446. StringBuffer passbuf;
  447. cfg->getProp(".//@systemPassword", passbuf);
  448. decrypt(m_sysuser_password, passbuf.str());
  449. StringBuffer sysuser_basedn;
  450. cfg->getProp(".//@systemBasedn", sysuser_basedn);
  451. if(sysuser_basedn.length() == 0)
  452. {
  453. if (m_isAzureAD)
  454. m_sysuser_basedn.appendf("ou=%s", AAD_USERS_GROUPS_OU);
  455. else if(m_serverType == ACTIVE_DIRECTORY)
  456. LdapUtils::normalizeDn( "cn=Users", m_basedn.str(), m_sysuser_basedn);
  457. else if(m_serverType == IPLANET)
  458. m_sysuser_basedn.append("ou=administrators,ou=topologymanagement,o=netscaperoot");
  459. else if(m_serverType == OPEN_LDAP)
  460. m_sysuser_basedn.append(m_basedn.str());
  461. }
  462. else
  463. {
  464. if(m_serverType == ACTIVE_DIRECTORY)
  465. LdapUtils::normalizeDn(sysuser_basedn.str(), m_basedn.str(), m_sysuser_basedn);
  466. else
  467. m_sysuser_basedn.append(sysuser_basedn.str());
  468. }
  469. if(m_sysuser_specified)
  470. {
  471. if(m_serverType == IPLANET)
  472. m_sysuser_dn.append("uid=").append(m_sysuser.str()).append(",").append(m_sysuser_basedn.str());
  473. else if(m_serverType == ACTIVE_DIRECTORY)
  474. m_sysuser_dn.append("cn=").append(m_sysuser_commonname.str()).append(",").append(m_sysuser_basedn.str());
  475. else if(m_serverType == OPEN_LDAP)
  476. {
  477. if (strstr(m_sysuser_commonname.str(), "Directory Manager"))
  478. m_sysuser_dn.append("cn=Directory Manager");
  479. else
  480. {
  481. if (nullptr == strchr(m_sysuser_commonname.str(), '='))
  482. m_sysuser_dn.append("uid=").append(m_sysuser_commonname.str()).append(",").append(m_sysuser_basedn.str()).append(",").append(m_basedn.str());
  483. else
  484. m_sysuser_dn.append(m_sysuser_commonname.str());//includes FQDN prefix, use as is (likely from initldap)
  485. }
  486. }
  487. }
  488. m_maxConnections = cfg->getPropInt(".//@maxConnections", DEFAULT_LDAP_POOL_SIZE);
  489. if(m_maxConnections <= 0)
  490. m_maxConnections = DEFAULT_LDAP_POOL_SIZE;
  491. if(m_serverType == ACTIVE_DIRECTORY)
  492. m_sdfieldname.append("ntSecurityDescriptor");
  493. else if(m_serverType == IPLANET)
  494. m_sdfieldname.append("aci");
  495. else if(m_serverType == OPEN_LDAP)
  496. m_sdfieldname.append("aci");
  497. }
  498. virtual const char * getAdminGroupDN()
  499. {
  500. return m_adminGroupDN.str();
  501. }
  502. virtual LdapServerType getServerType()
  503. {
  504. return m_serverType;
  505. }
  506. virtual const char * getCfgServerType() const
  507. {
  508. return m_cfgServerType.get();
  509. }
  510. virtual const char* getSdFieldName()
  511. {
  512. return m_sdfieldname.str();
  513. }
  514. virtual int getHostCount()
  515. {
  516. return s_hostManager.queryNumHosts();
  517. }
  518. virtual StringBuffer& getLdapHost(StringBuffer& hostbuf)
  519. {
  520. hostbuf.set(s_hostManager.queryCurrentHost());
  521. return hostbuf;
  522. }
  523. virtual void rejectHost(const char * host)
  524. {
  525. s_hostManager.rejectHost(host);
  526. }
  527. virtual void markDown(const char* ldaphost)
  528. {
  529. //SocketEndpoint ep(ldaphost, 0);
  530. //m_ldaphosts->setStatus(ep, false);
  531. }
  532. virtual int getLdapPort()
  533. {
  534. return m_ldapport;
  535. }
  536. virtual int getLdapSecurePort()
  537. {
  538. return m_ldap_secure_port;
  539. }
  540. virtual const char* getProtocol()
  541. {
  542. return m_protocol.str();
  543. }
  544. virtual const char* getBasedn()
  545. {
  546. return m_basedn.str();
  547. }
  548. virtual const char* getDomain()
  549. {
  550. return m_domain.str();
  551. }
  552. virtual const char* getAuthMethod()
  553. {
  554. return m_authmethod.str();
  555. }
  556. virtual const char* getUserBasedn()
  557. {
  558. return m_user_basedn.str();
  559. }
  560. virtual const char* getGroupBasedn()
  561. {
  562. return m_group_basedn.str();
  563. }
  564. virtual const char* getViewBasedn()
  565. {
  566. return m_view_basedn.str();
  567. }
  568. virtual const char* getResourceBasedn(SecResourceType rtype)
  569. {
  570. if(rtype == RT_DEFAULT || rtype == RT_MODULE || rtype == RT_SERVICE)
  571. return m_resource_basedn.str();
  572. else if(rtype == RT_FILE_SCOPE)
  573. return m_filescope_basedn.str();
  574. else if(rtype == RT_VIEW_SCOPE)
  575. return m_view_basedn.str();
  576. else if(rtype == RT_WORKUNIT_SCOPE)
  577. return m_workunitscope_basedn.str();
  578. else if(rtype == RT_SUDOERS)
  579. return m_sudoers_basedn.str();
  580. else
  581. return m_resource_basedn.str();
  582. }
  583. virtual const char* getTemplateName()
  584. {
  585. return m_template_name.str();
  586. }
  587. virtual const char* getSysUser()
  588. {
  589. return m_sysuser.str();
  590. }
  591. virtual const char* getSysUserDn()
  592. {
  593. return m_sysuser_dn.str();
  594. }
  595. virtual const char* getSysUserCommonName()
  596. {
  597. return m_sysuser_commonname.str();
  598. }
  599. virtual const char* getSysUserPassword()
  600. {
  601. return m_sysuser_password.str();
  602. }
  603. virtual const char* getSysUserBasedn()
  604. {
  605. return m_sysuser_basedn.str();
  606. }
  607. virtual bool sysuserSpecified()
  608. {
  609. return m_sysuser_specified;
  610. }
  611. virtual int getMaxConnections()
  612. {
  613. return m_maxConnections;
  614. }
  615. // For now, only sets default resourcebasedn, since it's only used by ESP services
  616. virtual void setResourceBasedn(const char* rbasedn, SecResourceType rtype)
  617. {
  618. if(rbasedn == NULL || rbasedn[0] == '\0')
  619. return;
  620. if(rtype == RT_DEFAULT || rtype == RT_MODULE || rtype == RT_SERVICE)
  621. {
  622. LdapUtils::normalizeDn(rbasedn, m_basedn.str(), m_resource_basedn);
  623. }
  624. else if(rtype == RT_FILE_SCOPE)
  625. {
  626. LdapUtils::normalizeDn(rbasedn, m_basedn.str(), m_filescope_basedn);
  627. }
  628. else if(rtype == RT_VIEW_SCOPE)
  629. {
  630. LdapUtils::normalizeDn(rbasedn, m_basedn.str(), m_view_basedn);
  631. }
  632. else if(rtype == RT_WORKUNIT_SCOPE)
  633. {
  634. LdapUtils::normalizeDn(rbasedn, m_basedn.str(), m_workunitscope_basedn);
  635. }
  636. else
  637. {
  638. LdapUtils::normalizeDn(rbasedn, m_basedn.str(), m_resource_basedn);
  639. }
  640. }
  641. virtual void getDefaultSysUserBasedn(StringBuffer& sysuser_basedn)
  642. {
  643. if(m_serverType == ACTIVE_DIRECTORY)
  644. LdapUtils::normalizeDn( "cn=Users", m_basedn.str(), sysuser_basedn);
  645. else if(m_serverType == IPLANET)
  646. sysuser_basedn.append("ou=administrators,ou=topologymanagement,o=netscaperoot");
  647. }
  648. virtual int getLdapTimeout()
  649. {
  650. return m_timeout;
  651. }
  652. virtual bool isAzureAD()
  653. {
  654. return m_isAzureAD;
  655. }
  656. };
  657. class CLdapConnection : implements ILdapConnection, public CInterface
  658. {
  659. private:
  660. LDAP *m_ld;
  661. Owned<CLdapConfig> m_ldapconfig;
  662. time_t m_lastaccesstime;
  663. bool m_connected;
  664. bool m_useSSL;
  665. public:
  666. IMPLEMENT_IINTERFACE
  667. CLdapConnection(CLdapConfig* ldapconfig)
  668. {
  669. m_ldapconfig.setown(LINK(ldapconfig));
  670. m_ld = NULL;
  671. m_connected = false;
  672. m_lastaccesstime = 0;
  673. m_useSSL = false;
  674. }
  675. ~CLdapConnection()
  676. {
  677. if(m_ld != NULL)
  678. {
  679. LDAP_UNBIND(m_ld);
  680. }
  681. }
  682. private:
  683. virtual int connect(const char* ldapserver, const char* protocol)
  684. {
  685. if(!ldapserver || *ldapserver == '\0')
  686. return -1;
  687. m_ld = LdapUtils::LdapInit(protocol, ldapserver, m_ldapconfig->getLdapPort(), m_ldapconfig->getLdapSecurePort());
  688. int rc = LDAP_SUCCESS;
  689. if(m_ldapconfig->sysuserSpecified())
  690. rc = LdapUtils::LdapBind(m_ld, m_ldapconfig->getLdapTimeout(), m_ldapconfig->getDomain(), m_ldapconfig->getSysUser(), m_ldapconfig->getSysUserPassword(), m_ldapconfig->getSysUserDn(), m_ldapconfig->getServerType(), m_ldapconfig->getAuthMethod());
  691. else
  692. rc = LdapUtils::LdapBind(m_ld, m_ldapconfig->getLdapTimeout(), m_ldapconfig->getDomain(), NULL, NULL, NULL, m_ldapconfig->getServerType(), m_ldapconfig->getAuthMethod());
  693. if(rc == LDAP_SUCCESS)
  694. {
  695. time(&m_lastaccesstime);
  696. m_connected = true;
  697. const char * ldap = NULL;
  698. switch (m_ldapconfig->getServerType())
  699. {
  700. case ACTIVE_DIRECTORY:
  701. ldap = "Active Directory";
  702. break;
  703. case OPEN_LDAP:
  704. ldap = "OpenLDAP";
  705. break;
  706. case IPLANET:
  707. ldap = "iplanet";
  708. break;
  709. default:
  710. ldap = "unknown";
  711. break;
  712. }
  713. DBGLOG("Connected to '%s' LdapServer %s using protocol %s", ldap, ldapserver, protocol);
  714. }
  715. else
  716. {
  717. DBGLOG("LDAP: sysuser bind failed - %s", ldap_err2string(rc));
  718. LDAP_UNBIND(m_ld);
  719. m_ld = NULL;
  720. }
  721. return rc;
  722. }
  723. public:
  724. virtual bool connect(bool force_ssl = false)
  725. {
  726. const char* proto;
  727. if(force_ssl)
  728. {
  729. proto = "ldaps";
  730. m_useSSL = true;
  731. }
  732. else
  733. {
  734. proto = m_ldapconfig->getProtocol();//get configured protocol, LDAP or LDAPS
  735. m_useSSL = (0 == stricmp(proto, "ldaps") ? true : false);
  736. }
  737. int rc = LDAP_SERVER_DOWN;//assume bad things
  738. StringBuffer hostbuf;
  739. for (int numHosts=0; numHosts < m_ldapconfig->getHostCount(); numHosts++)
  740. {
  741. m_ldapconfig->getLdapHost(hostbuf);
  742. for(int retries = 0; retries <= LDAPSEC_MAX_RETRIES; retries++)
  743. {
  744. rc = connect(hostbuf.str(), proto);
  745. if(!LdapServerDown(rc) || retries > LDAPSEC_MAX_RETRIES)
  746. break;
  747. sleep(LDAPSEC_RETRY_WAIT);
  748. if(retries < LDAPSEC_MAX_RETRIES)
  749. DBGLOG("Server temporarily unreachable, retrying ...");
  750. }
  751. if(rc == LDAP_SERVER_DOWN)
  752. {
  753. StringBuffer dc;
  754. LdapUtils::getDcName(m_ldapconfig->getDomain(), dc);
  755. if(dc.length() > 0)
  756. {
  757. WARNLOG("Using automatically obtained LDAP Server %s", dc.str());
  758. rc = connect(dc.str(), proto);
  759. }
  760. }
  761. if (rc != LDAP_SUCCESS)
  762. {
  763. m_ldapconfig->rejectHost(hostbuf);
  764. }
  765. else
  766. break;
  767. }
  768. if(rc == LDAP_SUCCESS)
  769. return true;
  770. else
  771. return false;
  772. }
  773. virtual LDAP* getLd()
  774. {
  775. return m_ld;
  776. }
  777. virtual bool validate()
  778. {
  779. time_t now;
  780. time(&now);
  781. if(!m_connected)
  782. return connect();
  783. else if(now - m_lastaccesstime <= 300)
  784. return true;
  785. else
  786. {
  787. LDAPMessage* msg = NULL;
  788. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  789. int err = ldap_search_ext_s(m_ld, NULL, LDAP_SCOPE_BASE, "objectClass=*", NULL, 0, NULL, NULL, &timeOut, 1, &msg);
  790. if(msg != NULL)
  791. ldap_msgfree(msg);
  792. if(err != LDAP_SUCCESS)
  793. {
  794. if(m_ld != NULL)
  795. {
  796. LDAP_UNBIND(m_ld);
  797. m_ld = NULL;
  798. m_connected = false;
  799. }
  800. DBGLOG("cached connection invalid (%s), creating a new connection", ldap_err2string(err));
  801. return connect(m_useSSL);//reconnect stale connection, using original protocol
  802. }
  803. else
  804. {
  805. time(&m_lastaccesstime);
  806. }
  807. }
  808. return true;
  809. }
  810. };
  811. class CLdapConnectionPool : implements ILdapConnectionPool, public CInterface
  812. {
  813. private:
  814. int m_maxsize;
  815. int m_currentsize;
  816. IArrayOf<ILdapConnection> m_connections;
  817. Monitor m_monitor;
  818. Owned<CLdapConfig> m_ldapconfig;
  819. public:
  820. IMPLEMENT_IINTERFACE
  821. CLdapConnectionPool(CLdapConfig* ldapconfig)
  822. {
  823. m_ldapconfig.setown(LINK(ldapconfig));
  824. m_maxsize = m_ldapconfig->getMaxConnections();
  825. m_currentsize = 0;
  826. // Set LDAP version to 3
  827. int version = LDAP_VERSION3;
  828. ldap_set_option( NULL, LDAP_OPT_PROTOCOL_VERSION, &version);
  829. }
  830. virtual ILdapConnection* getConnection()
  831. {
  832. synchronized block(m_monitor);
  833. ForEachItemIn(x, m_connections)
  834. {
  835. CLdapConnection* curcon = (CLdapConnection*)&(m_connections.item(x));
  836. if(curcon != NULL && !curcon->IsShared())
  837. {
  838. //DBGLOG("Reusing an LDAP connection");
  839. if(curcon->validate())
  840. return LINK(curcon);
  841. else
  842. throw MakeStringException(-1, "Connecting/authenticating to ldap server in re-validation failed");
  843. }
  844. }
  845. //DBGLOG("Creating new connection");
  846. CLdapConnection* newcon = new CLdapConnection(m_ldapconfig.get());
  847. if(newcon != NULL)
  848. {
  849. if(!newcon->connect())
  850. {
  851. throw MakeStringException(-1, "Connecting/authenticating to ldap server failed");
  852. }
  853. if(m_currentsize <= m_maxsize)
  854. {
  855. m_connections.append(*newcon);
  856. m_currentsize++;
  857. return LINK(newcon);
  858. }
  859. else
  860. {
  861. return newcon;
  862. }
  863. }
  864. else
  865. {
  866. throw MakeStringException(-1, "Failed to create new ldap connection");
  867. }
  868. }
  869. virtual ILdapConnection* getSSLConnection()
  870. {
  871. CLdapConnection* newcon = new CLdapConnection(m_ldapconfig.get());
  872. if(newcon != NULL)
  873. {
  874. if(!newcon->connect(true))
  875. {
  876. throw MakeStringException(-1, "Connecting/authenticating to ldap server via ldaps failed");
  877. }
  878. return newcon;
  879. }
  880. else
  881. {
  882. throw MakeStringException(-1, "Failed to create new ldap connection");
  883. }
  884. }
  885. };
  886. #define LDAP_CONNECTION_TIMEOUT INFINITE
  887. //------------ New Connection Pool Implementation ------------//
  888. class CLdapConnectionManager : implements IResourceFactory<CLdapConnection>, public CInterface
  889. {
  890. Owned<CLdapConfig> m_ldapconfig;
  891. public:
  892. IMPLEMENT_IINTERFACE;
  893. CLdapConnectionManager(CLdapConfig* ldapconfig)
  894. {
  895. m_ldapconfig.setown(LINK(ldapconfig));
  896. }
  897. CLdapConnection* createResource()
  898. {
  899. CLdapConnection* newcon = new CLdapConnection(m_ldapconfig.get());
  900. if(newcon != NULL)
  901. {
  902. if(!newcon->connect())
  903. {
  904. throw MakeStringException(-1, "Connecting/authenticating to ldap server failed");
  905. }
  906. return newcon;
  907. }
  908. else
  909. {
  910. throw MakeStringException(-1, "Failed to create new ldap connection");
  911. }
  912. }
  913. };
  914. class CLdapConnectionPool2 : implements ILdapConnectionPool, public CInterface
  915. {
  916. private:
  917. int m_maxsize;
  918. Owned<CLdapConfig> m_ldapconfig;
  919. Owned<CResourcePool<CLdapConnection> > m_connections;
  920. public:
  921. IMPLEMENT_IINTERFACE
  922. CLdapConnectionPool2(CLdapConfig* ldapconfig)
  923. {
  924. m_ldapconfig.setown(LINK(ldapconfig));
  925. m_maxsize = m_ldapconfig->getMaxConnections();
  926. // Set LDAP version to 3
  927. int version = LDAP_VERSION3;
  928. ldap_set_option( NULL, LDAP_OPT_PROTOCOL_VERSION, &version);
  929. m_connections.setown(new CResourcePool<CLdapConnection>);
  930. Owned<CLdapConnectionManager> poolMgr = new CLdapConnectionManager(ldapconfig);
  931. m_connections->init(m_maxsize, poolMgr.get());
  932. }
  933. virtual ILdapConnection* getConnection()
  934. {
  935. Owned<CLdapConnection> con;
  936. try
  937. {
  938. con.setown(m_connections->get(LDAP_CONNECTION_TIMEOUT));
  939. }
  940. catch(IException* e)
  941. {
  942. StringBuffer emsg;
  943. e->errorMessage(emsg);
  944. DBGLOG("getConnection exception - %s", emsg.str());
  945. e->Release();
  946. }
  947. catch(...)
  948. {
  949. DBGLOG("getConnection unknown exception");
  950. }
  951. if(con.get())
  952. {
  953. if(con->validate())
  954. return con.getLink();
  955. else
  956. throw MakeStringException(-1, "Connecting/authenticating to ldap server in re-validation failed");
  957. }
  958. else
  959. throw MakeStringException(-1, "Failed to get an LDAP Connection.");
  960. }
  961. virtual ILdapConnection* getSSLConnection()
  962. {
  963. CLdapConnection* newcon = new CLdapConnection(m_ldapconfig.get());
  964. if(newcon != NULL)
  965. {
  966. if(!newcon->connect(true))
  967. {
  968. throw MakeStringException(-1, "Connecting/authenticating to ldap server via ldaps failed");
  969. }
  970. return newcon;
  971. }
  972. else
  973. {
  974. throw MakeStringException(-1, "Failed to create new ldap connection");
  975. }
  976. }
  977. };
  978. struct ltstr
  979. {
  980. bool operator()(const char* s1, const char* s2) const { return strcmp(s1, s2) < 0; }
  981. };
  982. //--------------------------------------------
  983. // This helper class ensures memory allocate by calls
  984. // to ldap_first_attribute/ldap_next_attribute gets freed
  985. //--------------------------------------------
  986. class CLDAPGetAttributesWrapper
  987. {
  988. private:
  989. LDAP * ld;
  990. LDAPMessage * entry;
  991. BerElement * elem;
  992. char * attribute;
  993. public:
  994. CLDAPGetAttributesWrapper(LDAP * _ld, LDAPMessage * _entry)
  995. : ld(_ld), entry(_entry)
  996. {
  997. elem = NULL;
  998. attribute = NULL;
  999. }
  1000. ~CLDAPGetAttributesWrapper()
  1001. {
  1002. if (attribute)
  1003. ldap_memfree(attribute);
  1004. if (elem)
  1005. ber_free(elem, 0);
  1006. }
  1007. inline char * getFirst()
  1008. {
  1009. return attribute = ldap_first_attribute(ld, entry, &elem);
  1010. }
  1011. inline char * getNext()
  1012. {
  1013. if (attribute)
  1014. ldap_memfree(attribute);
  1015. return attribute = ldap_next_attribute(ld, entry, elem);
  1016. }
  1017. };
  1018. class CLDAPMessage
  1019. {
  1020. public:
  1021. LDAPMessage *msg;
  1022. CLDAPMessage() { msg = NULL; }
  1023. ~CLDAPMessage() { ldapMsgFree(); }
  1024. inline void ldapMsgFree() { if (msg) { ldap_msgfree(msg); msg = NULL;} }
  1025. inline operator LDAPMessage *() const { return msg; }
  1026. };
  1027. //------------------------------------------------------
  1028. // class CPagedLDAPSearch
  1029. //
  1030. // Performs a "paged" LDAP search, which allows for
  1031. // searching when there are over 1000 matching entries. Also
  1032. // works when there are less than 1000, but not as efficient as
  1033. // simply calling ldap_search_ext_s()
  1034. //------------------------------------------------------
  1035. #define MAX_ENTRIES 1000
  1036. class CPagedLDAPSearch
  1037. {
  1038. private:
  1039. LDAP * m_pLdapConn;
  1040. char * m_pszDN;
  1041. unsigned long m_scope;
  1042. char * m_pszFilter;
  1043. char * * m_pszAttrs;
  1044. bool m_morePages;
  1045. struct berval * m_pCookie;
  1046. LDAPMessage * m_pPageEntry;
  1047. LDAPMessage * m_pPageBlock;
  1048. int m_timeout;
  1049. //local helper class, ensures ldap Page Control memory freed
  1050. class CPageControlMemWrapper
  1051. {
  1052. LDAPControl * m_pageControl;
  1053. LDAPControl ** m_returnedCtrls;
  1054. public:
  1055. CPageControlMemWrapper() { m_pageControl = NULL; m_returnedCtrls = NULL; }
  1056. void setPageControl(LDAPControl * _pageCtrl) { m_pageControl = _pageCtrl; }
  1057. void setRetControls(LDAPControl ** _retCtrls) { m_returnedCtrls = _retCtrls; }
  1058. virtual ~CPageControlMemWrapper()
  1059. {
  1060. if (m_pageControl)
  1061. ldap_control_free(m_pageControl);
  1062. if (m_returnedCtrls)
  1063. ldap_controls_free(m_returnedCtrls);
  1064. }
  1065. };
  1066. //---------------------------------------------------
  1067. // Request next page of search results
  1068. //---------------------------------------------------
  1069. bool requestNextPage()
  1070. {
  1071. if (!m_morePages)
  1072. return false;
  1073. CPageControlMemWrapper pageCtrlMem;
  1074. TIMEVAL timeOut = {m_timeout,0};
  1075. try
  1076. {
  1077. #ifdef LDAP_API_FEATURE_PAGED_RESULTS
  1078. LDAPControl * pageControl = NULL;
  1079. int rc = ldap_create_page_control(m_pLdapConn, MAX_ENTRIES, m_pCookie, false, &pageControl);//cookie gets set on first call to ldap_parse_page_control()
  1080. if (rc != LDAP_SUCCESS)
  1081. {
  1082. int err = GetLastError();
  1083. throw MakeStringException(-1, "ldap_create_page_control failed with 0x%x (%s)",err, ldap_err2string( err ));
  1084. }
  1085. pageCtrlMem.setPageControl(pageControl);
  1086. LDAPControl * svrCtrls[] = { pageControl, NULL };
  1087. if (m_pPageBlock)
  1088. ldap_msgfree(m_pPageBlock);
  1089. rc = ldap_search_ext_s(m_pLdapConn, m_pszDN, m_scope, m_pszFilter, m_pszAttrs, 0, svrCtrls, NULL, &timeOut, 0, &m_pPageBlock);
  1090. if (rc != LDAP_SUCCESS)
  1091. {
  1092. if (rc == LDAP_NO_SUCH_OBJECT)
  1093. {
  1094. if (m_pCookie)
  1095. {
  1096. ber_bvfree(m_pCookie);
  1097. m_pCookie = NULL;
  1098. }
  1099. #ifdef _DEBUG
  1100. DBGLOG("CPagedLDAPSearch::requestNextPage: ldap_search_ext_s() : No Such Object : DN=%s", m_pszDN);
  1101. #endif
  1102. return false;
  1103. }
  1104. int err = GetLastError();
  1105. if (err && rc != LDAP_PARTIAL_RESULTS)//389DirectoryServer sometimes returns rc, but GetLastError returns 0. In this scenario continuing the query succeeds
  1106. {
  1107. if (m_pCookie)
  1108. {
  1109. ber_bvfree(m_pCookie);
  1110. m_pCookie = NULL;
  1111. }
  1112. throw MakeStringException(-1, "ldap_search_ext_s failed with 0x%x (%s)",err, ldap_err2string( err ));
  1113. }
  1114. if (!m_pPageBlock)
  1115. {
  1116. if (m_pCookie)
  1117. {
  1118. ber_bvfree(m_pCookie);
  1119. m_pCookie = NULL;
  1120. }
  1121. m_morePages = false;
  1122. DBGLOG("CPagedLDAPSearch::requestNextPage: ldap_search_ext_s() returns SUCCESS with no result.");
  1123. return false;
  1124. }
  1125. }
  1126. unsigned long l_errcode;
  1127. LDAPControl ** returnedCtrls = NULL;
  1128. #ifdef _WIN32
  1129. rc = ldap_parse_result(m_pLdapConn, m_pPageBlock, &l_errcode, NULL, NULL, NULL, &returnedCtrls, false);
  1130. #else
  1131. rc = ldap_parse_result(m_pLdapConn, m_pPageBlock, (int*)&l_errcode, NULL, NULL, NULL, &returnedCtrls, false);
  1132. #endif
  1133. if (m_pCookie)
  1134. {
  1135. ber_bvfree(m_pCookie);
  1136. m_pCookie = NULL;
  1137. }
  1138. if (rc != LDAP_SUCCESS)
  1139. {
  1140. int err = GetLastError();
  1141. if (err)
  1142. {
  1143. throw MakeStringException(-1, "ldap_parse_result failed with 0x%x (%s)",err, ldap_err2string( err ));
  1144. }
  1145. else
  1146. {
  1147. DBGLOG("ldap_parse_result returned unexpected rc=%x, err=%x, ignoring",rc,err);
  1148. }
  1149. }
  1150. pageCtrlMem.setRetControls(returnedCtrls);
  1151. unsigned long totCount;
  1152. #ifdef _WIN32
  1153. rc = ldap_parse_page_control(m_pLdapConn, returnedCtrls, &totCount, &m_pCookie);//sets cookie for next call to ldap_create_page_control()
  1154. #else
  1155. rc = ldap_parse_page_control(m_pLdapConn, returnedCtrls, (int*)&totCount, &m_pCookie);//sets cookie for next call to ldap_create_page_control()
  1156. #endif
  1157. if (rc != LDAP_SUCCESS)
  1158. {
  1159. int err = GetLastError();
  1160. if (err)
  1161. {
  1162. throw MakeStringException(-1, "ldap_parse_page_control failed with 0x%x (%s)",err, ldap_err2string( err ));
  1163. }
  1164. else
  1165. {
  1166. DBGLOG("ldap_parse_page_control returned unexpected rc=%x, err=%x, ignoring",rc,err);
  1167. }
  1168. }
  1169. if (!(m_pCookie && m_pCookie->bv_val != NULL && (strlen(m_pCookie->bv_val) > 0)))
  1170. m_morePages = false;
  1171. #else
  1172. int rc = ldap_search_ext_s(m_pLdapConn, m_pszDN, m_scope, m_pszFilter, m_pszAttrs, 0, NULL, NULL, &timeOut, 0, &m_pPageBlock);
  1173. m_morePages = false;
  1174. if (rc != LDAP_SUCCESS)
  1175. {
  1176. throw MakeStringException(-1, "ldap_search_ext_s failed with 0x%x (%s)",rc, ldap_err2string( rc ));
  1177. }
  1178. #endif
  1179. }
  1180. catch(IException* e)
  1181. {
  1182. StringBuffer emsg;
  1183. e->errorMessage(emsg);
  1184. throw MakeStringException(-1, "LDAP Paged Search - %s", emsg.str());
  1185. }
  1186. catch(...)
  1187. {
  1188. throw MakeStringException(-1, "Unknown Exception calling LDAP Paged Search");
  1189. }
  1190. return true;
  1191. }
  1192. public:
  1193. CPagedLDAPSearch(LDAP* _pLdapConn, int _timeout, char * _pszDN, unsigned long _scope, char * _pszFilter, char * _pszAttrs[])
  1194. {
  1195. m_pLdapConn =_pLdapConn;
  1196. m_pszDN = _pszDN;
  1197. m_timeout = _timeout;
  1198. m_scope = _scope;
  1199. m_pszFilter = _pszFilter;
  1200. m_pszAttrs = _pszAttrs;
  1201. m_pCookie = NULL;
  1202. m_morePages = true;
  1203. m_pPageEntry = NULL;
  1204. m_pPageBlock = NULL;
  1205. }
  1206. virtual ~CPagedLDAPSearch()
  1207. {
  1208. if (m_pPageBlock)
  1209. ldap_msgfree(m_pPageBlock);
  1210. if (m_pCookie)
  1211. ber_bvfree(m_pCookie);
  1212. }
  1213. //---------------------------------------------------
  1214. // Returns the count of the matching DN/filter/scope entries
  1215. //---------------------------------------------------
  1216. unsigned countEntries()
  1217. {
  1218. unsigned count = 0;
  1219. while (requestNextPage())
  1220. count += ldap_count_entries(m_pLdapConn, m_pPageBlock);
  1221. return count;
  1222. }
  1223. //---------------------------------------------------
  1224. // Get the first/next entry
  1225. // Returns NULL when no more
  1226. //---------------------------------------------------
  1227. LDAPMessage * getFirstEntry()
  1228. {
  1229. if (!requestNextPage())
  1230. {
  1231. m_morePages = false;
  1232. return NULL;
  1233. }
  1234. return getNextEntry();
  1235. }
  1236. LDAPMessage * getNextEntry()
  1237. {
  1238. if (!m_pPageEntry)
  1239. m_pPageEntry = LdapFirstEntry(m_pLdapConn, m_pPageBlock);
  1240. else
  1241. m_pPageEntry = LdapNextEntry(m_pLdapConn, m_pPageEntry);
  1242. if (!m_pPageEntry)
  1243. {
  1244. if (!requestNextPage())
  1245. return NULL;
  1246. m_pPageEntry = LdapFirstEntry(m_pLdapConn, m_pPageBlock);
  1247. }
  1248. return m_pPageEntry;
  1249. }
  1250. };
  1251. static CriticalSection mpaCrit;
  1252. static __int64 getMaxPwdAge(Owned<ILdapConnectionPool> _conns, const char * _baseDN, int _timeout)
  1253. {
  1254. static time_t lastPwdAgeCheck = 0;
  1255. static __int64 maxPwdAge = PWD_NEVER_EXPIRES;
  1256. #define HOURLY ((time_t)(60*60*1000))
  1257. CriticalBlock block(mpaCrit);
  1258. if (lastPwdAgeCheck != 0 && (((msTick() - lastPwdAgeCheck) < HOURLY)))//in case it was retrieved whilst this thread blocked
  1259. return maxPwdAge;
  1260. DBGLOG("Retrieving LDAP 'maxPwdAge'");
  1261. char* attrs[] = {"maxPwdAge", NULL};
  1262. CLDAPMessage searchResult;
  1263. TIMEVAL timeOut = {_timeout,0};
  1264. Owned<ILdapConnection> lconn = _conns->getConnection();
  1265. LDAP* sys_ld = lconn.get()->getLd();
  1266. int result = ldap_search_ext_s(sys_ld, (char*)_baseDN, LDAP_SCOPE_BASE, NULL,
  1267. attrs, 0, NULL, NULL, &timeOut, LDAP_NO_LIMIT, &searchResult.msg);
  1268. if(result != LDAP_SUCCESS)
  1269. {
  1270. DBGLOG("ldap_search_ext_s error: %s, when searching maxPwdAge", ldap_err2string( result ));
  1271. return 0;
  1272. }
  1273. unsigned entries = ldap_count_entries(sys_ld, searchResult);
  1274. if(entries == 0)
  1275. {
  1276. DBGLOG("ldap_search_ext_s error: Could not find maxPwdAge");
  1277. return 0;
  1278. }
  1279. maxPwdAge = 0;
  1280. CLDAPGetValuesLenWrapper vals(sys_ld, searchResult.msg, "maxPwdAge");
  1281. if (vals.hasValues())
  1282. {
  1283. const char *val = vals.queryCharValue(0);
  1284. if (val && *val)
  1285. {
  1286. if (*val == '-')
  1287. ++val;
  1288. for (int x=0; val[x]; x++)
  1289. maxPwdAge = maxPwdAge * 10 + ( (int)val[x] - '0');
  1290. }
  1291. }
  1292. else
  1293. maxPwdAge = PWD_NEVER_EXPIRES;
  1294. lastPwdAgeCheck = msTick();
  1295. return maxPwdAge;
  1296. }
  1297. static CriticalSection lcCrit;
  1298. class CLdapClient : implements ILdapClient, public CInterface
  1299. {
  1300. private:
  1301. Owned<ILdapConnectionPool> m_connections;
  1302. IPermissionProcessor* m_pp;
  1303. //int m_defaultFileScopePermission;
  1304. //int m_defaultWorkunitScopePermission;
  1305. Owned<CLdapConfig> m_ldapconfig;
  1306. StringBuffer m_pwscheme;
  1307. bool m_domainPwdsNeverExpire;//no domain policy for password expiration
  1308. struct MemoryAttrItem : public CInterface, public MemoryAttr
  1309. {
  1310. MemoryAttrItem() : MemoryAttr() {}
  1311. MemoryAttrItem(unsigned len, const void * ptr) : MemoryAttr(len, ptr) {}
  1312. };
  1313. ReadWriteLock m_unknownSIDCacheLock;
  1314. CIArrayOf<MemoryAttrItem> m_unknownSIDCache;//cache Security Identifier Structure (SID) of previously deleted/orphaned LDAP objects
  1315. public:
  1316. IMPLEMENT_IINTERFACE
  1317. CLdapClient(IPropertyTree* cfg)
  1318. {
  1319. m_ldapconfig.setown(new CLdapConfig(cfg));
  1320. if(cfg && cfg->getPropBool("@useRealConnectionPool", false))
  1321. m_connections.setown(new CLdapConnectionPool2(m_ldapconfig.get()));
  1322. else
  1323. m_connections.setown(new CLdapConnectionPool(m_ldapconfig.get()));
  1324. m_pp = NULL;
  1325. //m_defaultFileScopePermission = -2;
  1326. //m_defaultWorkunitScopePermission = -2;
  1327. m_domainPwdsNeverExpire = false;
  1328. }
  1329. virtual void init(IPermissionProcessor* pp)
  1330. {
  1331. m_pp = pp;
  1332. static bool createdOU = false;
  1333. CriticalBlock block(lcCrit);
  1334. if (!createdOU)
  1335. {
  1336. if(m_ldapconfig->getServerType() == OPEN_LDAP)
  1337. {
  1338. try
  1339. {
  1340. addDC(m_ldapconfig->getBasedn());
  1341. }
  1342. catch(...)
  1343. {
  1344. }
  1345. try
  1346. {
  1347. addGroup("Directory Administrators", NULL, NULL, m_ldapconfig->getBasedn());
  1348. }
  1349. catch(...)
  1350. {
  1351. }
  1352. }
  1353. //Create base LDAP OU tree. Specify PT_ADMINISTRATORS_ONLY to ensure each OU
  1354. //grants access to Administrators only
  1355. createLdapBasedn(NULL, m_ldapconfig->getResourceBasedn(RT_DEFAULT), PT_ADMINISTRATORS_ONLY);
  1356. createLdapBasedn(NULL, m_ldapconfig->getResourceBasedn(RT_FILE_SCOPE), PT_DEFAULT);
  1357. createLdapBasedn(NULL, m_ldapconfig->getResourceBasedn(RT_VIEW_SCOPE), PT_ADMINISTRATORS_ONLY);
  1358. createLdapBasedn(NULL, m_ldapconfig->getResourceBasedn(RT_WORKUNIT_SCOPE), PT_DEFAULT);
  1359. createLdapBasedn(NULL, m_ldapconfig->getResourceBasedn(RT_SUDOERS), PT_ADMINISTRATORS_ONLY);
  1360. createLdapBasedn(NULL, m_ldapconfig->getUserBasedn(), PT_ADMINISTRATORS_ONLY);
  1361. createLdapBasedn(NULL, m_ldapconfig->getGroupBasedn(), PT_ADMINISTRATORS_ONLY);
  1362. createdOU = true;
  1363. }
  1364. }
  1365. virtual LdapServerType getServerType()
  1366. {
  1367. return m_ldapconfig->getServerType();
  1368. }
  1369. virtual ILdapConfig* getLdapConfig()
  1370. {
  1371. return m_ldapconfig.get();
  1372. }
  1373. virtual void setResourceBasedn(const char* rbasedn, SecResourceType rtype)
  1374. {
  1375. m_ldapconfig->setResourceBasedn(rbasedn, rtype);
  1376. createLdapBasedn(NULL, m_ldapconfig->getResourceBasedn(rtype), PT_ADMINISTRATORS_ONLY);
  1377. }
  1378. void calcPWExpiry(CDateTime &dt, unsigned len, char * val)
  1379. {
  1380. __int64 time = 0;
  1381. for (unsigned x=0; x < len; x++)
  1382. time = time * 10 + ( (int)val[x] - '0');
  1383. time += getMaxPwdAge(m_connections,(char*)m_ldapconfig->getBasedn(), m_ldapconfig->getLdapTimeout());
  1384. dt.setFromFILETIME(time);
  1385. dt.adjustTime(dt.queryUtcToLocalDelta());
  1386. }
  1387. virtual bool authenticate(ISecUser& user)
  1388. {
  1389. {
  1390. char *attribute;
  1391. user.setAuthenticateStatus(AS_UNEXPECTED_ERROR);//assume the worst
  1392. const char* username = user.getName();
  1393. const char* password = user.credentials().getPassword();
  1394. if(!username || !*username || !password || !*password)
  1395. {
  1396. DBGLOG("CLdapClient::authenticate username/password must be provided");
  1397. return false;
  1398. }
  1399. if (getMaxPwdAge(m_connections,(char*)m_ldapconfig->getBasedn(), m_ldapconfig->getLdapTimeout()) != PWD_NEVER_EXPIRES)
  1400. m_domainPwdsNeverExpire = false;
  1401. else
  1402. m_domainPwdsNeverExpire = true;
  1403. StringBuffer filter;
  1404. // Retrieve user's dn with system connection
  1405. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  1406. filter.append("sAMAccountName=");
  1407. else
  1408. filter.append("uid=");
  1409. filter.append(username);
  1410. char* attrs[] = {"cn", "userAccountControl", "pwdLastSet", "givenName", "sn", "employeeId", "distinguishedName", "employeeNumber", NULL};
  1411. Owned<ILdapConnection> lconn = m_connections->getConnection();
  1412. LDAP* sys_ld = lconn.get()->getLd();
  1413. CLDAPMessage searchResult;
  1414. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  1415. int result = ldap_search_ext_s(sys_ld,
  1416. (char*)m_ldapconfig->getUserBasedn(), //distinguished name of the entry at which to start the search
  1417. LDAP_SCOPE_SUBTREE,
  1418. (char*)filter.str(), //search filter
  1419. attrs,
  1420. 0, //attribute types and values are to be returned, nonzero if only types are required
  1421. NULL,
  1422. NULL,
  1423. &timeOut,
  1424. LDAP_NO_LIMIT,
  1425. &searchResult.msg);
  1426. if(result != LDAP_SUCCESS)
  1427. {
  1428. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( result ), filter.str(), m_ldapconfig->getUserBasedn());
  1429. return false;
  1430. }
  1431. unsigned entries = ldap_count_entries(sys_ld, searchResult);
  1432. if(entries == 0)
  1433. {
  1434. searchResult.ldapMsgFree();
  1435. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  1436. result = ldap_search_ext_s(sys_ld, (char*)m_ldapconfig->getSysUserBasedn(), LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs, 0, NULL, NULL, &timeOut, LDAP_NO_LIMIT, &searchResult.msg);
  1437. if(result != LDAP_SUCCESS)
  1438. {
  1439. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( result ), filter.str(), m_ldapconfig->getSysUserBasedn());
  1440. user.setAuthenticateStatus(AS_INVALID_CREDENTIALS);
  1441. return false;
  1442. }
  1443. entries = ldap_count_entries(sys_ld, searchResult);
  1444. if(entries == 0)
  1445. {
  1446. DBGLOG("LDAP: User %s not found", username);
  1447. user.setAuthenticateStatus(AS_INVALID_CREDENTIALS);
  1448. return false;
  1449. }
  1450. }
  1451. LDAPMessage *entry = LdapFirstEntry(sys_ld, searchResult);
  1452. if(entry == NULL)
  1453. {
  1454. DBGLOG("LDAP: Can't find entry for user %s", username);
  1455. return false;
  1456. }
  1457. bool accountPwdNeverExpires = false;
  1458. CLDAPGetAttributesWrapper atts(sys_ld, searchResult);
  1459. for ( attribute = atts.getFirst();
  1460. attribute != NULL;
  1461. attribute = atts.getNext())
  1462. {
  1463. if(stricmp(attribute, "cn") == 0)
  1464. {
  1465. CLDAPGetValuesLenWrapper vals(sys_ld, entry, attribute);
  1466. if (vals.hasValues())
  1467. user.setFullName(vals.queryCharValue(0));
  1468. }
  1469. else if((stricmp(attribute, "givenName") == 0))
  1470. {
  1471. CLDAPGetValuesLenWrapper vals(sys_ld, entry, attribute);
  1472. if (vals.hasValues())
  1473. user.setFirstName(vals.queryCharValue(0));
  1474. }
  1475. else if((stricmp(attribute, "sn") == 0))
  1476. {
  1477. CLDAPGetValuesLenWrapper vals(sys_ld, entry, attribute);
  1478. if (vals.hasValues())
  1479. user.setLastName(vals.queryCharValue(0));
  1480. }
  1481. else if((stricmp(attribute, "userAccountControl") == 0))
  1482. {
  1483. //UF_DONT_EXPIRE_PASSWD 0x10000
  1484. CLDAPGetValuesLenWrapper vals(sys_ld, entry, attribute);
  1485. if (vals.hasValues())
  1486. if (atoi((char*)vals.queryCharValue(0)) & 0x10000)//this can be true at the account level, even if domain policy requires password
  1487. accountPwdNeverExpires = true;
  1488. }
  1489. else if((stricmp(attribute, "pwdLastSet") == 0))
  1490. {
  1491. /*pwdLastSet is the date and time that the password for this account was last changed. This
  1492. value is stored as a large integer that represents the number of 100 nanosecond intervals
  1493. since January 1, 1601 (UTC), also known as a FILETIME value. If this value is set
  1494. to 0 and the User-Account-Control attribute does not contain the UF_DONT_EXPIRE_PASSWD
  1495. flag, then the user must set the password at the next logon.
  1496. */
  1497. CLDAPGetValuesLenWrapper valsLen(sys_ld, entry, attribute);
  1498. if (valsLen.hasValues())
  1499. {
  1500. CDateTime expiry;
  1501. if (!m_domainPwdsNeverExpire && !accountPwdNeverExpires)
  1502. {
  1503. char * val = (char*)valsLen.queryCharValue(0);
  1504. calcPWExpiry(expiry, (unsigned)strlen(val), val);
  1505. }
  1506. else
  1507. {
  1508. expiry.clear();
  1509. DBGLOG("LDAP: Password never expires for user %s", username);
  1510. }
  1511. user.setPasswordExpiration(expiry);
  1512. }
  1513. }
  1514. else if(stricmp(attribute, "employeeId") == 0)
  1515. {
  1516. CLDAPGetValuesLenWrapper vals(sys_ld, entry, attribute);
  1517. if (vals.hasValues())
  1518. user.setEmployeeID(vals.queryCharValue(0));
  1519. }
  1520. else if(stricmp(attribute, "employeeNumber") == 0)
  1521. {
  1522. CLDAPGetValuesLenWrapper vals(sys_ld, entry, attribute);
  1523. if (vals.hasValues())
  1524. user.setEmployeeNumber(vals.queryCharValue(0));
  1525. }
  1526. else if(stricmp(attribute, "distinguishedName") == 0)
  1527. {
  1528. CLDAPGetValuesLenWrapper vals(sys_ld, entry, attribute);
  1529. if (vals.hasValues())
  1530. user.setDistinguishedName(vals.queryCharValue(0));
  1531. }
  1532. }
  1533. char *userdn = ldap_get_dn(sys_ld, entry);
  1534. if(userdn == NULL || strlen(userdn) == 0)
  1535. {
  1536. DBGLOG("LDAP: dn not found for user %s", username);
  1537. return false;
  1538. }
  1539. StringBuffer userdnbuf;
  1540. userdnbuf.append(userdn);
  1541. ldap_memfree(userdn);
  1542. StringBuffer hostbuf;
  1543. m_ldapconfig->getLdapHost(hostbuf);
  1544. int rc = LDAP_SERVER_DOWN;
  1545. char *ldap_errstring=NULL;
  1546. for(int retries = 0; retries <= LDAPSEC_MAX_RETRIES; retries++)
  1547. {
  1548. DBGLOG("LdapBind for user %s (retries=%d).", username, retries);
  1549. {
  1550. LDAP* user_ld = LdapUtils::LdapInit(m_ldapconfig->getProtocol(), hostbuf.str(), m_ldapconfig->getLdapPort(), m_ldapconfig->getLdapSecurePort());
  1551. rc = LdapUtils::LdapBind(user_ld, m_ldapconfig->getLdapTimeout(), m_ldapconfig->getDomain(), username, password, userdnbuf.str(), m_ldapconfig->getServerType(), m_ldapconfig->getAuthMethod());
  1552. if(rc != LDAP_SUCCESS)
  1553. ldap_get_option(user_ld, LDAP_OPT_ERROR_STRING, &ldap_errstring);
  1554. LDAP_UNBIND(user_ld);
  1555. }
  1556. DBGLOG("finished LdapBind for user %s, rc=%d", username, rc);
  1557. if(!LdapServerDown(rc) || retries > LDAPSEC_MAX_RETRIES)
  1558. break;
  1559. sleep(LDAPSEC_RETRY_WAIT);
  1560. if(retries < LDAPSEC_MAX_RETRIES)
  1561. DBGLOG("Server temporarily unreachable, retrying ...");
  1562. // Retrying next ldap sever, might be the same server
  1563. m_ldapconfig->getLdapHost(hostbuf);
  1564. }
  1565. if(rc == LDAP_SERVER_DOWN)
  1566. {
  1567. StringBuffer dc;
  1568. LdapUtils::getDcName(NULL, dc);
  1569. if(dc.length() > 0)
  1570. {
  1571. WARNLOG("Using automatically obtained LDAP Server %s", dc.str());
  1572. LDAP* user_ld = LdapUtils::LdapInit(m_ldapconfig->getProtocol(), dc.str(), m_ldapconfig->getLdapPort(), m_ldapconfig->getLdapSecurePort());
  1573. rc = LdapUtils::LdapBind(user_ld, m_ldapconfig->getLdapTimeout(), m_ldapconfig->getDomain(), username, password, userdnbuf.str(), m_ldapconfig->getServerType(), m_ldapconfig->getAuthMethod());
  1574. if(rc != LDAP_SUCCESS)
  1575. ldap_get_option(user_ld, LDAP_OPT_ERROR_STRING, &ldap_errstring);
  1576. LDAP_UNBIND(user_ld);
  1577. }
  1578. }
  1579. if(rc != LDAP_SUCCESS)
  1580. {
  1581. if (ldap_errstring && *ldap_errstring && strstr(ldap_errstring, " data "))//if extended error strings are available (they are not in windows clients)
  1582. {
  1583. #ifdef _DEBUG
  1584. DBGLOG("LDAPBIND ERR: RC=%d, - '%s'", rc, ldap_errstring);
  1585. #endif
  1586. if (strstr(ldap_errstring, "data 532"))//80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 532, v1db0.
  1587. {
  1588. DBGLOG("LDAP: Password Expired(1) for user %s", username);
  1589. user.setAuthenticateStatus(AS_PASSWORD_VALID_BUT_EXPIRED);
  1590. }
  1591. else if (strstr(ldap_errstring, "data 773"))//User must reset password "80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 773, v1db1'
  1592. {
  1593. DBGLOG("LDAP: User %s Must Reset Password", username);
  1594. user.setAuthenticateStatus(AS_PASSWORD_VALID_BUT_EXPIRED);
  1595. }
  1596. else if (strstr(ldap_errstring, "data 533"))
  1597. {
  1598. DBGLOG("LDAP: User %s Account Disabled", username);
  1599. user.setAuthenticateStatus(AS_ACCOUNT_DISABLED);
  1600. }
  1601. else if (strstr(ldap_errstring, "data 701"))
  1602. {
  1603. DBGLOG("LDAP: User %s Account Expired", username);
  1604. user.setAuthenticateStatus(AS_ACCOUNT_EXPIRED);
  1605. }
  1606. else if (strstr(ldap_errstring, "data 775"))
  1607. {
  1608. DBGLOG("LDAP: User %s Account Locked Out", username);
  1609. user.setAuthenticateStatus(AS_ACCOUNT_LOCKED);
  1610. }
  1611. else
  1612. {
  1613. DBGLOG("LDAP: Authentication(1) (%c) for user %s failed - %s", isWorkunitDAToken(password) ? 't' :'f', username, ldap_err2string(rc));
  1614. user.setAuthenticateStatus(AS_INVALID_CREDENTIALS);
  1615. }
  1616. }
  1617. else
  1618. {
  1619. //This path is typical if running ESP on Windows. We have no way
  1620. //to determine if password entered is valid but expired
  1621. if (user.getPasswordDaysRemaining() == scPasswordExpired)
  1622. {
  1623. DBGLOG("LDAP: Password Expired(2) for user %s", username);
  1624. user.setAuthenticateStatus(AS_PASSWORD_EXPIRED);
  1625. }
  1626. else
  1627. {
  1628. DBGLOG("LDAP: Authentication(2) for user %s failed - %s", username, ldap_err2string(rc));
  1629. user.setAuthenticateStatus(AS_INVALID_CREDENTIALS);
  1630. }
  1631. }
  1632. return false;
  1633. }
  1634. user.setAuthenticateStatus(AS_AUTHENTICATED);
  1635. }
  1636. //Always retrieve user info(SID, UID, fullname, etc) for Active Directory, when the user first logs in.
  1637. if((m_ldapconfig->getServerType() == ACTIVE_DIRECTORY) && (m_pp != NULL))
  1638. m_pp->retrieveUserInfo(user);
  1639. return true;
  1640. };
  1641. virtual bool authorize(SecResourceType rtype, ISecUser& user, IArrayOf<ISecResource>& resources, const char * resName = nullptr)
  1642. {
  1643. bool ok = false;
  1644. const char* basedn = m_ldapconfig->getResourceBasedn(rtype);
  1645. if(basedn == NULL || *basedn == '\0')
  1646. {
  1647. DBGLOG("corresponding basedn is not defined for authorize");
  1648. return false;
  1649. }
  1650. const char* username = user.getName();
  1651. if(!username || !*username)
  1652. {
  1653. DBGLOG("CLdapClient::authorize username must be specified");
  1654. return false;
  1655. }
  1656. const char* sysuser = m_ldapconfig->getSysUser();
  1657. if(sysuser && *sysuser && (strcmp(username, sysuser) == 0))
  1658. {
  1659. ForEachItemIn(x, resources)
  1660. {
  1661. ISecResource* res = &resources.item(x);
  1662. if(!res)
  1663. continue;
  1664. if(rtype == RT_MODULE)
  1665. {
  1666. StringBuffer filter;
  1667. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  1668. filter.append("name=");
  1669. else
  1670. filter.append("ou=");
  1671. filter.append(res->getName());
  1672. int count = countEntries(m_ldapconfig->getResourceBasedn(rtype), (char*)filter.str(), 10);
  1673. if(count != 0)
  1674. res->setAccessFlags(SecAccess_Full);
  1675. else
  1676. res->setAccessFlags(SecAccess_Unavailable);
  1677. }
  1678. else
  1679. res->setAccessFlags(SecAccess_Full);
  1680. }
  1681. return true;
  1682. }
  1683. if(rtype == RT_FILE_SCOPE)
  1684. {
  1685. SecAccessFlags defaultFileScopePermission = queryDefaultPermission(user);
  1686. IArrayOf<ISecResource> non_emptylist;
  1687. ForEachItemIn(x, resources)
  1688. {
  1689. ISecResource& res = resources.item(x);
  1690. const char* res_name = res.getName();
  1691. if(res_name == NULL || *res_name == '\0')
  1692. res.setAccessFlags(defaultFileScopePermission); //res.setAccessFlags(m_defaultFileScopePermission);
  1693. else
  1694. non_emptylist.append(*LINK(&res));
  1695. }
  1696. ok = authorizeScope(user, non_emptylist, basedn);
  1697. //if(ok && m_defaultFileScopePermission != -2)
  1698. if(ok && defaultFileScopePermission != UNK_PERM_VALUE)
  1699. {
  1700. ForEachItemIn(x, non_emptylist)
  1701. {
  1702. ISecResource& res = non_emptylist.item(x);
  1703. if(res.getAccessFlags() == -1)
  1704. res.setAccessFlags(defaultFileScopePermission); //res.setAccessFlags(m_defaultFileScopePermission);
  1705. }
  1706. }
  1707. return ok;
  1708. }
  1709. else if(rtype == RT_WORKUNIT_SCOPE)
  1710. {
  1711. SecAccessFlags defaultWorkunitScopePermission = UNK_PERM_VALUE;//init to invalid SecAccessFlags value
  1712. //if(m_defaultWorkunitScopePermission == -2)
  1713. {
  1714. const char* basebasedn = strchr(basedn, ',') + 1;
  1715. StringBuffer baseresource;
  1716. baseresource.append(basebasedn-basedn-4, basedn+3);
  1717. IArrayOf<ISecResource> base_resources;
  1718. base_resources.append(*(new CLdapSecResource(baseresource.str())));
  1719. bool baseok = authorizeScope(user, base_resources, basebasedn);
  1720. if(baseok)
  1721. {
  1722. defaultWorkunitScopePermission = base_resources.item(0).getAccessFlags();//replace UNK_PERM_VALUE with a valid flag
  1723. }
  1724. }
  1725. IArrayOf<ISecResource> non_emptylist;
  1726. ForEachItemIn(x, resources)
  1727. {
  1728. ISecResource& res = resources.item(x);
  1729. const char* res_name = res.getName();
  1730. if(res_name == NULL || *res_name == '\0')
  1731. res.setAccessFlags(defaultWorkunitScopePermission);
  1732. else
  1733. non_emptylist.append(*LINK(&res));
  1734. }
  1735. ok = authorizeScope(user, non_emptylist, basedn);
  1736. if(ok && defaultWorkunitScopePermission != UNK_PERM_VALUE)//if default perm is known, use it
  1737. {
  1738. ForEachItemIn(x, non_emptylist)
  1739. {
  1740. ISecResource& res = non_emptylist.item(x);
  1741. if(res.getAccessFlags() == -1)
  1742. res.setAccessFlags(defaultWorkunitScopePermission);
  1743. }
  1744. }
  1745. return ok;
  1746. }
  1747. else if (rtype == RT_VIEW_SCOPE)
  1748. {
  1749. SecAccessFlags defPerm = queryDefaultPermission(user); //default perm to be applied when no lfn or column provided
  1750. //Get view lfn/col mappings for this view
  1751. assertex(resources.ordinality() > 0);
  1752. assertex(resName && *resName != '\0');
  1753. StringArray viewFiles;
  1754. StringArray viewColumns;
  1755. queryViewColumns(resName, viewFiles, viewColumns);
  1756. unsigned numViewMembers = viewFiles.ordinality();
  1757. assertex(numViewMembers == viewColumns.ordinality());
  1758. StringAttr lfn;
  1759. StringAttr col;
  1760. unsigned fails = 0;
  1761. ForEachItemIn(idx, resources) //Iterate over all resources in list
  1762. {
  1763. ISecResource& res = resources.item(idx);
  1764. assertex(RT_VIEW_SCOPE == res.getResourceType());
  1765. lfn.set(res.getParameter("file"));
  1766. col.set(res.getParameter("column"));
  1767. #ifdef _DEBUG
  1768. DBGLOG("Checking '%s' RT_VIEW_SCOPE for lfn %s, col %s", resName, lfn.str(), col.str());
  1769. #endif
  1770. if (lfn.isEmpty() || col.isEmpty())
  1771. res.setAccessFlags(defPerm);
  1772. else
  1773. {
  1774. //Check LDAP
  1775. res.setAccessFlags(SecAccess_None);
  1776. ++fails;
  1777. for (unsigned vIdx = 0; vIdx < numViewMembers; vIdx++)
  1778. {
  1779. if (0 == stricmp(lfn.str(), viewFiles.item(vIdx)) &&
  1780. 0 == stricmp(col.str(), viewColumns.item(vIdx)))
  1781. {
  1782. res.setAccessFlags(SecAccess_Full);
  1783. --fails;
  1784. break;
  1785. }
  1786. }
  1787. }
  1788. }
  1789. return fails == 0 ? true : false;
  1790. }
  1791. else
  1792. {
  1793. IArrayOf<CSecurityDescriptor> sdlist;
  1794. ForEachItemIn(x, resources)
  1795. {
  1796. ISecResource& res = resources.item(x);
  1797. const char* resourcename = res.getName();
  1798. CSecurityDescriptor* sd = new CSecurityDescriptor(resourcename);
  1799. sdlist.append(*sd);
  1800. }
  1801. getSecurityDescriptors(rtype, sdlist);
  1802. if(m_pp != NULL)
  1803. ok = m_pp->getPermissions(user, sdlist, resources);
  1804. return ok;
  1805. }
  1806. }
  1807. // Returns true if all resources are correctly added, otherwise returns false.
  1808. virtual bool addResources(SecResourceType rtype, ISecUser& user, IArrayOf<ISecResource>& resources, SecPermissionType ptype, const char* basedn)
  1809. {
  1810. bool ret = true;
  1811. for(unsigned i = 0; i < resources.length(); i++)
  1812. {
  1813. ISecResource* resource = &resources.item(i);
  1814. if(resource != NULL)
  1815. {
  1816. bool oneret = addResource(rtype, user, resource, ptype, basedn);
  1817. ret = ret && oneret;
  1818. }
  1819. }
  1820. return ret;
  1821. }
  1822. virtual bool getUserInfo(ISecUser& user, const char* infotype)
  1823. {
  1824. char *attribute;
  1825. LDAPMessage *message;
  1826. const char* username = user.getName();
  1827. if(username == NULL || strlen(username) == 0)
  1828. {
  1829. DBGLOG("LDAP: getUserInfo : username is empty");
  1830. return false;
  1831. }
  1832. if(infotype && stricmp(infotype, "sudoers") == 0)
  1833. {
  1834. CLdapSecUser* ldapuser = dynamic_cast<CLdapSecUser*>(&user);
  1835. if (ldapuser == nullptr)
  1836. {
  1837. throw MakeStringException(-1, "Unable to cast user %s to CLdapSecUser", username);
  1838. }
  1839. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  1840. Owned<ILdapConnection> lconn = m_connections->getConnection();
  1841. LDAP* ld = lconn.get()->getLd();
  1842. StringBuffer filter("sudoUser=");
  1843. filter.append(username);
  1844. char *attrs[] = {"sudoHost", "sudoCommand", "sudoOption", NULL};
  1845. const char* basedn = m_ldapconfig->getResourceBasedn(RT_SUDOERS);
  1846. CLDAPMessage searchResult;
  1847. int rc = ldap_search_ext_s(ld, (char*)basedn, LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs, 0, NULL, NULL, &timeOut, LDAP_NO_LIMIT, &searchResult.msg);
  1848. if ( rc != LDAP_SUCCESS )
  1849. {
  1850. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), basedn);
  1851. ldapuser->setSudoersEnabled(false);
  1852. ldapuser->setInSudoers(false);
  1853. return false;
  1854. }
  1855. ldapuser->setSudoersEnabled(true);
  1856. unsigned entries = ldap_count_entries(ld, searchResult);
  1857. if(entries == 0)
  1858. {
  1859. ldapuser->setInSudoers(false);
  1860. return true;
  1861. }
  1862. message = LdapFirstEntry(ld, searchResult);
  1863. if(message == NULL)
  1864. {
  1865. ldapuser->setInSudoers(false);
  1866. return true;
  1867. }
  1868. ldapuser->setInSudoers(true);
  1869. CLDAPGetAttributesWrapper atts(ld, searchResult);
  1870. for ( attribute = atts.getFirst();
  1871. attribute != NULL;
  1872. attribute = atts.getNext())
  1873. {
  1874. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  1875. if (vals.hasValues())
  1876. {
  1877. if(stricmp(attribute, "sudoHost") == 0)
  1878. ldapuser->setSudoHost(vals.queryCharValue(0));
  1879. else if(stricmp(attribute, "sudoCommand") == 0)
  1880. ldapuser->setSudoCommand(vals.queryCharValue(0));
  1881. else if(stricmp(attribute, "sudoOption") == 0)
  1882. ldapuser->setSudoOption(vals.queryCharValue(0));
  1883. }
  1884. }
  1885. return true;
  1886. }
  1887. else
  1888. {
  1889. StringBuffer filter;
  1890. const char* basedn = m_ldapconfig->getUserBasedn();
  1891. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  1892. {
  1893. filter.append("sAMAccountName=");
  1894. }
  1895. else
  1896. {
  1897. filter.append("uid=");
  1898. if(stricmp(username, m_ldapconfig->getSysUser()) == 0)
  1899. basedn = m_ldapconfig->getSysUserBasedn();
  1900. }
  1901. filter.append(user.getName());
  1902. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  1903. Owned<ILdapConnection> lconn = m_connections->getConnection();
  1904. LDAP* ld = lconn.get()->getLd();
  1905. char *attrs[] = {"cn", "givenName", "sn", "gidnumber", "uidnumber", "homedirectory", "loginshell", "objectClass", "employeeId", "employeeNumber", "distinguishedName", "userAccountControl", "pwdLastSet", NULL};
  1906. CLDAPMessage searchResult;
  1907. int rc = ldap_search_ext_s(ld, (char*)basedn, LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs, 0, NULL, NULL, &timeOut, LDAP_NO_LIMIT, &searchResult.msg );
  1908. if ( rc != LDAP_SUCCESS )
  1909. {
  1910. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), basedn);
  1911. return false;
  1912. }
  1913. bool accountPwdNeverExpires = false;
  1914. ((CLdapSecUser*)&user)->setPosixenabled(false);
  1915. // Go through the search results by checking message types
  1916. for(message = LdapFirstEntry( ld, searchResult); message != NULL; message = ldap_next_entry(ld, message))
  1917. {
  1918. CLDAPGetAttributesWrapper atts(ld, searchResult);
  1919. for ( attribute = atts.getFirst();
  1920. attribute != NULL;
  1921. attribute = atts.getNext())
  1922. {
  1923. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  1924. if (vals.hasValues())
  1925. {
  1926. if(stricmp(attribute, "cn") == 0)
  1927. user.setFullName(vals.queryCharValue(0));
  1928. else if(stricmp(attribute, "givenName") == 0)
  1929. user.setFirstName(vals.queryCharValue(0));
  1930. else if(stricmp(attribute, "sn") == 0)
  1931. user.setLastName(vals.queryCharValue(0));
  1932. else if(stricmp(attribute, "gidnumber") == 0)
  1933. ((CLdapSecUser*)&user)->setGidnumber(vals.queryCharValue(0));
  1934. else if(stricmp(attribute, "uidnumber") == 0)
  1935. ((CLdapSecUser*)&user)->setUidnumber(vals.queryCharValue(0));
  1936. else if(stricmp(attribute, "homedirectory") == 0)
  1937. ((CLdapSecUser*)&user)->setHomedirectory(vals.queryCharValue(0));
  1938. else if(stricmp(attribute, "loginshell") == 0)
  1939. ((CLdapSecUser*)&user)->setLoginshell(vals.queryCharValue(0));
  1940. else if(stricmp(attribute, "distinguishedName") == 0)
  1941. ((CLdapSecUser*)&user)->setDistinguishedName(vals.queryCharValue(0));
  1942. else if((stricmp(attribute, "userAccountControl") == 0))
  1943. {
  1944. //UF_DONT_EXPIRE_PASSWD 0x10000
  1945. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  1946. if (vals.hasValues())
  1947. if (atoi((char*)vals.queryCharValue(0)) & 0x10000)//this can be true at the account level, even if domain policy requires password
  1948. accountPwdNeverExpires = true;
  1949. }
  1950. else if(stricmp(attribute, "pwdLastSet") == 0)
  1951. {
  1952. CLDAPGetValuesLenWrapper valsLen(ld, message, attribute);
  1953. if (!m_domainPwdsNeverExpire && !accountPwdNeverExpires && valsLen.hasValues())
  1954. {
  1955. CDateTime expiry;
  1956. char * val = (char*)valsLen.queryCharValue(0);
  1957. calcPWExpiry(expiry, (unsigned)strlen(val), val);
  1958. ((CLdapSecUser*)&user)->setPasswordExpiration(expiry);
  1959. }
  1960. }
  1961. else if(stricmp(attribute, "objectClass") == 0)
  1962. {
  1963. int valind = 0;
  1964. while(vals.queryCharValue(valind))
  1965. {
  1966. if(stricmp(vals.queryCharValue(valind), "posixAccount") == 0)
  1967. {
  1968. ((CLdapSecUser*)&user)->setPosixenabled(true);
  1969. break;
  1970. }
  1971. valind++;
  1972. }
  1973. }
  1974. else if(stricmp(attribute, "employeeId") == 0)
  1975. user.setEmployeeID(vals.queryCharValue(0));
  1976. else if(stricmp(attribute, "employeeNumber") == 0)
  1977. user.setEmployeeNumber(vals.queryCharValue(0));
  1978. }
  1979. }
  1980. }
  1981. return true;
  1982. }
  1983. }
  1984. ISecUser* lookupUser(unsigned uid)
  1985. {
  1986. StringBuffer sysuser;
  1987. sysuser.append(m_ldapconfig->getSysUser());
  1988. if(sysuser.length() == 0)
  1989. {
  1990. #ifdef _WIN32
  1991. char uname[128];
  1992. unsigned long len = 128;
  1993. int rc = GetUserName(uname, &len);
  1994. if(rc != 0)
  1995. sysuser.append(len, uname);
  1996. else
  1997. throw MakeStringException(-1, "Error getting current user's username, error code = %d", rc);
  1998. #else
  1999. throw MakeStringException(-1, "systemUser not found in config");
  2000. #endif
  2001. }
  2002. MemoryBuffer usersidbuf;
  2003. StringBuffer usersidstr;
  2004. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2005. {
  2006. if(m_pp != NULL)
  2007. m_pp->lookupSid(sysuser.str(), usersidbuf);
  2008. if(usersidbuf.length() == 0)
  2009. {
  2010. throw MakeStringException(-1, "system user %s's SID not found", sysuser.str());
  2011. }
  2012. int sidlen = usersidbuf.length();
  2013. char* uidbuf = (char*)&uid;
  2014. for(int i = 0; i < 4; i++)
  2015. {
  2016. usersidbuf.writeDirect(sidlen -4 + i, 1, (uidbuf + 3 - i));
  2017. }
  2018. LdapUtils::bin2str(usersidbuf, usersidstr);
  2019. }
  2020. else
  2021. {
  2022. usersidbuf.append(uid);
  2023. }
  2024. char *attribute;
  2025. LDAPMessage *message;
  2026. StringBuffer filter;
  2027. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2028. {
  2029. filter.append("objectSid=").append(usersidstr.str());
  2030. }
  2031. else
  2032. {
  2033. filter.appendf("entryid=%d", uid);
  2034. }
  2035. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  2036. Owned<ILdapConnection> lconn = m_connections->getConnection();
  2037. LDAP* ld = lconn.get()->getLd();
  2038. char* act_fieldname;
  2039. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2040. {
  2041. act_fieldname = "sAMAccountName";
  2042. }
  2043. else
  2044. {
  2045. act_fieldname = "uid";
  2046. }
  2047. char *attrs[] = {"cn", act_fieldname, NULL};
  2048. CLDAPMessage searchResult;
  2049. int rc = ldap_search_ext_s(ld, (char*)m_ldapconfig->getUserBasedn(), LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs, 0, NULL, NULL, &timeOut, LDAP_NO_LIMIT, &searchResult.msg );
  2050. if ( rc != LDAP_SUCCESS )
  2051. {
  2052. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), m_ldapconfig->getUserBasedn());
  2053. return NULL;
  2054. }
  2055. if(ldap_count_entries(ld, searchResult) < 1)
  2056. {
  2057. DBGLOG("No entries are found for user with uid %0X", uid);
  2058. return NULL;
  2059. }
  2060. CLdapSecUser* ldapuser = new CLdapSecUser("", "");
  2061. // Go through the search results by checking message types
  2062. for(message = LdapFirstEntry( ld, searchResult); message != NULL; message = ldap_next_entry(ld, message))
  2063. {
  2064. CLDAPGetAttributesWrapper atts(ld, searchResult);
  2065. for ( attribute = atts.getFirst();
  2066. attribute != NULL;
  2067. attribute = atts.getNext())
  2068. {
  2069. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  2070. if (vals.hasValues())
  2071. {
  2072. if(stricmp(attribute, "cn") == 0)
  2073. ldapuser->setFullName(vals.queryCharValue(0));
  2074. else if(stricmp(attribute, act_fieldname) == 0)
  2075. ldapuser->setName(vals.queryCharValue(0));
  2076. }
  2077. }
  2078. }
  2079. ldapuser->setUserID(uid);
  2080. ldapuser->setUserSid(usersidbuf.length(), usersidbuf.toByteArray());
  2081. // Since we've got the SID for the user, cache it for later uses.
  2082. MemoryBuffer mb;
  2083. if(m_pp != NULL)
  2084. {
  2085. m_pp->getCachedSid(ldapuser->getName(), mb);
  2086. if(mb.length() == 0)
  2087. {
  2088. m_pp->cacheSid(ldapuser->getName(), usersidbuf.length(), usersidbuf.toByteArray());
  2089. }
  2090. }
  2091. return ldapuser;
  2092. }
  2093. bool lookupAccount(MemoryBuffer& sidbuf, StringBuffer& account_name, ACT_TYPE& act_type)
  2094. {
  2095. {
  2096. int sidLen = sidbuf.length();
  2097. ReadLockBlock readLock(m_unknownSIDCacheLock);
  2098. ForEachItemIn(idx, m_unknownSIDCache)
  2099. {
  2100. MemoryAttrItem& sid = m_unknownSIDCache.item(idx);
  2101. if (sid.length()==sidLen && 0==memcmp(sid.bufferBase(), sidbuf.bufferBase(), sidLen))
  2102. {
  2103. return false;
  2104. }
  2105. }
  2106. }
  2107. char *attribute;
  2108. LDAPMessage *message;
  2109. char* act_fieldname;
  2110. StringBuffer filter;
  2111. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2112. {
  2113. act_fieldname = "sAMAccountName";
  2114. StringBuffer usersidstr;
  2115. LdapUtils::bin2str(sidbuf, usersidstr);
  2116. filter.append("objectSid=").append(usersidstr.str());
  2117. }
  2118. else
  2119. {
  2120. unsigned* uid = (unsigned*)sidbuf.toByteArray();
  2121. filter.appendf("entryid=%d", *uid);
  2122. act_fieldname = "uid";
  2123. }
  2124. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  2125. Owned<ILdapConnection> lconn = m_connections->getConnection();
  2126. LDAP* ld = lconn.get()->getLd();
  2127. char *attrs[] = {"cn", act_fieldname, "objectClass", NULL};
  2128. CLDAPMessage searchResult;
  2129. int rc = ldap_search_ext_s(ld, (char*)m_ldapconfig->getUserBasedn(), LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs, 0, NULL, NULL, &timeOut, LDAP_NO_LIMIT, &searchResult.msg );
  2130. if ( rc != LDAP_SUCCESS )
  2131. {
  2132. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), m_ldapconfig->getUserBasedn());
  2133. return false;
  2134. }
  2135. if(ldap_count_entries(ld, searchResult) < 1)
  2136. {
  2137. searchResult.ldapMsgFree();
  2138. ldap_search_ext_s(ld, (char*)m_ldapconfig->getGroupBasedn(), LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs, 0, NULL, NULL, &timeOut, LDAP_NO_LIMIT, &searchResult.msg );
  2139. if(ldap_count_entries(ld, searchResult) < 1)
  2140. {
  2141. searchResult.ldapMsgFree();
  2142. ldap_search_ext_s(ld, (char*)m_ldapconfig->getSysUserBasedn(), LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs, 0, NULL, NULL, &timeOut, LDAP_NO_LIMIT, &searchResult.msg );
  2143. if(ldap_count_entries(ld, searchResult) < 1)
  2144. {
  2145. MemoryAttrItem *pItem = new MemoryAttrItem();
  2146. pItem->set(sidbuf.length(), sidbuf.bufferBase());
  2147. WriteLockBlock writeLock(m_unknownSIDCacheLock);
  2148. m_unknownSIDCache.append(*pItem);//remember orphaned SID so won't try to look up again
  2149. return false;
  2150. }
  2151. }
  2152. }
  2153. StringBuffer act_name;
  2154. StringBuffer cnbuf;
  2155. // Go through the search results by checking message types
  2156. for(message = LdapFirstEntry( ld, searchResult); message != NULL; message = ldap_next_entry(ld, message))
  2157. {
  2158. CLDAPGetAttributesWrapper atts(ld, searchResult);
  2159. for ( attribute = atts.getFirst();
  2160. attribute != NULL;
  2161. attribute = atts.getNext())
  2162. {
  2163. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  2164. if (vals.hasValues())
  2165. {
  2166. if(stricmp(attribute, act_fieldname) == 0)
  2167. act_name.clear().append(vals.queryCharValue(0));
  2168. else if(stricmp(attribute, "cn") == 0)
  2169. cnbuf.clear().append(vals.queryCharValue(0));
  2170. else if(stricmp(attribute, "objectClass") == 0)
  2171. {
  2172. int i = 0;
  2173. while(vals.queryCharValue(i) != NULL)
  2174. {
  2175. if(stricmp(vals.queryCharValue(i), "person") == 0)
  2176. act_type = USER_ACT;
  2177. else if(stricmp(vals.queryCharValue(i), "group") == 0)
  2178. act_type = GROUP_ACT;
  2179. i++;
  2180. }
  2181. }
  2182. }
  2183. }
  2184. }
  2185. if(act_type == USER_ACT)
  2186. account_name.append(act_name.str());
  2187. else
  2188. account_name.append(cnbuf.str());
  2189. return true;
  2190. }
  2191. virtual void lookupSid(const char* basedn, const char* filter, MemoryBuffer& act_sid)
  2192. {
  2193. char *attribute;
  2194. LDAPMessage *message;
  2195. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  2196. Owned<ILdapConnection> lconn = m_connections->getConnection();
  2197. LDAP* ld = lconn.get()->getLd();
  2198. char* fieldname;
  2199. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2200. fieldname = "objectSid";
  2201. else
  2202. fieldname = "entryid";
  2203. char *attrs[] = {fieldname, NULL};
  2204. CLDAPMessage searchResult;
  2205. int rc = ldap_search_ext_s(ld, (char*)basedn, LDAP_SCOPE_SUBTREE, (char*)filter, attrs, 0, NULL, NULL, &timeOut, LDAP_NO_LIMIT, &searchResult.msg );
  2206. if ( rc != LDAP_SUCCESS )
  2207. {
  2208. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter, basedn);
  2209. return;
  2210. }
  2211. message = LdapFirstEntry( ld, searchResult);
  2212. if(message != NULL)
  2213. {
  2214. CLDAPGetAttributesWrapper atts(ld, searchResult);
  2215. for ( attribute = atts.getFirst();
  2216. attribute != NULL;
  2217. attribute = atts.getNext())
  2218. {
  2219. if(0 == stricmp(attribute, fieldname))
  2220. {
  2221. CLDAPGetValuesLenWrapper valsLen(ld, message, attribute);
  2222. if (valsLen.hasValues())
  2223. {
  2224. struct berval* val = valsLen.queryBValues()[0];
  2225. if(val != NULL)
  2226. {
  2227. int len = val->bv_len;
  2228. act_sid.append(val->bv_len, val->bv_val);
  2229. }
  2230. }
  2231. break;
  2232. }
  2233. }
  2234. }
  2235. }
  2236. virtual void lookupSid(const char* act_name, MemoryBuffer& act_sid, ACT_TYPE act_type)
  2237. {
  2238. StringBuffer filter;
  2239. const char* basedn;
  2240. if(act_type == USER_ACT)
  2241. {
  2242. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2243. filter.append("sAMAccountName=").append(act_name);
  2244. else
  2245. filter.append("uid=").append(act_name);
  2246. basedn = m_ldapconfig->getUserBasedn();
  2247. if (m_ldapconfig->isAzureAD() && strieq(act_name, m_ldapconfig->getSysUser()))
  2248. basedn = m_ldapconfig->getSysUserBasedn();
  2249. lookupSid(basedn, filter.str(), act_sid);
  2250. if(act_sid.length() == 0)
  2251. {
  2252. StringBuffer basebuf;
  2253. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2254. basebuf.append("cn=Users,").append(m_ldapconfig->getBasedn());
  2255. else if(stricmp(act_name, m_ldapconfig->getSysUser()) == 0)
  2256. basebuf.append(m_ldapconfig->getSysUserBasedn());
  2257. else
  2258. basebuf.append("ou=People,").append(m_ldapconfig->getBasedn());
  2259. lookupSid(basebuf.str(), filter.str(), act_sid);
  2260. }
  2261. }
  2262. else
  2263. {
  2264. filter.append("cn=").append(act_name);
  2265. basedn = m_ldapconfig->getGroupBasedn();
  2266. lookupSid(basedn, filter.str(), act_sid);
  2267. if(act_sid.length() == 0)
  2268. {
  2269. StringBuffer basebuf;
  2270. basebuf.append("cn=Users,").append(m_ldapconfig->getBasedn());
  2271. lookupSid(basebuf.str(), filter.str(), act_sid);
  2272. if(act_sid.length() == 0)
  2273. {
  2274. basebuf.clear();
  2275. basebuf.append("cn=Builtin,").append(m_ldapconfig->getBasedn());
  2276. lookupSid(basebuf.str(), filter.str(), act_sid);
  2277. }
  2278. }
  2279. }
  2280. }
  2281. virtual void setPermissionProcessor(IPermissionProcessor* pp)
  2282. {
  2283. m_pp = pp;
  2284. }
  2285. virtual bool retrieveUsers(IUserArray& users)
  2286. {
  2287. return retrieveUsers("", users);
  2288. }
  2289. virtual bool retrieveUsers(const char* searchstr, IUserArray& users)
  2290. {
  2291. char *attribute;
  2292. LDAPMessage *message;
  2293. StringBuffer filter;
  2294. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2295. filter.append("objectClass=User");
  2296. else
  2297. filter.append("objectClass=inetorgperson");
  2298. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  2299. Owned<ILdapConnection> lconn = m_connections->getConnection();
  2300. LDAP* ld = lconn.get()->getLd();
  2301. char* act_fieldname;
  2302. char* sid_fieldname;
  2303. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2304. {
  2305. act_fieldname = "sAMAccountName";
  2306. sid_fieldname = "objectSid";
  2307. }
  2308. else
  2309. {
  2310. act_fieldname = "uid";
  2311. sid_fieldname = "entryid";
  2312. }
  2313. if(searchstr && *searchstr && strcmp(searchstr, "*") != 0)
  2314. {
  2315. filter.insert(0, "(&(");
  2316. filter.appendf(")(|(%s=*%s*)(%s=*%s*)(%s=*%s*)))", act_fieldname, searchstr, "givenName", searchstr, "sn", searchstr);
  2317. }
  2318. char *attrs[] = {act_fieldname, sid_fieldname, "cn", "userAccountControl", "pwdLastSet", "employeeId", "employeeNumber", NULL};
  2319. CPagedLDAPSearch pagedSrch(ld, m_ldapconfig->getLdapTimeout(), (char*)m_ldapconfig->getUserBasedn(), LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs);
  2320. for (message = pagedSrch.getFirstEntry(); message; message = pagedSrch.getNextEntry())
  2321. {
  2322. bool accountPwdNeverExpires = false;
  2323. Owned<ISecUser> user = new CLdapSecUser("", "");
  2324. // Go through the search results by checking message types
  2325. CLDAPGetAttributesWrapper atts(ld, message);
  2326. for ( attribute = atts.getFirst();
  2327. attribute != NULL;
  2328. attribute = atts.getNext())
  2329. {
  2330. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  2331. if (!vals.hasValues())
  2332. continue;
  2333. if(stricmp(attribute, "cn") == 0)
  2334. {
  2335. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  2336. if (vals.hasValues())
  2337. user->setFullName(vals.queryCharValue(0));
  2338. }
  2339. else if (stricmp(attribute, "userAccountControl") == 0)
  2340. {
  2341. //UF_DONT_EXPIRE_PASSWD 0x10000
  2342. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  2343. if (vals.hasValues())
  2344. if (atoi((char*)vals.queryCharValue(0)) & 0x10000)//this can be true at the account level, even if domain policy requires password
  2345. accountPwdNeverExpires = true;
  2346. }
  2347. else if(stricmp(attribute, "pwdLastSet") == 0)
  2348. {
  2349. CDateTime expiry;
  2350. if (!m_domainPwdsNeverExpire && !accountPwdNeverExpires)
  2351. {
  2352. CLDAPGetValuesLenWrapper valsLen(ld, message, attribute);
  2353. if (valsLen.hasValues())
  2354. {
  2355. struct berval* val = valsLen.queryBValues()[0];
  2356. calcPWExpiry(expiry, (unsigned)val->bv_len, val->bv_val);
  2357. }
  2358. }
  2359. else
  2360. expiry.clear();
  2361. user->setPasswordExpiration(expiry);
  2362. }
  2363. else if(stricmp(attribute, act_fieldname) == 0)
  2364. {
  2365. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  2366. if (vals.hasValues())
  2367. user->setName(vals.queryCharValue(0));
  2368. }
  2369. else if(stricmp(attribute, sid_fieldname) == 0)
  2370. {
  2371. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2372. {
  2373. CLDAPGetValuesLenWrapper valsLen(ld, message, attribute);
  2374. if (valsLen.hasValues())
  2375. {
  2376. struct berval* val = valsLen.queryBValues()[0];
  2377. if(val != NULL)
  2378. {
  2379. unsigned uid = val->bv_val[val->bv_len - 4];
  2380. int i;
  2381. for(i = 3; i > 0; i--)
  2382. {
  2383. uid = (uid << 8) + val->bv_val[val->bv_len - i];
  2384. }
  2385. ((CLdapSecUser*)user.get())->setUserID(uid);
  2386. }
  2387. }
  2388. }
  2389. else
  2390. {
  2391. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  2392. if (vals.hasValues())
  2393. ((CLdapSecUser*)user.get())->setUserID(atoi(vals.queryCharValue(0)));
  2394. }
  2395. }
  2396. else if(stricmp(attribute, "employeeId") == 0)
  2397. {
  2398. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  2399. if (vals.hasValues())
  2400. user->setEmployeeID(vals.queryCharValue(0));
  2401. }
  2402. else if(stricmp(attribute, "employeeNumber") == 0)
  2403. {
  2404. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  2405. if (vals.hasValues())
  2406. user->setEmployeeNumber(vals.queryCharValue(0));
  2407. }
  2408. }
  2409. if (user->getName() && *user->getName())
  2410. users.append(*LINK(user.get()));
  2411. }
  2412. return true;
  2413. }
  2414. virtual IPropertyTreeIterator* getUserIterator(const char* userName)
  2415. {
  2416. IUserArray users;
  2417. retrieveUsers(userName, users);
  2418. Owned<IPropertyTree> usersTree = createPTree("Users");
  2419. ForEachItemIn(i, users)
  2420. addUserTree(users.item(i), usersTree);
  2421. return usersTree->getElements("*");
  2422. }
  2423. void addUserTree(ISecUser& usr, IPropertyTree* users)
  2424. {
  2425. const char* usrName = usr.getName();
  2426. if(!usrName || !*usrName)
  2427. {
  2428. DBGLOG("CLdapClient::addUserTree username must be provided");
  2429. return;
  2430. }
  2431. const char* fullName = usr.getFullName();
  2432. StringBuffer sb;
  2433. switch (usr.getPasswordDaysRemaining())//-1 if expired, -2 if never expires
  2434. {
  2435. case scPasswordExpired:
  2436. sb.set("Expired");
  2437. break;
  2438. case scPasswordNeverExpires:
  2439. sb.set("Never");
  2440. break;
  2441. default:
  2442. CDateTime dt;
  2443. usr.getPasswordExpiration(dt);
  2444. dt.getDateString(sb);
  2445. break;
  2446. }
  2447. Owned<IPTree> userTree = createPTree("User");
  2448. userTree->addProp(getUserFieldNames(UFName), usrName);
  2449. if (fullName && *fullName)
  2450. userTree->addProp(getUserFieldNames(UFFullName), fullName);
  2451. userTree->addPropInt(getUserFieldNames(UFUserID), usr.getUserID());
  2452. userTree->addProp(getUserFieldNames(UFPasswordExpiration), sb.str());
  2453. userTree->addProp(getUserFieldNames(UFEmployeeID), usr.getEmployeeID());
  2454. userTree->addProp(getUserFieldNames(UFEmployeeNumber), usr.getEmployeeNumber());
  2455. users->addPropTree("User", userTree.getClear());
  2456. }
  2457. ISecItemIterator* getUsersSorted(const char* userName, UserField* sortOrder, const unsigned pageStartFrom, const unsigned pageSize, unsigned* total, __int64* cacheHint)
  2458. {
  2459. class CElementsPager : public CSimpleInterface, implements IElementsPager
  2460. {
  2461. ILdapClient* ldapClient;
  2462. StringAttr userName;
  2463. StringAttr sortOrder;
  2464. public:
  2465. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  2466. CElementsPager(ILdapClient* _ldapClient, const char* _userName, const char*_sortOrder)
  2467. : ldapClient(_ldapClient), userName(_userName), sortOrder(_sortOrder) { };
  2468. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree>& elements)
  2469. {
  2470. StringArray unknownAttributes;
  2471. Owned<IPropertyTreeIterator> iter = ldapClient->getUserIterator(userName.get());
  2472. sortElements(iter, sortOrder.get(), NULL, NULL, unknownAttributes, elements);
  2473. return NULL;
  2474. }
  2475. virtual bool allMatchingElementsReceived() { return true; }//For now, ldap always returns all of matched users.
  2476. };
  2477. StringBuffer so;
  2478. if (sortOrder)
  2479. {
  2480. for (unsigned i=0;sortOrder[i]!=UFterm;i++)
  2481. {
  2482. if (so.length())
  2483. so.append(',');
  2484. int fmt = sortOrder[i];
  2485. if (fmt&UFreverse)
  2486. so.append('-');
  2487. if (fmt&UFnocase)
  2488. so.append('?');
  2489. if (fmt&UFnumeric)
  2490. so.append('#');
  2491. so.append(getUserFieldNames((UserField) (fmt&0xff)));
  2492. }
  2493. }
  2494. IArrayOf<IPropertyTree> results;
  2495. Owned<IElementsPager> elementsPager = new CElementsPager(this, userName, so.length()?so.str():NULL);
  2496. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager, pageStartFrom, pageSize, NULL, "", cacheHint, results, total, NULL, false);
  2497. return new CSecItemIterator(results);
  2498. }
  2499. virtual bool userInGroup(const char* userdn, const char* groupdn)
  2500. {
  2501. const char* fldname;
  2502. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2503. fldname = "member";
  2504. else
  2505. fldname = "uniquemember";
  2506. Owned<ILdapConnection> lconn = m_connections->getConnection();
  2507. LDAP* ld = lconn.get()->getLd();
  2508. int rc = LDAP_COMPARE_EXT_S(ld, (const char*)groupdn, (const char*)fldname, (const char*)userdn,0,0,0);
  2509. #ifndef _WIN32
  2510. if (rc == -3)//389DirectoryServer always seems to return -3
  2511. rc = ldap_compare_s(ld, groupdn, fldname, userdn);
  2512. #endif
  2513. if(rc == LDAP_COMPARE_TRUE)
  2514. return true;
  2515. else
  2516. return false;
  2517. }
  2518. // Update user's firstname, lastname (plus displayname for active directory).
  2519. virtual bool updateUser(const char* type, ISecUser& user)
  2520. {
  2521. const char* username = user.getName();
  2522. if(!username || !*username)
  2523. {
  2524. DBGLOG("CLdapClient::updateUser username must be provided");
  2525. return false;
  2526. }
  2527. StringBuffer userdn;
  2528. getUserDN(username, userdn);
  2529. int rc = LDAP_SUCCESS;
  2530. if(!type || !*type || stricmp(type, "names") == 0)
  2531. {
  2532. StringBuffer cnbuf;
  2533. const char* fname = user.getFirstName();
  2534. const char* lname = user.getLastName();
  2535. if(fname && *fname && lname && *lname)
  2536. {
  2537. cnbuf.append(fname).append(" ").append(lname);
  2538. }
  2539. else
  2540. throw MakeStringException(-1, "Please specify both firstname and lastname");
  2541. char *gn_values[] = { (char*)fname, NULL };
  2542. LDAPMod gn_attr = {
  2543. LDAP_MOD_REPLACE,
  2544. "givenName",
  2545. gn_values
  2546. };
  2547. char *sn_values[] = { (char*)lname, NULL };
  2548. LDAPMod sn_attr = {
  2549. LDAP_MOD_REPLACE,
  2550. "sn",
  2551. sn_values
  2552. };
  2553. char *cn_values[] = {(char*)cnbuf.str(), NULL };
  2554. LDAPMod cn_attr =
  2555. {
  2556. LDAP_MOD_REPLACE,
  2557. "cn",
  2558. cn_values
  2559. };
  2560. char *dispname_values[] = {(char*)cnbuf.str(), NULL };
  2561. LDAPMod dispname_attr =
  2562. {
  2563. LDAP_MOD_REPLACE,
  2564. "displayName",
  2565. dispname_values
  2566. };
  2567. const char * emplID = user.getEmployeeID();
  2568. char *employeeID_values[] = {(emplID && *emplID) ? (char*)emplID : nullptr, nullptr };
  2569. LDAPMod employeeID_attr =
  2570. {
  2571. LDAP_MOD_REPLACE,
  2572. "employeeId",
  2573. employeeID_values
  2574. };
  2575. const char * emplNumber = user.getEmployeeNumber();
  2576. char *employeeNumber_values[] = {(emplNumber && *emplNumber) ? (char*)emplNumber : nullptr, nullptr };
  2577. LDAPMod employeeNumber_attr =
  2578. {
  2579. LDAP_MOD_REPLACE,
  2580. "employeeNumber",
  2581. employeeNumber_values
  2582. };
  2583. LDAPMod *attrs[6];
  2584. int ind = 0;
  2585. attrs[ind++] = &gn_attr;
  2586. attrs[ind++] = &sn_attr;
  2587. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2588. {
  2589. attrs[ind++] = &dispname_attr;
  2590. }
  2591. else
  2592. {
  2593. attrs[ind++] = &cn_attr;
  2594. }
  2595. attrs[ind++] = &employeeID_attr;
  2596. attrs[ind++] = &employeeNumber_attr;
  2597. attrs[ind] = NULL;
  2598. Owned<ILdapConnection> lconn = m_connections->getConnection();
  2599. LDAP* ld = lconn.get()->getLd();
  2600. rc = ldap_modify_ext_s(ld, (char*)userdn.str(), attrs, NULL, NULL);
  2601. if (rc == LDAP_SUCCESS && m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2602. {
  2603. StringBuffer newrdn("cn=");
  2604. newrdn.append(cnbuf.str());
  2605. rc = LdapRename(ld, (char*)userdn.str(), (char*)newrdn.str(), NULL, true, NULL, NULL);
  2606. }
  2607. }
  2608. else if(stricmp(type, "posixenable") == 0)
  2609. {
  2610. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2611. throw MakeStringException(-1, "posixAccount isn't applicable to Active Directory");
  2612. CLdapSecUser* ldapuser = dynamic_cast<CLdapSecUser*>(&user);
  2613. if (ldapuser == nullptr)
  2614. {
  2615. throw MakeStringException(-1, "Unable to cast user %s to CLdapSecUser", username);
  2616. }
  2617. char* oc_values[] = {"posixAccount", NULL};
  2618. LDAPMod oc_attr = {
  2619. LDAP_MOD_ADD,
  2620. "objectclass",
  2621. oc_values
  2622. };
  2623. char* oc1_values[] = {"shadowAccount", NULL};
  2624. LDAPMod oc1_attr = {
  2625. LDAP_MOD_ADD,
  2626. "objectclass",
  2627. oc1_values
  2628. };
  2629. char *gidnum_values[] = { (char*)ldapuser->getGidnumber(), NULL };
  2630. LDAPMod gidnum_attr = {
  2631. LDAP_MOD_REPLACE,
  2632. "gidnumber",
  2633. gidnum_values
  2634. };
  2635. char *uidnum_values[] = { (char*)ldapuser->getUidnumber(), NULL };
  2636. LDAPMod uidnum_attr = {
  2637. LDAP_MOD_REPLACE,
  2638. "uidnumber",
  2639. uidnum_values
  2640. };
  2641. char *homedir_values[] = {(char*)ldapuser->getHomedirectory(), NULL };
  2642. LDAPMod homedir_attr =
  2643. {
  2644. LDAP_MOD_REPLACE,
  2645. "homedirectory",
  2646. homedir_values
  2647. };
  2648. char *loginshell_values[] = {(char*)ldapuser->getLoginshell(), NULL };
  2649. LDAPMod loginshell_attr =
  2650. {
  2651. LDAP_MOD_REPLACE,
  2652. "loginshell",
  2653. loginshell_values
  2654. };
  2655. LDAPMod *attrs[7];
  2656. int ind = 0;
  2657. attrs[ind++] = &gidnum_attr;
  2658. attrs[ind++] = &uidnum_attr;
  2659. attrs[ind++] = &homedir_attr;
  2660. attrs[ind++] = &loginshell_attr;
  2661. Owned<ILdapConnection> lconn = m_connections->getConnection();
  2662. LDAP* ld = lconn.get()->getLd();
  2663. int compresult = LDAP_COMPARE_EXT_S(ld, (const char*)userdn.str(), (const char*)"objectclass", (const char*)"posixAccount",0,0,0);
  2664. #ifndef _WIN32
  2665. if (compresult == -3)//389DirectoryServer always seems to return -3
  2666. compresult = ldap_compare_s(ld, userdn.str(), "objectclass", "posixAccount");
  2667. #endif
  2668. if(compresult != LDAP_COMPARE_TRUE)
  2669. attrs[ind++] = &oc_attr;
  2670. compresult = LDAP_COMPARE_EXT_S(ld, (const char*)userdn.str(), (const char*)"objectclass", (const char*)"shadowAccount",0,0,0);
  2671. #ifndef _WIN32
  2672. if (compresult == -3)//389DirectoryServer always seems to return -3
  2673. compresult = ldap_compare_s(ld, userdn.str(), "objectclass", "shadowAccount");
  2674. #endif
  2675. if(compresult != LDAP_COMPARE_TRUE)
  2676. attrs[ind++] = &oc1_attr;
  2677. attrs[ind] = NULL;
  2678. rc = ldap_modify_ext_s(ld, (char*)userdn.str(), attrs, NULL, NULL);
  2679. }
  2680. else if(stricmp(type, "posixdisable") == 0)
  2681. {
  2682. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2683. throw MakeStringException(-1, "posixAccount isn't applicable to Active Directory");
  2684. Owned<ILdapConnection> lconn = m_connections->getConnection();
  2685. LDAP* ld = lconn.get()->getLd();
  2686. int compresult = LDAP_COMPARE_EXT_S(ld, (const char*)userdn.str(), (const char*)"objectclass", (const char*)"posixAccount",0,0,0);
  2687. #ifndef _WIN32
  2688. if (compresult == -3)//389DirectoryServer always seems to return -3
  2689. compresult = ldap_compare_s(ld, userdn.str(), "objectclass", "posixAccount");
  2690. #endif
  2691. if(compresult != LDAP_COMPARE_TRUE)
  2692. {
  2693. rc = LDAP_SUCCESS;
  2694. }
  2695. else
  2696. {
  2697. char* oc_values[] = {"posixAccount", NULL};
  2698. LDAPMod oc_attr = {
  2699. LDAP_MOD_DELETE,
  2700. "objectclass",
  2701. oc_values
  2702. };
  2703. char* oc1_values[] = {"shadowAccount", NULL};
  2704. LDAPMod oc1_attr = {
  2705. LDAP_MOD_DELETE,
  2706. "objectclass",
  2707. oc1_values
  2708. };
  2709. char *gidnum_values[] = { NULL };
  2710. LDAPMod gidnum_attr = {
  2711. LDAP_MOD_DELETE,
  2712. "gidnumber",
  2713. gidnum_values
  2714. };
  2715. char *uidnum_values[] = {NULL };
  2716. LDAPMod uidnum_attr = {
  2717. LDAP_MOD_DELETE,
  2718. "uidnumber",
  2719. uidnum_values
  2720. };
  2721. char *homedir_values[] = { NULL };
  2722. LDAPMod homedir_attr =
  2723. {
  2724. LDAP_MOD_DELETE,
  2725. "homedirectory",
  2726. homedir_values
  2727. };
  2728. char *loginshell_values[] = { NULL };
  2729. LDAPMod loginshell_attr =
  2730. {
  2731. LDAP_MOD_DELETE,
  2732. "loginshell",
  2733. loginshell_values
  2734. };
  2735. LDAPMod *attrs[7];
  2736. int ind = 0;
  2737. attrs[ind++] = &gidnum_attr;
  2738. attrs[ind++] = &uidnum_attr;
  2739. attrs[ind++] = &homedir_attr;
  2740. attrs[ind++] = &loginshell_attr;
  2741. attrs[ind++] = &oc_attr;
  2742. attrs[ind++] = &oc1_attr;
  2743. attrs[ind] = NULL;
  2744. rc = ldap_modify_ext_s(ld, (char*)userdn.str(), attrs, NULL, NULL);
  2745. }
  2746. }
  2747. else if(stricmp(type, "sudoersadd") == 0)
  2748. {
  2749. CLdapSecUser* ldapuser = dynamic_cast<CLdapSecUser*>(&user);
  2750. if (ldapuser == nullptr)
  2751. {
  2752. throw MakeStringException(-1, "Unable to cast user %s to CLdapSecUser", username);
  2753. }
  2754. char *cn_values[] = {(char*)username, NULL };
  2755. LDAPMod cn_attr =
  2756. {
  2757. LDAP_MOD_ADD,
  2758. "cn",
  2759. cn_values
  2760. };
  2761. char *oc_values[] = {"sudoRole", NULL };
  2762. LDAPMod oc_attr =
  2763. {
  2764. LDAP_MOD_ADD,
  2765. "objectClass",
  2766. oc_values
  2767. };
  2768. char *user_values[] = {(char*)username, NULL };
  2769. LDAPMod user_attr =
  2770. {
  2771. LDAP_MOD_ADD,
  2772. "sudoUser",
  2773. user_values
  2774. };
  2775. char* sudoHost = (char*)ldapuser->getSudoHost();
  2776. char* sudoCommand = (char*)ldapuser->getSudoCommand();
  2777. char* sudoOption = (char*)ldapuser->getSudoOption();
  2778. char *host_values[] = {sudoHost, NULL };
  2779. LDAPMod host_attr =
  2780. {
  2781. LDAP_MOD_ADD,
  2782. "sudoHost",
  2783. host_values
  2784. };
  2785. char *cmd_values[] = {sudoCommand, NULL };
  2786. LDAPMod cmd_attr =
  2787. {
  2788. LDAP_MOD_ADD,
  2789. "sudoCommand",
  2790. cmd_values
  2791. };
  2792. char *option_values[] = {sudoOption, NULL };
  2793. LDAPMod option_attr =
  2794. {
  2795. LDAP_MOD_ADD,
  2796. "sudoOption",
  2797. option_values
  2798. };
  2799. LDAPMod *attrs[8];
  2800. int ind = 0;
  2801. attrs[ind++] = &cn_attr;
  2802. attrs[ind++] = &oc_attr;
  2803. attrs[ind++] = &user_attr;
  2804. if(sudoHost && *sudoHost)
  2805. attrs[ind++] = &host_attr;
  2806. if(sudoCommand && *sudoCommand)
  2807. attrs[ind++] = &cmd_attr;
  2808. if(sudoOption && *sudoOption)
  2809. attrs[ind++] = &option_attr;
  2810. attrs[ind] = NULL;
  2811. Owned<ILdapConnection> lconn = m_connections->getConnection();
  2812. LDAP* ld = lconn.get()->getLd();
  2813. StringBuffer dn;
  2814. dn.append("cn=").append(username).append(",").append(m_ldapconfig->getResourceBasedn(RT_SUDOERS));
  2815. int rc = ldap_add_ext_s(ld, (char*)dn.str(), attrs, NULL, NULL);
  2816. if ( rc != LDAP_SUCCESS )
  2817. {
  2818. if(rc == LDAP_ALREADY_EXISTS)
  2819. {
  2820. throw MakeStringException(-1, "can't add %s to sudoers, an LDAP object with this name already exists", username);
  2821. }
  2822. else
  2823. {
  2824. DBGLOG("error adding %s to sudoers: %s", username, ldap_err2string( rc ));
  2825. throw MakeStringException(-1, "error adding %s to sudoers: %s", username, ldap_err2string( rc ));
  2826. }
  2827. }
  2828. }
  2829. else if(stricmp(type, "sudoersdelete") == 0)
  2830. {
  2831. StringBuffer dn;
  2832. dn.append("cn=").append(username).append(",").append(m_ldapconfig->getResourceBasedn(RT_SUDOERS));
  2833. Owned<ILdapConnection> lconn = m_connections->getConnection();
  2834. LDAP* ld = lconn.get()->getLd();
  2835. int rc = ldap_delete_ext_s(ld, (char*)dn.str(), NULL, NULL);
  2836. if ( rc != LDAP_SUCCESS )
  2837. {
  2838. throw MakeStringException(-1, "Error deleting user %s from sudoers: %s", username, ldap_err2string(rc));
  2839. }
  2840. }
  2841. else if(stricmp(type, "sudoersupdate") == 0)
  2842. {
  2843. CLdapSecUser* ldapuser = dynamic_cast<CLdapSecUser*>(&user);
  2844. if (ldapuser == nullptr)
  2845. {
  2846. throw MakeStringException(-1, "Unable to cast user %s to CLdapSecUser", username);
  2847. }
  2848. char* sudoHost = (char*)ldapuser->getSudoHost();
  2849. char* sudoCommand = (char*)ldapuser->getSudoCommand();
  2850. char* sudoOption = (char*)ldapuser->getSudoOption();
  2851. char *host_values[] = {(sudoHost&&*sudoHost)?sudoHost:NULL, NULL };
  2852. LDAPMod host_attr =
  2853. {
  2854. LDAP_MOD_REPLACE,
  2855. "sudoHost",
  2856. host_values
  2857. };
  2858. char *cmd_values[] = {(sudoCommand&&*sudoCommand)?sudoCommand:NULL, NULL };
  2859. LDAPMod cmd_attr =
  2860. {
  2861. LDAP_MOD_REPLACE,
  2862. "sudoCommand",
  2863. cmd_values
  2864. };
  2865. char *option_values[] = {(sudoOption&&*sudoOption)?sudoOption:NULL, NULL };
  2866. LDAPMod option_attr =
  2867. {
  2868. LDAP_MOD_REPLACE,
  2869. "sudoOption",
  2870. option_values
  2871. };
  2872. LDAPMod *attrs[4];
  2873. int ind = 0;
  2874. attrs[ind++] = &host_attr;
  2875. attrs[ind++] = &cmd_attr;
  2876. attrs[ind++] = &option_attr;
  2877. attrs[ind] = NULL;
  2878. Owned<ILdapConnection> lconn = m_connections->getConnection();
  2879. LDAP* ld = lconn.get()->getLd();
  2880. StringBuffer dn;
  2881. dn.append("cn=").append(username).append(",").append(m_ldapconfig->getResourceBasedn(RT_SUDOERS));
  2882. int rc = ldap_modify_ext_s(ld, (char*)dn.str(), attrs, NULL, NULL);
  2883. if ( rc != LDAP_SUCCESS )
  2884. {
  2885. DBGLOG("error modifying sudoers for user %s: %s", username, ldap_err2string( rc ));
  2886. throw MakeStringException(-1, "error modifying sudoers for user %s: %s", username, ldap_err2string( rc ));
  2887. }
  2888. }
  2889. if (rc == LDAP_SUCCESS )
  2890. DBGLOG("User %s successfully updated", username);
  2891. else
  2892. throw MakeStringException(-1, "Error updating user %s - %s", username, ldap_err2string( rc ));
  2893. return true;
  2894. }
  2895. virtual bool changePasswordSSL(const char* username, const char* newPassword)
  2896. {
  2897. Owned<ILdapConnection> lconn;
  2898. try
  2899. {
  2900. lconn.setown(m_connections->getSSLConnection());
  2901. }
  2902. catch(IException*)
  2903. {
  2904. throw MakeStringException(-1, "Failed to set user %s's password because of not being able to create an SSL connection to the ldap server. To set an Active Directory user's password from Linux, you need to enable SSL on the Active Directory ldap server", username);
  2905. }
  2906. LDAP* ld = lconn.get()->getLd();
  2907. char *attribute, **values = NULL;
  2908. LDAPMessage *message;
  2909. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  2910. StringBuffer filter;
  2911. filter.append("sAMAccountName=").append(username);
  2912. char *attrs[] = {"distinguishedName", NULL};
  2913. CLDAPMessage searchResult;
  2914. int rc = ldap_search_ext_s(ld, (char*)m_ldapconfig->getUserBasedn(), LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs, 0, NULL, NULL, &timeOut, LDAP_NO_LIMIT, &searchResult.msg );
  2915. if ( rc != LDAP_SUCCESS )
  2916. {
  2917. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), m_ldapconfig->getUserBasedn());
  2918. return false;
  2919. }
  2920. StringBuffer userdn;
  2921. message = LdapFirstEntry( ld, searchResult);
  2922. if(message != NULL)
  2923. {
  2924. CLDAPGetAttributesWrapper atts(ld, searchResult);
  2925. for ( attribute = atts.getFirst();
  2926. attribute != NULL;
  2927. attribute = atts.getNext())
  2928. {
  2929. if(0 == stricmp(attribute, "distinguishedName"))
  2930. {
  2931. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  2932. if (vals.hasValues())
  2933. userdn.set(vals.queryCharValue(0));
  2934. break;
  2935. }
  2936. }
  2937. }
  2938. if(userdn.length() == 0)
  2939. {
  2940. throw MakeStringException(-1, "can't find dn for user %s", username);
  2941. }
  2942. LDAPMod modPassword;
  2943. LDAPMod *modEntry[2];
  2944. struct berval pwdBerVal;
  2945. struct berval *pwd_attr[2];
  2946. unsigned short pszPasswordWithQuotes[1024];
  2947. modEntry[0] = &modPassword;
  2948. modEntry[1] = NULL;
  2949. modPassword.mod_op = LDAP_MOD_REPLACE | LDAP_MOD_BVALUES;
  2950. modPassword.mod_type = "unicodePwd";
  2951. modPassword.mod_vals.modv_bvals = pwd_attr;
  2952. pwd_attr[0] = &pwdBerVal;
  2953. pwd_attr[1]= NULL;
  2954. StringBuffer quotedPasswd("\"");
  2955. quotedPasswd.append(newPassword).append("\"");
  2956. ConvertCToW(pszPasswordWithQuotes, quotedPasswd);
  2957. pwdBerVal.bv_len = quotedPasswd.length() * sizeof(unsigned short);
  2958. pwdBerVal.bv_val = (char*)pszPasswordWithQuotes;
  2959. rc = ldap_modify_ext_s(ld, (char*)userdn.str(), modEntry, NULL, NULL);
  2960. if (rc == LDAP_SUCCESS )
  2961. DBGLOG("User %s's password has been changed successfully", username);
  2962. else
  2963. {
  2964. StringBuffer errmsg;
  2965. errmsg.appendf("Error setting password for %s - (%d) %s.", username, rc, ldap_err2string( rc ));
  2966. if(rc == LDAP_UNWILLING_TO_PERFORM)
  2967. errmsg.append(" The ldap server refused to change the password. Usually this is because your new password doesn't satisfy the domain policy.");
  2968. throw MakeStringExceptionDirect(-1, errmsg.str());
  2969. }
  2970. return true;
  2971. }
  2972. virtual bool queryPasswordStatus(ISecUser& user, const char* password)
  2973. {
  2974. char *ldap_errstring = NULL;
  2975. const char * username = user.getName();
  2976. StringBuffer userdn;
  2977. getUserDN(user.getName(), userdn);
  2978. StringBuffer hostbuf;
  2979. m_ldapconfig->getLdapHost(hostbuf);
  2980. LDAP* user_ld = LdapUtils::LdapInit(m_ldapconfig->getProtocol(), hostbuf.str(), m_ldapconfig->getLdapPort(), m_ldapconfig->getLdapSecurePort());
  2981. int rc = LdapUtils::LdapBind(user_ld, m_ldapconfig->getLdapTimeout(),m_ldapconfig->getDomain(), username, password, userdn, m_ldapconfig->getServerType(), m_ldapconfig->getAuthMethod());
  2982. if(rc != LDAP_SUCCESS)
  2983. ldap_get_option(user_ld, LDAP_OPT_ERROR_STRING, &ldap_errstring);
  2984. LDAP_UNBIND(user_ld);
  2985. //Error string ""80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 532, v1db0."
  2986. //is returned if pw valid but expired
  2987. if(rc == LDAP_SUCCESS || strstr(ldap_errstring, "data 532") || strstr(ldap_errstring, "data 773"))//
  2988. return true;
  2989. else
  2990. return false;
  2991. }
  2992. virtual bool updateUserPassword(ISecUser& user, const char* newPassword, const char* currPassword)
  2993. {
  2994. const char* username = user.getName();
  2995. if(!username || !*username)
  2996. {
  2997. DBGLOG("CLdapClient::updateUserPassword username must be provided");
  2998. return false;
  2999. }
  3000. if(isEmptyString(newPassword))
  3001. {
  3002. DBGLOG("CLdapClient::updateUserPassword password must be provided");
  3003. return false;
  3004. }
  3005. if (currPassword)
  3006. {
  3007. //User will not be authenticated if their password was expired,
  3008. //so check here that they provided a valid one in the "change
  3009. //password" form (use the one they type, not the one in the secuser)
  3010. bool validated = queryPasswordStatus(user, currPassword);
  3011. if (!validated)
  3012. throw MakeStringException(-1, "Password not changed, invalid credentials");
  3013. }
  3014. return updateUserPassword(username, newPassword);
  3015. }
  3016. virtual bool updateUserPassword(const char* username, const char* newPassword)
  3017. {
  3018. if(!username || !*username)
  3019. {
  3020. DBGLOG("CLdapClient::updateUserPassword username must be provided");
  3021. return false;
  3022. }
  3023. if(isEmptyString(newPassword))
  3024. {
  3025. DBGLOG("CLdapClient::updateUserPassword password must be provided");
  3026. return false;
  3027. }
  3028. const char* sysuser = m_ldapconfig->getSysUser();
  3029. if(sysuser && *sysuser && strcmp(username, sysuser) == 0)
  3030. throw MakeStringException(-1, "You can't change password of the system user.");
  3031. LdapServerType servertype = m_ldapconfig->getServerType();
  3032. bool ret = true;
  3033. if(servertype == ACTIVE_DIRECTORY)
  3034. {
  3035. #ifdef _WIN32
  3036. DWORD nStatus = 0;
  3037. // The application has to run on the same domain as ldap host, and under an administrative user.
  3038. USER_INFO_1003 usriSetPassword;
  3039. StringBuffer fullserver("\\\\");
  3040. StringBuffer server;
  3041. m_ldapconfig->getLdapHost(server);
  3042. fullserver.append(server.str());
  3043. LPWSTR whost = (LPWSTR)alloca((fullserver.length() +1) * sizeof(WCHAR));
  3044. ConvertCToW((unsigned short *)whost, fullserver.str());
  3045. LPWSTR wusername = (LPWSTR)alloca((strlen(username) + 1) * sizeof(WCHAR));
  3046. ConvertCToW((unsigned short *)wusername, username);
  3047. LPWSTR wnewpasswd = (LPWSTR)alloca((strlen(newPassword) + 1) * sizeof(WCHAR));
  3048. ConvertCToW((unsigned short *)wnewpasswd, newPassword);
  3049. usriSetPassword.usri1003_password = wnewpasswd;
  3050. nStatus = NetUserSetInfo(whost, wusername, 1003, (LPBYTE)&usriSetPassword, NULL);
  3051. if (nStatus == NERR_Success)
  3052. {
  3053. DBGLOG("User %s's password has been changed successfully", username);
  3054. return true;
  3055. }
  3056. else
  3057. {
  3058. StringBuffer errcode, errmsg;
  3059. if(nStatus == ERROR_ACCESS_DENIED)
  3060. {
  3061. errcode.append("ERROR_ACCESS_DENIED");
  3062. errmsg.append("The user does not have access to the requested information.");
  3063. }
  3064. else if(nStatus == ERROR_INVALID_PASSWORD)
  3065. {
  3066. errcode.append("ERROR_INVALID_PASSWORD");
  3067. errmsg.append("The user has entered an invalid password.");
  3068. }
  3069. else if(nStatus == NERR_InvalidComputer)
  3070. {
  3071. errcode.append("NERR_InvalidComputer");
  3072. errmsg.append("The computer name is invalid.");
  3073. }
  3074. else if(nStatus == NERR_NotPrimary)
  3075. {
  3076. errcode.append("NERR_NotPrimary");
  3077. errmsg.append("The operation is allowed only on the primary domain controller of the domain.");
  3078. }
  3079. else if(nStatus == NERR_UserNotFound)
  3080. {
  3081. errcode.append("NERR_UserNotFound");
  3082. errmsg.append("The user name could not be found.");
  3083. }
  3084. else if(nStatus == NERR_PasswordTooShort)
  3085. {
  3086. errcode.append("NERR_PasswordTooShort");
  3087. errmsg.append("The password is shorter than required. ");
  3088. }
  3089. else if(nStatus == ERROR_LOGON_FAILURE)
  3090. {
  3091. errcode.append("ERROR_LOGON_FAILURE");
  3092. errmsg.append("To be able to reset password this way, esp has to run under an administrative user on the same domain as the active directory. ");
  3093. }
  3094. else
  3095. {
  3096. errcode.appendf("%d", nStatus);
  3097. errmsg.append("");
  3098. }
  3099. // For certain errors just return, other errors try changePasswordSSL.
  3100. if(nStatus == ERROR_INVALID_PASSWORD || nStatus == NERR_UserNotFound || nStatus == NERR_PasswordTooShort)
  3101. throw MakeStringException(-1, "An error has occurred while setting password with NetUserSetInfo for %s: %s - %s\n", username, errcode.str(), errmsg.str());
  3102. else
  3103. DBGLOG("An error has occurred while setting password with NetUserSetInfo for %s: %s - %s\n", username, errcode.str(), errmsg.str());
  3104. }
  3105. DBGLOG("Trying changePasswordSSL to change password over regular SSL connection.");
  3106. #endif
  3107. changePasswordSSL(username, newPassword);
  3108. }
  3109. else
  3110. {
  3111. StringBuffer filter;
  3112. filter.append("uid=").append(username);
  3113. char **values = NULL;
  3114. LDAPMessage *message;
  3115. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  3116. Owned<ILdapConnection> lconn = m_connections->getConnection();
  3117. LDAP* ld = lconn.get()->getLd();
  3118. char *attrs[] = {LDAP_NO_ATTRS, NULL};
  3119. CLDAPMessage searchResult;
  3120. int rc = ldap_search_ext_s(ld, (char*)m_ldapconfig->getUserBasedn(), LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs, 0, NULL, NULL, &timeOut, LDAP_NO_LIMIT, &searchResult.msg );
  3121. if ( rc != LDAP_SUCCESS )
  3122. {
  3123. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), m_ldapconfig->getUserBasedn());
  3124. return false;
  3125. }
  3126. StringBuffer userdn;
  3127. message = LdapFirstEntry( ld, searchResult);
  3128. if(message != NULL)
  3129. {
  3130. char *p = ldap_get_dn(ld, message);
  3131. userdn.append(p);
  3132. ldap_memfree(p);
  3133. }
  3134. char* passwdvalue[] = { (char*)newPassword, NULL };
  3135. LDAPMod pmod =
  3136. {
  3137. LDAP_MOD_REPLACE,
  3138. "userpassword",
  3139. passwdvalue
  3140. };
  3141. LDAPMod* pmods[] = {&pmod, NULL};
  3142. rc = ldap_modify_ext_s(ld, (char*)userdn.str(), pmods, NULL, NULL);
  3143. if (rc == LDAP_SUCCESS )
  3144. DBGLOG("User %s's password has been changed successfully", username);
  3145. else
  3146. {
  3147. StringBuffer errmsg;
  3148. errmsg.appendf("Error changing password for %s - (%d) %s.", username, rc, ldap_err2string( rc ));
  3149. if(rc == LDAP_UNWILLING_TO_PERFORM)
  3150. errmsg.append(" The ldap server refused to execute the password change action, one of the reasons might be that the new password you entered doesn't satisfy the policy requirement.");
  3151. throw MakeStringExceptionDirect(-1, errmsg.str());
  3152. }
  3153. }
  3154. return true;
  3155. }
  3156. virtual bool getResources(SecResourceType rtype, const char * basedn, const char * prefix, const char * searchstr, IArrayOf<ISecResource>& resources)
  3157. {
  3158. return getResources(nullptr, rtype, basedn, prefix, searchstr, resources);
  3159. }
  3160. virtual bool getResources(LDAP* ld, SecResourceType rtype, const char * basedn, const char * prefix, const char * searchstr, IArrayOf<ISecResource>& resources)
  3161. {
  3162. Owned<ILdapConnection> lconn;
  3163. if (nullptr == ld)
  3164. {
  3165. lconn.setown(m_connections->getConnection());
  3166. ld = lconn.get()->getLd();
  3167. }
  3168. if(rtype == RT_FILE_SCOPE || rtype == RT_WORKUNIT_SCOPE)
  3169. {
  3170. assertex(isEmptyString(searchstr));
  3171. assertex(isEmptyString(prefix));
  3172. getManagedScopeTree(ld, rtype, basedn, resources);
  3173. return true;
  3174. }
  3175. char *attribute;
  3176. LDAPMessage *message;
  3177. StringBuffer basednbuf;
  3178. LdapUtils::normalizeDn(basedn, m_ldapconfig->getBasedn(), basednbuf);
  3179. StringBuffer filter("objectClass=*");
  3180. if(searchstr && *searchstr && strcmp(searchstr, "*") != 0)
  3181. {
  3182. filter.insert(0, "(&(");
  3183. filter.appendf(")(|(%s=*%s*)))", "uNCName", searchstr);
  3184. }
  3185. const char* fldname;
  3186. LdapServerType servertype = m_ldapconfig->getServerType();
  3187. if(servertype == ACTIVE_DIRECTORY && (rtype == RT_DEFAULT || rtype == RT_MODULE || rtype == RT_SERVICE))
  3188. fldname = "name";
  3189. else
  3190. fldname = "ou";
  3191. char *attrs[] = {(char*)fldname, "description", NULL};
  3192. CPagedLDAPSearch pagedSrch(ld, m_ldapconfig->getLdapTimeout(), (char*)basednbuf.str(), LDAP_SCOPE_ONELEVEL, (char*)filter.str(), attrs);
  3193. for (message = pagedSrch.getFirstEntry(); message; message = pagedSrch.getNextEntry())
  3194. {
  3195. CLDAPGetAttributesWrapper atts(ld, message);
  3196. for ( attribute = atts.getFirst(); attribute != NULL; attribute = atts.getNext())
  3197. {
  3198. StringBuffer descbuf;
  3199. StringBuffer curname;
  3200. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  3201. if (vals.hasValues())
  3202. {
  3203. const char* val = vals.queryCharValue(0);
  3204. if(val != NULL)
  3205. {
  3206. if(stricmp(attribute, fldname) == 0)
  3207. {
  3208. curname.append(val);
  3209. }
  3210. else if(stricmp(attribute, "description") == 0)
  3211. {
  3212. descbuf.append(val);
  3213. }
  3214. }
  3215. }
  3216. if(curname.length() == 0)
  3217. continue;
  3218. StringBuffer resourcename;
  3219. if(prefix != NULL && *prefix != '\0')
  3220. resourcename.append(prefix);
  3221. resourcename.append(curname.str());
  3222. CLdapSecResource* resource = new CLdapSecResource(resourcename.str());
  3223. resource->setDescription(descbuf.str());
  3224. resources.append(*resource);
  3225. }
  3226. }
  3227. return true;
  3228. }
  3229. virtual IPropertyTreeIterator* getResourceIterator(SecResourceType rtype, const char * basedn,
  3230. const char* prefix, const char* resourceName, unsigned extraNameFilter)
  3231. {
  3232. IArrayOf<ISecResource> resources;
  3233. getResources(nullptr, rtype, basedn, prefix, resourceName, resources);
  3234. Owned<IPTree> resourceTree = createPTree("Resources");
  3235. ForEachItemIn(i, resources)
  3236. {
  3237. ISecResource& resource = resources.item(i);
  3238. const char* resourceName = resource.getName();
  3239. if (!resourceName || !*resourceName)
  3240. continue;
  3241. if (checkResourceNameExtraFilter(rtype, resourceName, extraNameFilter))
  3242. addResourceTree(resourceName, resource.getDescription(), resourceTree);
  3243. }
  3244. return resourceTree->getElements("*");
  3245. }
  3246. bool checkResourceNameExtraFilter(SecResourceType rtype, const char* name, unsigned extraNameFilter)
  3247. {
  3248. if((rtype == RT_FILE_SCOPE) && (extraNameFilter & RF_RT_FILE_SCOPE_FILE) && strieq(name, "file"))
  3249. return false;
  3250. if((rtype == RT_MODULE) && (extraNameFilter & RF_RT_MODULE_NO_REPOSITORY) && strnicmp(name, "repository.", 11))
  3251. return false;
  3252. return true;
  3253. }
  3254. void addResourceTree(const char* name, const char* desc, IPropertyTree* elements)
  3255. {
  3256. if (!name || !*name)
  3257. {
  3258. DBGLOG("CLdapClient::addResourceTree resource name must be provided");
  3259. return;
  3260. }
  3261. Owned<IPTree> element = createPTree();
  3262. element->addProp(getResourceFieldNames(RFName), name);
  3263. if (desc && *desc)
  3264. element->addProp(getResourceFieldNames(RFDesc), desc);
  3265. elements->addPropTree("Resource", element.getClear());
  3266. }
  3267. ISecItemIterator* getResourcesSorted(SecResourceType rtype, const char * basedn, const char* resourceName, unsigned extraNameFilter,
  3268. ResourceField* sortOrder, const unsigned pageStartFrom, const unsigned pageSize, unsigned* total, __int64* cacheHint)
  3269. {
  3270. class CElementsPager : public CSimpleInterface, implements IElementsPager
  3271. {
  3272. ILdapClient* ldapClient;
  3273. StringAttr sortOrder, basedn, resourceName;
  3274. SecResourceType rtype;
  3275. unsigned extraNameFilter;
  3276. public:
  3277. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  3278. CElementsPager(ILdapClient* _ldapClient, SecResourceType _rtype, const char * _basedn, const char* _resourceName,
  3279. unsigned _extraNameFilter, const char*_sortOrder) : ldapClient(_ldapClient), rtype(_rtype), basedn(_basedn),
  3280. resourceName(_resourceName), extraNameFilter(_extraNameFilter), sortOrder(_sortOrder) { };
  3281. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree>& elements)
  3282. {
  3283. StringArray unknownAttributes;
  3284. Owned<IPropertyTreeIterator> iter = ldapClient->getResourceIterator(rtype, basedn.get(), "", resourceName.get(), extraNameFilter);
  3285. sortElements(iter, sortOrder.get(), NULL, NULL, unknownAttributes, elements);
  3286. return NULL;
  3287. }
  3288. virtual bool allMatchingElementsReceived() { return true; }//For now, ldap always returns all of matched users.
  3289. };
  3290. StringBuffer so;
  3291. if (sortOrder)
  3292. {
  3293. for (unsigned i=0;sortOrder[i]!=RFterm;i++)
  3294. {
  3295. if (so.length())
  3296. so.append(',');
  3297. int fmt = sortOrder[i];
  3298. if (fmt & RFreverse)
  3299. so.append('-');
  3300. if (fmt & RFnocase)
  3301. so.append('?');
  3302. if (fmt & RFnumeric)
  3303. so.append('#');
  3304. so.append(getResourceFieldNames((ResourceField) (fmt&0xff)));
  3305. }
  3306. }
  3307. IArrayOf<IPropertyTree> results;
  3308. Owned<IElementsPager> elementsPager = new CElementsPager(this, rtype, basedn, resourceName, extraNameFilter, so.length()?so.str():NULL);
  3309. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager, pageStartFrom, pageSize, NULL, "", cacheHint, results, total, NULL, false);
  3310. return new CSecItemIterator(results);
  3311. }
  3312. virtual bool getPermissionsArray(const char* basedn, SecResourceType rtype, const char* name, IArrayOf<CPermission>& permissions)
  3313. {
  3314. StringBuffer basednbuf;
  3315. LdapUtils::normalizeDn(basedn, m_ldapconfig->getBasedn(), basednbuf);
  3316. Owned<CSecurityDescriptor> sd = new CSecurityDescriptor(name);
  3317. IArrayOf<CSecurityDescriptor> sdlist;
  3318. sdlist.append(*LINK(sd));
  3319. if(rtype == RT_FILE_SCOPE || rtype == RT_WORKUNIT_SCOPE)
  3320. getSecurityDescriptorsScope(sdlist, basednbuf.str());
  3321. else
  3322. getSecurityDescriptors(sdlist, basednbuf.str());
  3323. m_pp->getPermissionsArray(sd.get(), permissions);
  3324. return true;
  3325. }
  3326. SecResourceType str2RType(const char* rtstr)
  3327. {
  3328. if(isEmptyString(rtstr))
  3329. return RT_DEFAULT;
  3330. else if(strieq(rtstr, "module"))
  3331. return RT_MODULE;
  3332. else if(strieq(rtstr, "service"))
  3333. return RT_SERVICE;
  3334. else if(strieq(rtstr, "file"))
  3335. return RT_FILE_SCOPE;
  3336. else if(strieq(rtstr, "workunit"))
  3337. return RT_WORKUNIT_SCOPE;
  3338. else
  3339. return RT_DEFAULT;
  3340. }
  3341. void addPermissionTree(CPermission& permission, enum ACCOUNT_TYPE_REQ accountType, IPropertyTree* permissionTree)
  3342. {
  3343. const char* accountName = permission.getAccount_name();
  3344. if(isEmptyString(accountName))
  3345. return;
  3346. ACT_TYPE type = permission.getAccount_type();
  3347. if ((accountType != REQ_ANY_ACT) && (type != (ACT_TYPE) accountType))
  3348. return;
  3349. Owned<IPTree> permissionNode = createPTree();
  3350. permissionNode->setProp(getResourcePermissionFieldNames(RPFName), accountName);
  3351. permissionNode->setPropInt(getResourcePermissionFieldNames(RPFType), type);
  3352. permissionNode->setPropInt(getResourcePermissionFieldNames(RPFAllow), permission.getAllows());
  3353. permissionNode->setPropInt(getResourcePermissionFieldNames(RPFDeny), permission.getDenies());
  3354. permissionTree->addPropTree("Permission", permissionNode.getClear());
  3355. }
  3356. virtual IPropertyTreeIterator* getResourcePermissionIterator(const char* name, enum ACCOUNT_TYPE_REQ accountType, const char* baseDN,
  3357. const char* rtype, const char* prefix)
  3358. {
  3359. StringBuffer namebuf(name);
  3360. SecResourceType type = str2RType(rtype);
  3361. if((type == RT_MODULE) && !strieq(name, "repository") && (strnicmp(name, "repository.", 11) != 0))
  3362. namebuf.insert(0, "repository.");
  3363. if(prefix && *prefix)
  3364. namebuf.insert(0, prefix);
  3365. IArrayOf<CPermission> permissions;
  3366. getPermissionsArray(baseDN, type, namebuf.str(), permissions);
  3367. Owned<IPropertyTree> permissionTree = createPTree("Permissions");
  3368. ForEachItemIn(i, permissions)
  3369. addPermissionTree(permissions.item(i), accountType, permissionTree);
  3370. return permissionTree->getElements("*");
  3371. }
  3372. ISecItemIterator* getResourcePermissionsSorted(const char* name, enum ACCOUNT_TYPE_REQ accountType, const char* baseDN, const char* rtype,
  3373. const char* prefix, ResourcePermissionField* sortOrder, const unsigned pageStartFrom, const unsigned pageSize,
  3374. unsigned* total, __int64* cacheHint)
  3375. {
  3376. class CElementsPager : public CSimpleInterface, implements IElementsPager
  3377. {
  3378. ILdapClient* ldapClient;
  3379. StringAttr sortOrder, name, baseDN, rtype, prefix;
  3380. enum ACCOUNT_TYPE_REQ accountType;
  3381. public:
  3382. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  3383. CElementsPager(ILdapClient* _ldapClient, const char* _name, enum ACCOUNT_TYPE_REQ _accountType, const char* _baseDN,
  3384. const char* _rtype, const char* _prefix, const char*_sortOrder) : ldapClient(_ldapClient), name(_name),
  3385. accountType(_accountType), baseDN(_baseDN), rtype(_rtype), prefix(_prefix), sortOrder(_sortOrder) { };
  3386. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree>& elements)
  3387. {
  3388. StringArray unknownAttributes;
  3389. Owned<IPropertyTreeIterator> iter = ldapClient->getResourcePermissionIterator(name.get(), accountType, baseDN.get(), rtype.get(), prefix.get());
  3390. sortElements(iter, sortOrder.get(), NULL, NULL, unknownAttributes, elements);
  3391. return NULL;
  3392. }
  3393. virtual bool allMatchingElementsReceived() { return true; }//For now, ldap always returns all of matched users.
  3394. };
  3395. StringBuffer so;
  3396. if (sortOrder)
  3397. {
  3398. for (unsigned i=0; sortOrder[i]!=RPFterm; i++)
  3399. {
  3400. if (so.length())
  3401. so.append(',');
  3402. int fmt = sortOrder[i];
  3403. if (fmt&RPFreverse)
  3404. so.append('-');
  3405. if (fmt&RPFnocase)
  3406. so.append('?');
  3407. if (fmt&RPFnumeric)
  3408. so.append('#');
  3409. so.append(getResourcePermissionFieldNames((ResourcePermissionField) (fmt&0xff)));
  3410. }
  3411. }
  3412. IArrayOf<IPropertyTree> results;
  3413. Owned<IElementsPager> elementsPager = new CElementsPager(this, name, accountType, baseDN, rtype, prefix, so.length()?so.str():NULL);
  3414. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager, pageStartFrom, pageSize, NULL, "", cacheHint, results, total, NULL, false);
  3415. return new CSecItemIterator(results);
  3416. }
  3417. virtual void getAllGroups(StringArray & groups, StringArray & managedBy, StringArray & descriptions, const char * baseDN=nullptr)
  3418. {
  3419. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  3420. {
  3421. groups.append("Authenticated Users");
  3422. managedBy.append("");
  3423. descriptions.append("");
  3424. if (!m_ldapconfig->isAzureAD())
  3425. {
  3426. groups.append("Administrators");
  3427. managedBy.append("");
  3428. descriptions.append("");
  3429. }
  3430. }
  3431. else
  3432. {
  3433. groups.append("Directory Administrators");
  3434. managedBy.append("");
  3435. descriptions.append("");
  3436. }
  3437. char *attribute;
  3438. LDAPMessage *message;
  3439. StringBuffer filter;
  3440. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  3441. filter.append("objectClass=group");
  3442. else
  3443. filter.append("objectClass=groupofuniquenames");
  3444. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  3445. Owned<ILdapConnection> lconn = m_connections->getConnection();
  3446. LDAP* ld = lconn.get()->getLd();
  3447. char *attrs[] = {"cn", "managedBy", "description", NULL};
  3448. CPagedLDAPSearch pagedSrch(ld, m_ldapconfig->getLdapTimeout(), baseDN==nullptr ? (char*)m_ldapconfig->getGroupBasedn() : (char*)baseDN, LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs);
  3449. for (message = pagedSrch.getFirstEntry(); message; message = pagedSrch.getNextEntry())
  3450. {
  3451. // Go through the search results by checking message types
  3452. CLDAPGetAttributesWrapper atts(ld, message);
  3453. for ( attribute = atts.getFirst();
  3454. attribute != NULL;
  3455. attribute = atts.getNext())
  3456. {
  3457. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  3458. if (!vals.hasValues())
  3459. continue;
  3460. if(stricmp(attribute, "cn") == 0)
  3461. {
  3462. groups.append(vals.queryCharValue(0));
  3463. managedBy.append("");
  3464. descriptions.append("");
  3465. }
  3466. else if(stricmp(attribute, "managedBy") == 0)
  3467. managedBy.replace(vals.queryCharValue(0), groups.length() - 1);
  3468. else if(stricmp(attribute, "description") == 0)
  3469. descriptions.replace(vals.queryCharValue(0), groups.length() - 1);
  3470. }
  3471. }
  3472. }
  3473. virtual IPropertyTreeIterator* getGroupIterator()
  3474. {
  3475. StringArray groupNames, managedBy, descriptions;
  3476. getAllGroups(groupNames, managedBy, descriptions);
  3477. Owned<IPTree> groups = createPTree("Groups");
  3478. ForEachItemIn(i, groupNames)
  3479. addGroupTree(groupNames.item(i), managedBy.item(i), descriptions.item(i), groups);
  3480. return groups->getElements("*");
  3481. }
  3482. void addGroupTree(const char* name, const char* manageBy, const char* desc, IPropertyTree* groups)
  3483. {
  3484. if (!name || !*name)
  3485. {
  3486. DBGLOG("CLdapClient::addGroupTree groupname must be provided");
  3487. return;
  3488. }
  3489. Owned<IPTree> group = createPTree();
  3490. group->addProp(getGroupFieldNames(GFName), name);
  3491. if (manageBy && *manageBy)
  3492. group->addProp(getGroupFieldNames(GFManagedBy), manageBy);
  3493. if (desc && *desc)
  3494. group->addProp(getGroupFieldNames(GFDesc), desc);
  3495. groups->addPropTree("Group", group.getClear());
  3496. }
  3497. ISecItemIterator* getGroupsSorted(GroupField* sortOrder, const unsigned pageStartFrom, const unsigned pageSize, unsigned* total, __int64* cacheHint)
  3498. {
  3499. class CElementsPager : public CSimpleInterface, implements IElementsPager
  3500. {
  3501. ILdapClient* ldapClient;
  3502. StringAttr sortOrder;
  3503. public:
  3504. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  3505. CElementsPager(ILdapClient* _ldapClient, const char*_sortOrder)
  3506. : ldapClient(_ldapClient), sortOrder(_sortOrder) { };
  3507. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree>& elements)
  3508. {
  3509. StringArray unknownAttributes;
  3510. Owned<IPropertyTreeIterator> iter = ldapClient->getGroupIterator();
  3511. sortElements(iter, sortOrder.get(), NULL, NULL, unknownAttributes, elements);
  3512. return NULL;
  3513. }
  3514. virtual bool allMatchingElementsReceived() { return true; }//For now, ldap always returns all of matched users.
  3515. };
  3516. StringBuffer so;
  3517. if (sortOrder)
  3518. {
  3519. for (unsigned i=0;sortOrder[i]!=GFterm;i++)
  3520. {
  3521. if (so.length())
  3522. so.append(',');
  3523. int fmt = sortOrder[i];
  3524. if (fmt & GFreverse)
  3525. so.append('-');
  3526. if (fmt & GFnocase)
  3527. so.append('?');
  3528. if (fmt & GFnumeric)
  3529. so.append('#');
  3530. so.append(getGroupFieldNames((GroupField) (fmt&0xff)));
  3531. }
  3532. }
  3533. IArrayOf<IPropertyTree> results;
  3534. Owned<IElementsPager> elementsPager = new CElementsPager(this, so.length()?so.str():NULL);
  3535. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager, pageStartFrom, pageSize, NULL, "", cacheHint, results, total, NULL, false);
  3536. return new CSecItemIterator(results);
  3537. }
  3538. virtual bool changePermission(CPermissionAction& action)
  3539. {
  3540. StringBuffer basednbuf;
  3541. LdapUtils::normalizeDn(action.m_basedn.str(), m_ldapconfig->getBasedn(), basednbuf);
  3542. Owned<CSecurityDescriptor> sd = new CSecurityDescriptor(action.m_rname.str());
  3543. IArrayOf<CSecurityDescriptor> sdlist;
  3544. sdlist.append(*LINK(sd));
  3545. if(action.m_rtype == RT_FILE_SCOPE || action.m_rtype == RT_WORKUNIT_SCOPE)
  3546. getSecurityDescriptorsScope(sdlist, basednbuf.str());
  3547. else
  3548. getSecurityDescriptors(sdlist, basednbuf.str());
  3549. if(m_ldapconfig->getServerType() != ACTIVE_DIRECTORY)
  3550. {
  3551. StringBuffer act_dn;
  3552. if(action.m_account_type == GROUP_ACT)
  3553. getGroupDN(action.m_account_name.str(), act_dn);
  3554. else
  3555. getUserDN(action.m_account_name.str(), act_dn);
  3556. action.m_account_name.clear().append(act_dn.str());
  3557. }
  3558. Owned<CSecurityDescriptor> newsd = m_pp->changePermission(sd.get(), action);
  3559. StringBuffer normdnbuf;
  3560. LdapServerType servertype = m_ldapconfig->getServerType();
  3561. name2dn(action.m_rtype, action.m_rname.str(), action.m_basedn.str(), normdnbuf);
  3562. char *empty_values[] = { NULL };
  3563. int numberOfSegs = m_pp->sdSegments(newsd.get());
  3564. LDAPMod *attrs[2];
  3565. LDAPMod sd_attr;
  3566. if(newsd->getDescriptor().length() > 0)
  3567. {
  3568. struct berval** sd_values = (struct berval**)alloca(sizeof(struct berval*)*(numberOfSegs+1));
  3569. MemoryBuffer& sdbuf = newsd->getDescriptor();
  3570. // Active Directory acutally has only one segment.
  3571. if(servertype == ACTIVE_DIRECTORY)
  3572. {
  3573. struct berval* sd_val = (struct berval*)alloca(sizeof(struct berval));
  3574. sd_val->bv_len = sdbuf.length();
  3575. sd_val->bv_val = (char*)sdbuf.toByteArray();
  3576. sd_values[0] = sd_val;
  3577. sd_values[1] = NULL;
  3578. sd_attr.mod_type = "nTSecurityDescriptor";
  3579. }
  3580. else
  3581. {
  3582. const char* bbptr = sdbuf.toByteArray();
  3583. const char* bptr = sdbuf.toByteArray();
  3584. int sdbuflen = sdbuf.length();
  3585. int segind;
  3586. for(segind = 0; segind < numberOfSegs; segind++)
  3587. {
  3588. if(bptr - bbptr >= sdbuflen)
  3589. break;
  3590. while(*bptr == '\0' && (bptr - bbptr) < sdbuflen)
  3591. bptr++;
  3592. const char* eptr = bptr;
  3593. while(*eptr != '\0' && (eptr - bbptr) < sdbuflen)
  3594. eptr++;
  3595. struct berval* sd_val = (struct berval*)alloca(sizeof(struct berval));
  3596. sd_val->bv_len = eptr - bptr;
  3597. sd_val->bv_val = (char*)bptr;
  3598. sd_values[segind] = sd_val;
  3599. bptr = eptr + 1;
  3600. }
  3601. sd_values[segind] = NULL;
  3602. sd_attr.mod_type = (char*)m_ldapconfig->getSdFieldName();
  3603. }
  3604. sd_attr.mod_op = LDAP_MOD_REPLACE | LDAP_MOD_BVALUES;
  3605. sd_attr.mod_vals.modv_bvals = sd_values;
  3606. attrs[0] = &sd_attr;
  3607. }
  3608. else
  3609. {
  3610. if(m_ldapconfig->getServerType() == OPEN_LDAP)
  3611. throw MakeStringException(-1, "removing all permissions for openldap is currently not supported");
  3612. sd_attr.mod_op = LDAP_MOD_DELETE;
  3613. sd_attr.mod_type = (char*)m_ldapconfig->getSdFieldName();
  3614. sd_attr.mod_vals.modv_strvals = empty_values;
  3615. attrs[0] = &sd_attr;
  3616. }
  3617. attrs[1] = NULL;
  3618. SDServerCtlWrapper ctlwrapper(m_ldapconfig->isAzureAD());
  3619. Owned<ILdapConnection> lconn = m_connections->getConnection();
  3620. LDAP* ld = lconn.get()->getLd();
  3621. int rc = ldap_modify_ext_s(ld, (char*)normdnbuf.str(), attrs, ctlwrapper.ctls, NULL);
  3622. if ( rc != LDAP_SUCCESS )
  3623. {
  3624. throw MakeStringException(-1, "ldap_modify_ext_s error: %d %s", rc, ldap_err2string( rc ));
  3625. }
  3626. return true;
  3627. }
  3628. virtual void getGroups(const char *user, StringArray& groups)
  3629. {
  3630. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  3631. {
  3632. char *attribute;
  3633. LDAPMessage *message;
  3634. if(user == NULL || strlen(user) == 0)
  3635. {
  3636. DBGLOG("CLdapClient::getGroups username must be provided");
  3637. return;
  3638. }
  3639. StringBuffer filter("sAMAccountName=");
  3640. filter.append(user);
  3641. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  3642. Owned<ILdapConnection> lconn = m_connections->getConnection();
  3643. LDAP* ld = lconn.get()->getLd();
  3644. char *attrs[] = {"memberOf", NULL};
  3645. CLDAPMessage searchResult;
  3646. int rc = ldap_search_ext_s(ld, (char*)m_ldapconfig->getUserBasedn(), LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs, 0, NULL, NULL, &timeOut, LDAP_NO_LIMIT, &searchResult.msg );
  3647. if ( rc != LDAP_SUCCESS )
  3648. {
  3649. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), m_ldapconfig->getUserBasedn());
  3650. return;
  3651. }
  3652. unsigned entries = ldap_count_entries(ld, searchResult);
  3653. if(entries == 0)
  3654. {
  3655. searchResult.ldapMsgFree();
  3656. rc = ldap_search_ext_s(ld, (char*)m_ldapconfig->getSysUserBasedn(), LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs, 0, NULL, NULL, &timeOut, LDAP_NO_LIMIT, &searchResult.msg );
  3657. if ( rc != LDAP_SUCCESS )
  3658. {
  3659. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), m_ldapconfig->getSysUserBasedn());
  3660. return;
  3661. }
  3662. }
  3663. // Go through the search results by checking message types
  3664. for(message = LdapFirstEntry( ld, searchResult); message != NULL; message = ldap_next_entry(ld, message))
  3665. {
  3666. CLDAPGetAttributesWrapper atts(ld, searchResult);
  3667. for ( attribute = atts.getFirst();
  3668. attribute != NULL;
  3669. attribute = atts.getNext())
  3670. {
  3671. if(0 == stricmp(attribute, "memberOf"))
  3672. {
  3673. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  3674. if (vals.hasValues())
  3675. {
  3676. for (int i = 0; vals.queryBValues()[ i ] != NULL; i++ )
  3677. {
  3678. const char* val = vals.queryCharValue(i);
  3679. char* comma = strchr((char*)val, ',');
  3680. StringBuffer groupname;
  3681. groupname.append(comma - val -3, val+3);
  3682. groups.append(groupname.str());
  3683. }
  3684. }
  3685. }
  3686. }
  3687. }
  3688. }
  3689. else
  3690. {
  3691. StringArray allgroups;
  3692. StringArray allgroupManagedBy;
  3693. StringArray allgroupDescription;
  3694. getAllGroups(allgroups, allgroupManagedBy, allgroupDescription);
  3695. for(unsigned i = 0; i < allgroups.length(); i++)
  3696. {
  3697. const char* grp = allgroups.item(i);
  3698. StringBuffer grpdn, usrdn;
  3699. getUserDN(user, usrdn);
  3700. getGroupDN(grp, grpdn);
  3701. if(userInGroup(usrdn.str(), grpdn.str()))
  3702. {
  3703. groups.append(grp);
  3704. }
  3705. }
  3706. }
  3707. }
  3708. virtual void changeUserGroup(const char* action, const char* username, const char* groupname, const char * groupDN=nullptr)
  3709. {
  3710. StringBuffer userdn, groupdn;
  3711. getUserDN(username, userdn);
  3712. getGroupDN(groupname, groupdn, groupDN);
  3713. // Not needed for Active Directory
  3714. // changeUserMemberOf(action, userdn.str(), groupdn.str());
  3715. changeGroupMember(action, groupdn.str(), userdn.str());
  3716. }
  3717. virtual bool deleteUser(ISecUser* user)
  3718. {
  3719. if(user == NULL)
  3720. {
  3721. DBGLOG("CLdapClient::deleteUser ISecUser must be provided");
  3722. return false;
  3723. }
  3724. const char* username = user->getName();
  3725. if(username == NULL || *username == '\0')
  3726. {
  3727. DBGLOG("CLdapClient::deleteUser username must be provided");
  3728. return false;
  3729. }
  3730. StringBuffer userdn;
  3731. getUserDN(username, userdn);
  3732. Owned<ILdapConnection> lconn = m_connections->getConnection();
  3733. LDAP* ld = lconn.get()->getLd();
  3734. int rc = ldap_delete_ext_s(ld, (char*)userdn.str(), NULL, NULL);
  3735. if ( rc != LDAP_SUCCESS )
  3736. {
  3737. throw MakeStringException(-1, "error deleting user %s: %s", username, ldap_err2string(rc));
  3738. }
  3739. StringArray grps;
  3740. getGroups(username, grps);
  3741. ForEachItemIn(x, grps)
  3742. {
  3743. const char* grp = grps.item(x);
  3744. if(!grp || !*grp)
  3745. continue;
  3746. changeUserGroup("delete", username, grp);
  3747. }
  3748. //Remove tempfile scope for this user
  3749. StringBuffer resName(queryDfsXmlBranchName(DXB_Internal));
  3750. resName.append("::").append(username);
  3751. deleteResource(RT_FILE_SCOPE, resName.str(), m_ldapconfig->getResourceBasedn(RT_FILE_SCOPE));
  3752. return true;
  3753. }
  3754. virtual void addGroup(const char* groupname, const char * groupOwner, const char * groupDesc)
  3755. {
  3756. if(groupname == NULL || *groupname == '\0')
  3757. throw MakeStringException(-1, "Can't add group, groupname is empty");
  3758. addGroup(groupname, groupOwner, groupDesc, m_ldapconfig->getGroupBasedn());
  3759. }
  3760. virtual void addGroup(const char* groupname, const char * groupOwner, const char * groupDesc, const char* basedn)
  3761. {
  3762. if(groupname == NULL || *groupname == '\0')
  3763. {
  3764. DBGLOG("CLdapClient::addGroup groupname must be provided");
  3765. return;
  3766. }
  3767. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  3768. {
  3769. if(stricmp(groupname, "Administrators") == 0)
  3770. throw MakeStringException(-1, "Can't add group %s, it's reserved by the system.", groupname);
  3771. }
  3772. else
  3773. {
  3774. if(stricmp(groupname, "Directory Administrators") == 0)
  3775. throw MakeStringException(-1, "Can't add group %s, it's reserved by the system.", groupname);
  3776. }
  3777. StringBuffer dn;
  3778. dn.append("cn=").append(groupname).append(",").append(basedn);
  3779. char* oc_name;
  3780. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  3781. {
  3782. oc_name = "group";
  3783. }
  3784. else
  3785. {
  3786. oc_name = "groupofuniquenames";
  3787. }
  3788. char *cn_values[] = {(char*)groupname, NULL };
  3789. LDAPMod cn_attr =
  3790. {
  3791. LDAP_MOD_ADD,
  3792. "cn",
  3793. cn_values
  3794. };
  3795. char *oc_values[] = {oc_name, NULL };
  3796. LDAPMod oc_attr =
  3797. {
  3798. LDAP_MOD_ADD,
  3799. "objectClass",
  3800. oc_values
  3801. };
  3802. char *member_values[] = {"", NULL};
  3803. LDAPMod member_attr =
  3804. {
  3805. LDAP_MOD_ADD,
  3806. "uniqueMember",
  3807. member_values
  3808. };
  3809. char *owner_values[] = {(char*)groupOwner, NULL};
  3810. LDAPMod owner_attr =
  3811. {
  3812. LDAP_MOD_ADD,
  3813. "managedBy",
  3814. owner_values
  3815. };
  3816. char *desc_values[] = {(char*)groupDesc, NULL};
  3817. LDAPMod desc_attr =
  3818. {
  3819. LDAP_MOD_ADD,
  3820. "description",
  3821. desc_values
  3822. };
  3823. LDAPMod *attrs[6];
  3824. int ind = 0;
  3825. attrs[ind++] = &cn_attr;
  3826. attrs[ind++] = &oc_attr;
  3827. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  3828. {
  3829. if (groupOwner && *groupOwner)
  3830. attrs[ind++] = &owner_attr;
  3831. }
  3832. if (groupDesc && *groupDesc)
  3833. attrs[ind++] = &desc_attr;
  3834. attrs[ind] = NULL;
  3835. Owned<ILdapConnection> lconn = m_connections->getConnection();
  3836. LDAP* ld = lconn.get()->getLd();
  3837. int rc = ldap_add_ext_s(ld, (char*)dn.str(), attrs, NULL, NULL);
  3838. if ( rc == LDAP_INVALID_SYNTAX && m_ldapconfig->getServerType() == OPEN_LDAP)//Fedora389 does not 'seem' to need this, openLDAP does
  3839. {
  3840. attrs[ind++] = &member_attr;
  3841. attrs[ind] = NULL;
  3842. rc = ldap_add_ext_s(ld, (char*)dn.str(), attrs, NULL, NULL);
  3843. }
  3844. if ( rc != LDAP_SUCCESS)
  3845. {
  3846. if(rc == LDAP_ALREADY_EXISTS)
  3847. {
  3848. throw MakeStringException(-1, "can't add group %s, an LDAP object with this name already exists", groupname);
  3849. }
  3850. else
  3851. {
  3852. DBGLOG("error addGroup %s, ldap_add_ext_s error: %s", groupname, ldap_err2string( rc ));
  3853. throw MakeStringException(-1, "error addGroup %s, ldap_add_ext_s error: %s", groupname, ldap_err2string( rc ));
  3854. }
  3855. }
  3856. }
  3857. virtual void deleteGroup(const char* groupname, const char * groupsDN=nullptr)
  3858. {
  3859. if(groupname == NULL || *groupname == '\0')
  3860. throw MakeStringException(-1, "group name can't be empty");
  3861. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  3862. {
  3863. if(stricmp(groupname, "Administrators") == 0 || stricmp(groupname, "Authenticated Users") == 0)
  3864. throw MakeStringException(-1, "you can't delete Authenticated Users or Administrators group");
  3865. }
  3866. else
  3867. {
  3868. if(stricmp(groupname, "Directory Administrators") == 0)
  3869. throw MakeStringException(-1, "you can't delete Directory Administrators group");
  3870. }
  3871. StringBuffer dn;
  3872. getGroupDN(groupname, dn, groupsDN);
  3873. Owned<ILdapConnection> lconn = m_connections->getConnection();
  3874. LDAP* ld = lconn.get()->getLd();
  3875. int rc = ldap_delete_ext_s(ld, (char*)dn.str(), NULL, NULL);
  3876. if ( rc != LDAP_SUCCESS )
  3877. {
  3878. throw MakeStringException(-1, "error deleting group %s: %s", groupname, ldap_err2string(rc));
  3879. }
  3880. }
  3881. virtual void getGroupMembers(const char* groupname, StringArray & users, const char * groupsDN=nullptr)
  3882. {
  3883. char *attribute;
  3884. LDAPMessage *message;
  3885. if(groupname == NULL || strlen(groupname) == 0)
  3886. throw MakeStringException(-1, "group name can't be empty");
  3887. StringBuffer grpdn;
  3888. getGroupDN(groupname, grpdn, groupsDN);
  3889. StringBuffer filter;
  3890. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  3891. {
  3892. filter.append("distinguishedName=").append(grpdn.str());
  3893. }
  3894. else if(m_ldapconfig->getServerType() == IPLANET)
  3895. {
  3896. filter.append("entrydn=").append(grpdn.str());
  3897. }
  3898. else if(m_ldapconfig->getServerType() == OPEN_LDAP)
  3899. {
  3900. filter.append("cn=").append(groupname);
  3901. }
  3902. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  3903. Owned<ILdapConnection> lconn = m_connections->getConnection();
  3904. LDAP* ld = lconn.get()->getLd();
  3905. const char* memfieldname;
  3906. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  3907. {
  3908. memfieldname = "member";
  3909. }
  3910. else
  3911. {
  3912. memfieldname = "uniquemember";
  3913. }
  3914. char *attrs[] = {(char*)memfieldname, NULL};
  3915. StringBuffer groupbasedn;
  3916. getGroupBaseDN(groupname, groupbasedn, groupsDN);
  3917. CPagedLDAPSearch pagedSrch(ld, m_ldapconfig->getLdapTimeout(), (char*)groupbasedn.str(), LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs);
  3918. for (message = pagedSrch.getFirstEntry(); message; message = pagedSrch.getNextEntry())
  3919. {
  3920. // Go through the search results by checking message types
  3921. CLDAPGetAttributesWrapper atts(ld, message);
  3922. for ( attribute = atts.getFirst();
  3923. attribute != NULL;
  3924. attribute = atts.getNext())
  3925. {
  3926. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  3927. if (vals.hasValues())
  3928. {
  3929. for (int i = 0; vals.queryBValues()[ i ] != NULL; i++ )
  3930. {
  3931. const char* val = vals.queryCharValue(i);
  3932. StringBuffer uid;
  3933. getUidFromDN(ld, val, uid);
  3934. if(uid.length() > 0)
  3935. users.append(uid.str());
  3936. }
  3937. }
  3938. }
  3939. }
  3940. }
  3941. virtual IPropertyTreeIterator* getGroupMemberIterator(const char* groupName)
  3942. {
  3943. StringArray users;
  3944. getGroupMembers(groupName, users);
  3945. Owned<IPropertyTree> usersTree = createPTree("Users");
  3946. ForEachItemIn(i, users)
  3947. {
  3948. const char* usrName = users.item(i);
  3949. if (!usrName || !*usrName)
  3950. continue;
  3951. IUserArray usersInBaseDN;
  3952. retrieveUsers(usrName, usersInBaseDN);
  3953. ForEachItemIn(x, usersInBaseDN)
  3954. {
  3955. ISecUser& usr = usersInBaseDN.item(x);
  3956. const char* usrName0 = usr.getName();
  3957. if(usrName0 && strieq(usrName, usrName0))
  3958. {
  3959. //BUG#41536: The users in the Administrators group are all the users on the whole
  3960. //active directory, while the users in the users list are only the users who are
  3961. //under the "usersBasedn" of this environment. So, we should only return the users
  3962. //who are in the usersBasedn.
  3963. addUserTree(usr, usersTree);
  3964. break;
  3965. }
  3966. }
  3967. }
  3968. return usersTree->getElements("*");
  3969. }
  3970. ISecItemIterator* getGroupMembersSorted(const char* groupName, UserField* sortOrder, const unsigned pageStartFrom, const unsigned pageSize,
  3971. unsigned* total, __int64* cacheHint)
  3972. {
  3973. class CElementsPager : public CSimpleInterface, implements IElementsPager
  3974. {
  3975. ILdapClient* ldapClient;
  3976. StringAttr sortOrder, groupName;
  3977. public:
  3978. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  3979. CElementsPager(ILdapClient* _ldapClient, const char*_groupName, const char*_sortOrder)
  3980. : ldapClient(_ldapClient), groupName(_groupName), sortOrder(_sortOrder) { };
  3981. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree>& elements)
  3982. {
  3983. StringArray unknownAttributes;
  3984. Owned<IPropertyTreeIterator> iter = ldapClient->getGroupMemberIterator(groupName.str());
  3985. sortElements(iter, sortOrder.get(), NULL, NULL, unknownAttributes, elements);
  3986. return NULL;
  3987. }
  3988. virtual bool allMatchingElementsReceived() { return true; }//For now, ldap always returns all of matched users.
  3989. };
  3990. StringBuffer so;
  3991. if (sortOrder)
  3992. {
  3993. for (unsigned i=0;sortOrder[i]!=UFterm;i++)
  3994. {
  3995. if (so.length())
  3996. so.append(',');
  3997. int fmt = sortOrder[i];
  3998. if (fmt&UFreverse)
  3999. so.append('-');
  4000. if (fmt&UFnocase)
  4001. so.append('?');
  4002. if (fmt&UFnumeric)
  4003. so.append('#');
  4004. so.append(getUserFieldNames((UserField) (fmt&0xff)));
  4005. }
  4006. }
  4007. IArrayOf<IPropertyTree> results;
  4008. Owned<IElementsPager> elementsPager = new CElementsPager(this, groupName, so.length()?so.str():NULL);
  4009. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager, pageStartFrom, pageSize, NULL, "", cacheHint, results, total, NULL, false);
  4010. return new CSecItemIterator(results);
  4011. }
  4012. virtual void deleteResource(SecResourceType rtype, const char* name, const char* basedn)
  4013. {
  4014. if(basedn == NULL || *basedn == '\0')
  4015. basedn = m_ldapconfig->getResourceBasedn(rtype);
  4016. StringBuffer dn;
  4017. name2dn(rtype, name, basedn, dn);
  4018. Owned<ILdapConnection> lconn = m_connections->getConnection();
  4019. LDAP* ld = lconn.get()->getLd();
  4020. int rc = ldap_delete_ext_s(ld, (char*)dn.str(), NULL, NULL);
  4021. if ( rc != LDAP_SUCCESS )
  4022. {
  4023. DBGLOG("error deleting %s: %s", dn.str(), ldap_err2string(rc));
  4024. //throw MakeStringException(-1, "error deleting %s: %s", dn.str(), ldap_err2string(rc));
  4025. }
  4026. }
  4027. virtual void renameResource(SecResourceType rtype, const char* oldname, const char* newname, const char* basedn)
  4028. {
  4029. if(oldname == NULL || *oldname == '\0' || newname == NULL || *newname == '\0')
  4030. throw MakeStringException(-1, "please specfiy old and new names");
  4031. if(basedn == NULL || *basedn == '\0')
  4032. basedn = m_ldapconfig->getResourceBasedn(rtype);
  4033. StringBuffer olddn, newrdn;
  4034. name2dn(rtype, oldname, basedn, olddn);
  4035. name2rdn(rtype, newname, newrdn);
  4036. Owned<ILdapConnection> lconn = m_connections->getConnection();
  4037. LDAP* ld = lconn.get()->getLd();
  4038. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY && (rtype == RT_DEFAULT || rtype == RT_MODULE || rtype == RT_SERVICE))
  4039. {
  4040. char* uncname_values[] = {(char*)newname, NULL};
  4041. LDAPMod uncname_attr =
  4042. {
  4043. LDAP_MOD_REPLACE,
  4044. "uNCName",
  4045. uncname_values
  4046. };
  4047. LDAPMod *attrs[2];
  4048. attrs[0] = &uncname_attr;
  4049. attrs[1] = NULL;
  4050. int rc = ldap_modify_ext_s(ld, (char*)olddn.str(), attrs, NULL, NULL);
  4051. if (rc != LDAP_SUCCESS )
  4052. {
  4053. DBGLOG("Error changing unc %s to %s - %s", oldname, newname, ldap_err2string( rc ));
  4054. //throw MakeStringException(-1, "Error changing unc %s to %s - %s", oldname, newname, ldap_err2string( rc ));
  4055. }
  4056. }
  4057. #ifdef _WIN32
  4058. int rc = ldap_rename_ext_s(ld, (char*)olddn.str(), (char*)newrdn.str(), NULL, true, NULL, NULL);
  4059. #else
  4060. int rc = ldap_rename_s(ld, (char*)olddn.str(), (char*)newrdn.str(), NULL, true, NULL, NULL);
  4061. #endif
  4062. if (rc != LDAP_SUCCESS )
  4063. {
  4064. DBGLOG("Error renaming %s to %s - %s", oldname, newname, ldap_err2string( rc ));
  4065. //throw MakeStringException(-1, "Error renaming %s to %s - %s", oldname, newname, ldap_err2string( rc ));
  4066. }
  4067. }
  4068. virtual void copyResource(SecResourceType rtype, const char* oldname, const char* newname, const char* basedn)
  4069. {
  4070. if(oldname == NULL || *oldname == '\0' || newname == NULL || *newname == '\0')
  4071. throw MakeStringException(-1, "please specfiy old and new names");
  4072. if(basedn == NULL || *basedn == '\0')
  4073. basedn = m_ldapconfig->getResourceBasedn(rtype);
  4074. Owned<CSecurityDescriptor> sd = new CSecurityDescriptor(oldname);
  4075. IArrayOf<CSecurityDescriptor> sdlist;
  4076. sdlist.append(*LINK(sd));
  4077. if(rtype == RT_FILE_SCOPE || rtype == RT_WORKUNIT_SCOPE)
  4078. getSecurityDescriptorsScope(sdlist, basedn);
  4079. else
  4080. getSecurityDescriptors(sdlist, basedn);
  4081. if(sd->getDescriptor().length() == 0)
  4082. throw MakeStringException(-1, "error copying %s to %s, %s doesn't exist", oldname, newname, oldname);
  4083. ISecUser* user = NULL;
  4084. CLdapSecResource resource(newname);
  4085. addResource(rtype, *user, &resource, PT_ADMINISTRATORS_ONLY, basedn, sd.get(), false);
  4086. }
  4087. void normalizeDn(const char* dn, StringBuffer& ndn)
  4088. {
  4089. LdapUtils::normalizeDn(dn, m_ldapconfig->getBasedn(), ndn);
  4090. }
  4091. virtual bool isSuperUser(ISecUser* user)
  4092. {
  4093. if(user == NULL || user->getName() == NULL)
  4094. {
  4095. DBGLOG("CLdapClient::isSuperUser Populated ISecUser must be provided");
  4096. return false;
  4097. }
  4098. const char* username = user->getName();
  4099. const char* sysuser = m_ldapconfig->getSysUser();
  4100. if(sysuser != NULL && stricmp(sysuser, username) == 0)
  4101. return true;
  4102. StringBuffer userdn;
  4103. getUserDN(username, userdn);
  4104. return userInGroup(userdn.str(), m_ldapconfig->getAdminGroupDN());
  4105. }
  4106. virtual ILdapConfig* queryConfig()
  4107. {
  4108. return m_ldapconfig.get();
  4109. }
  4110. virtual int countUsers(const char* searchstr, int limit)
  4111. {
  4112. StringBuffer filter;
  4113. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  4114. filter.append("objectClass=User");
  4115. else
  4116. filter.append("objectClass=inetorgperson");
  4117. if(searchstr && *searchstr && strcmp(searchstr, "*") != 0)
  4118. {
  4119. filter.insert(0, "(&(");
  4120. filter.appendf(")(|(%s=*%s*)(%s=*%s*)(%s=*%s*)))", (m_ldapconfig->getServerType()==ACTIVE_DIRECTORY)?"sAMAcccountName":"uid", searchstr, "givenName", searchstr, "sn", searchstr);
  4121. }
  4122. return countEntries(m_ldapconfig->getUserBasedn(), filter.str(), limit);
  4123. }
  4124. virtual int countResources(const char* basedn, const char* searchstr, int limit)
  4125. {
  4126. StringBuffer filter;
  4127. filter.append("objectClass=*");
  4128. if(searchstr && *searchstr && strcmp(searchstr, "*") != 0)
  4129. {
  4130. filter.insert(0, "(&(");
  4131. filter.appendf(")(|(%s=*%s*)))", "uNCName", searchstr);
  4132. }
  4133. return countEntries(basedn, filter.str(), limit);
  4134. }
  4135. virtual int countEntries(const char* basedn, const char* filter, int limit)
  4136. {
  4137. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  4138. Owned<ILdapConnection> lconn = m_connections->getConnection();
  4139. LDAP* ld = lconn.get()->getLd();
  4140. char *attrs[] = { LDAP_NO_ATTRS, NULL };
  4141. CPagedLDAPSearch pagedSrch(ld, m_ldapconfig->getLdapTimeout(), (char*)basedn, LDAP_SCOPE_SUBTREE, (char*)filter, attrs);
  4142. int entries = pagedSrch.countEntries();
  4143. return entries;
  4144. }
  4145. virtual const char* getPasswordStorageScheme()
  4146. {
  4147. if(m_pwscheme.length() == 0)
  4148. {
  4149. if(m_ldapconfig->getServerType() == IPLANET)
  4150. {
  4151. Owned<ILdapConnection> lconn = m_connections->getConnection();
  4152. LDAP* ld = lconn.get()->getLd();
  4153. char* pw_attrs[] = {"nsslapd-rootpwstoragescheme", NULL};
  4154. CLDAPMessage msg;
  4155. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  4156. int err = ldap_search_ext_s(ld, "cn=config", LDAP_SCOPE_BASE, "objectClass=*", pw_attrs, false, NULL, NULL, &timeOut, LDAP_NO_LIMIT, &msg.msg);
  4157. if(err != LDAP_SUCCESS)
  4158. {
  4159. DBGLOG("ldap_search_ext_s error: %s", ldap_err2string( err ));
  4160. return NULL;
  4161. }
  4162. LDAPMessage* entry = LdapFirstEntry(ld, msg);
  4163. if(entry != NULL)
  4164. {
  4165. CLDAPGetValuesLenWrapper vals(ld, entry, "nsslapd-rootpwstoragescheme");
  4166. if (vals.hasValues())
  4167. m_pwscheme.append(vals.queryCharValue(0));
  4168. }
  4169. ldap_msgfree(msg);
  4170. }
  4171. }
  4172. if(m_pwscheme.length() == 0)
  4173. return NULL;
  4174. else
  4175. return m_pwscheme.str();
  4176. }
  4177. private:
  4178. class SDServerCtlWrapper
  4179. {
  4180. public:
  4181. LDAPControl **ctls = nullptr;
  4182. LDAPControl* ctl = nullptr;
  4183. StringBuffer oidbuf, valbuf;
  4184. SDServerCtlWrapper(bool isAzureAD)
  4185. {
  4186. if (isAzureAD)
  4187. {
  4188. oidbuf.append(AAD_LDAP_SERVER_SD_FLAGS_OID);
  4189. //48,3,2 are for ber-ans.1 encoding
  4190. //1 is the length of the data
  4191. //7 is the data, which is bit wise OR of owner info (0x1), group info (0x2) and discretionary ACL (0x4)
  4192. valbuf.appendf("%c%c%c%c%c", 48, 3, 2, 1, 7);
  4193. ctl = new LDAPControl;
  4194. ctl->ldctl_oid = (char*)oidbuf.str();
  4195. ctl->ldctl_value.bv_len = valbuf.length();
  4196. ctl->ldctl_value.bv_val = (char*)valbuf.str();
  4197. ctls = new LDAPControl*[2];
  4198. ctls[0] = ctl;
  4199. ctls[1] = nullptr;
  4200. }
  4201. }
  4202. ~SDServerCtlWrapper()
  4203. {
  4204. if (ctl)
  4205. delete ctl;
  4206. if (ctls)
  4207. delete []ctls;
  4208. }
  4209. };
  4210. virtual void addDC(const char* dc)
  4211. {
  4212. if(dc == NULL || *dc == '\0')
  4213. {
  4214. DBGLOG("CLdapClient::addDC dc must be provided");
  4215. return;
  4216. }
  4217. StringBuffer dcname;
  4218. LdapUtils::getName(dc, dcname);
  4219. char *dc_values[] = {(char*)dcname.str(), NULL };
  4220. LDAPMod dc_attr =
  4221. {
  4222. LDAP_MOD_ADD,
  4223. "dc",
  4224. dc_values
  4225. };
  4226. char *o_values[] = {(char*)dcname.str(), NULL };
  4227. LDAPMod o_attr =
  4228. {
  4229. LDAP_MOD_ADD,
  4230. "o",
  4231. o_values
  4232. };
  4233. char *oc_values[] = {"organization", "dcObject", NULL };
  4234. LDAPMod oc_attr =
  4235. {
  4236. LDAP_MOD_ADD,
  4237. "objectClass",
  4238. oc_values
  4239. };
  4240. LDAPMod *attrs[4];
  4241. attrs[0] = &oc_attr;
  4242. attrs[1] = &o_attr;
  4243. attrs[2] = &dc_attr;
  4244. attrs[3] = NULL;
  4245. Owned<ILdapConnection> lconn = m_connections->getConnection();
  4246. LDAP* ld = lconn.get()->getLd();
  4247. int rc = ldap_add_ext_s(ld, (char*)dc, attrs, NULL, NULL);
  4248. if ( rc != LDAP_SUCCESS )
  4249. {
  4250. if(rc == LDAP_ALREADY_EXISTS)
  4251. {
  4252. throw MakeStringException(-1, "can't add dc %s, an LDAP object with this name already exists", dc);
  4253. }
  4254. else
  4255. {
  4256. DBGLOG("error addDC %s, ldap_add_ext_s error: 0x%0x %s", dc, rc, ldap_err2string( rc ));
  4257. throw MakeStringException(-1, "error addDC %s, ldap_add_ext_s error: %s", dc, ldap_err2string( rc ));
  4258. }
  4259. }
  4260. }
  4261. virtual void getUserDN(const char* username, StringBuffer& userdn)
  4262. {
  4263. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  4264. {
  4265. StringBuffer filter;
  4266. filter.append("sAMAccountName=");
  4267. filter.append(username);
  4268. char *attribute;
  4269. LDAPMessage *message;
  4270. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  4271. char *dn_fieldname;
  4272. dn_fieldname = "distinguishedName";
  4273. Owned<ILdapConnection> lconn = m_connections->getConnection();
  4274. LDAP* ld = lconn.get()->getLd();
  4275. char *attrs[] = {dn_fieldname, NULL};
  4276. CLDAPMessage searchResult;
  4277. int rc = ldap_search_ext_s(ld, (char*)m_ldapconfig->getUserBasedn(), LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs, 0, NULL, NULL, &timeOut, LDAP_NO_LIMIT, &searchResult.msg );
  4278. if ( rc != LDAP_SUCCESS )
  4279. {
  4280. throw MakeStringException(-1, "ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), m_ldapconfig->getUserBasedn());
  4281. }
  4282. unsigned entries = ldap_count_entries(ld, searchResult);
  4283. if(entries == 0)
  4284. {
  4285. searchResult.ldapMsgFree();
  4286. int rc = ldap_search_ext_s(ld, (char*)m_ldapconfig->getSysUserBasedn(), LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs, 0, NULL, NULL, &timeOut, LDAP_NO_LIMIT, &searchResult.msg );
  4287. if ( rc != LDAP_SUCCESS )
  4288. {
  4289. throw MakeStringException(-1, "ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), m_ldapconfig->getSysUserBasedn());
  4290. }
  4291. }
  4292. message = LdapFirstEntry( ld, searchResult);
  4293. if(message != NULL)
  4294. {
  4295. CLDAPGetAttributesWrapper atts(ld, searchResult);
  4296. attribute = atts.getFirst();
  4297. if(attribute != NULL)
  4298. {
  4299. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  4300. if (vals.hasValues())
  4301. userdn.append(vals.queryCharValue(0));
  4302. }
  4303. }
  4304. if(userdn.length() == 0)
  4305. throw MakeStringException(-1, "user %s can't be found", username);
  4306. }
  4307. else
  4308. {
  4309. if(stricmp(username, "anyone") == 0)
  4310. userdn.append(username);
  4311. else
  4312. userdn.append("uid=").append(username).append(",").append(m_ldapconfig->getUserBasedn());
  4313. }
  4314. }
  4315. virtual void getUidFromDN(LDAP* ld, const char* dn, StringBuffer& uid)
  4316. {
  4317. if(dn == NULL || *dn == '\0')
  4318. {
  4319. DBGLOG("CLdapClient::getUidFromDN dn must be provided");
  4320. return;
  4321. }
  4322. if(m_ldapconfig->getServerType() != ACTIVE_DIRECTORY)
  4323. {
  4324. if (strncmp(dn,"uid=",4))//Fedora389 returns "cn=Directory Administrators"
  4325. return;
  4326. const char* comma = strchr(dn, ',');
  4327. // DN is in the format of "uid=uuu,ou=ooo,dc=dd"
  4328. uid.append(comma - dn - 4, dn + 4);
  4329. return;
  4330. }
  4331. StringBuffer filter;
  4332. filter.append("distinguishedName=").append(dn);
  4333. filter.replaceString("\\", "\\5c");//Replace special characters with valid UTF-8 string (see valueencoding rule in RFC 4515)
  4334. filter.replaceString("*", "\\2a");
  4335. filter.replaceString("(", "\\28");
  4336. filter.replaceString(")", "\\29");
  4337. char *attribute;
  4338. LDAPMessage *message;
  4339. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  4340. char *uid_fieldname = "sAMAccountName";
  4341. char *attrs[] = {uid_fieldname, NULL};
  4342. CLDAPMessage searchResult;
  4343. int rc = ldap_search_ext_s(ld, (char*)m_ldapconfig->getUserBasedn(), LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs, 0, NULL, NULL, &timeOut, LDAP_NO_LIMIT, &searchResult.msg );
  4344. if ( rc != LDAP_SUCCESS )
  4345. {
  4346. throw MakeStringException(-1, "ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), m_ldapconfig->getUserBasedn());
  4347. }
  4348. message = LdapFirstEntry( ld, searchResult);
  4349. if(message != NULL)
  4350. {
  4351. CLDAPGetAttributesWrapper atts(ld, searchResult);
  4352. attribute = atts.getFirst();
  4353. if(attribute != NULL)
  4354. {
  4355. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  4356. if (vals.hasValues())
  4357. uid.append(vals.queryCharValue(0));
  4358. }
  4359. }
  4360. }
  4361. virtual void getGroupDN(const char* groupname, StringBuffer& groupdn, const char * groupBaseDN=nullptr)
  4362. {
  4363. if(groupname == NULL)
  4364. {
  4365. DBGLOG("CLdapClient::getGroupDN groupname must be provided");
  4366. return;
  4367. }
  4368. LdapServerType stype = m_ldapconfig->getServerType();
  4369. groupdn.append("cn=").append(groupname).append(",");
  4370. if(stype == ACTIVE_DIRECTORY && stricmp(groupname, "Administrators") == 0)
  4371. {
  4372. groupdn.append("cn=Builtin,").append(m_ldapconfig->getBasedn());
  4373. }
  4374. else if((stype == IPLANET || stype == OPEN_LDAP) && stricmp(groupname, "Directory Administrators") == 0)
  4375. {
  4376. groupdn.append(m_ldapconfig->getBasedn());
  4377. }
  4378. else
  4379. {
  4380. groupdn.append(groupBaseDN == nullptr ? m_ldapconfig->getGroupBasedn() : groupBaseDN);
  4381. }
  4382. }
  4383. virtual void getGroupBaseDN(const char* groupname, StringBuffer& groupbasedn, const char * groupBaseDN=nullptr)
  4384. {
  4385. if(groupname == NULL)
  4386. {
  4387. DBGLOG("CLdapClient::getGroupBaseDN groupname must be provided");
  4388. return;
  4389. }
  4390. LdapServerType stype = m_ldapconfig->getServerType();
  4391. if(stype == ACTIVE_DIRECTORY && stricmp(groupname, "Administrators") == 0)
  4392. {
  4393. groupbasedn.append("cn=Builtin,").append(m_ldapconfig->getBasedn());
  4394. }
  4395. else if((stype == IPLANET || stype == OPEN_LDAP) && stricmp(groupname, "Directory Administrators") == 0)
  4396. {
  4397. groupbasedn.append(m_ldapconfig->getBasedn());
  4398. }
  4399. else
  4400. {
  4401. groupbasedn.append(groupBaseDN==nullptr ? m_ldapconfig->getGroupBasedn() : groupBaseDN);
  4402. }
  4403. }
  4404. virtual void changeUserMemberOf(const char* action, const char* userdn, const char* groupdn)
  4405. {
  4406. char *grp_values[] = {(char*)groupdn, NULL};
  4407. LDAPMod grp_attr = {
  4408. (action != NULL && stricmp(action, "delete") == 0)?LDAP_MOD_DELETE:LDAP_MOD_ADD,
  4409. "memberOf",
  4410. grp_values
  4411. };
  4412. LDAPMod *grp_attrs[2];
  4413. grp_attrs[0] = &grp_attr;
  4414. grp_attrs[1] = NULL;
  4415. Owned<ILdapConnection> lconn = m_connections->getConnection();
  4416. LDAP* ld = lconn.get()->getLd();
  4417. int rc = ldap_modify_ext_s(ld, (char*)userdn, grp_attrs, NULL, NULL);
  4418. if ( rc != LDAP_SUCCESS )
  4419. {
  4420. throw MakeStringException(-1, "error changing group for user %s, ldap_modify_ext_s error: %s", userdn, ldap_err2string( rc ));
  4421. }
  4422. }
  4423. virtual void changeGroupMember(const char* action, const char* groupdn, const char* userdn)
  4424. {
  4425. Owned<ILdapConnection> lconn = m_connections->getConnection();
  4426. LDAP* ld = lconn.get()->getLd();
  4427. const char* memberfieldname;
  4428. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  4429. {
  4430. memberfieldname = "member";
  4431. }
  4432. else
  4433. {
  4434. memberfieldname = "uniquemember";
  4435. }
  4436. char *member_values[] = {(char*)userdn, NULL};
  4437. LDAPMod member_attr = {
  4438. (action != NULL && stricmp(action, "delete") == 0)?LDAP_MOD_DELETE:LDAP_MOD_ADD,
  4439. (char*)memberfieldname,
  4440. member_values
  4441. };
  4442. LDAPMod *member_attrs[2];
  4443. member_attrs[0] = &member_attr;
  4444. member_attrs[1] = NULL;
  4445. int rc = ldap_modify_ext_s(ld, (char*)groupdn, member_attrs, NULL, NULL);
  4446. if ( rc != LDAP_SUCCESS )
  4447. {
  4448. if (action != NULL && stricmp(action, "delete") == 0)
  4449. throw MakeStringException(-1, "Failed in deleting member from group: ldap_modify_ext_s error: %s; userdn: %s; groupdn: %s", ldap_err2string( rc ), userdn, groupdn);
  4450. else
  4451. throw MakeStringException(-1, "Failed in adding member to group, ldap_modify_ext_s error: %s; userdn: %s; groupdn: %s", ldap_err2string( rc ), userdn, groupdn);
  4452. }
  4453. }
  4454. void ConvertCToW(unsigned short* pszDest, const char * pszSrc)
  4455. {
  4456. unsigned i = 0;
  4457. for(i = 0; i < strlen(pszSrc); i++)
  4458. pszDest[i] = (unsigned short) pszSrc[i];
  4459. pszDest[i] = (unsigned short)'\0';
  4460. }
  4461. virtual bool authorizeScope(ISecUser& user, IArrayOf<ISecResource>& resources, const char* basedn)
  4462. {
  4463. IArrayOf<CSecurityDescriptor> sdlist;
  4464. std::set<const char*, ltstr> scopeset;
  4465. ForEachItemIn(x, resources)
  4466. {
  4467. ISecResource& res = resources.item(x);
  4468. const char* resourcename = res.getName();
  4469. if(resourcename == NULL || *resourcename == '\0')
  4470. continue;
  4471. // Add one extra Volume type SecurityDescriptor for each resource for ActiveDirectory.
  4472. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  4473. {
  4474. CSecurityDescriptor* sd = new CSecurityDescriptor(resourcename);
  4475. sd->setObjectClass("Volume");
  4476. sdlist.append(*sd);
  4477. }
  4478. scopeset.insert(resourcename);
  4479. int len = strlen(resourcename);
  4480. const char* curptr = resourcename + len - 1;
  4481. while(curptr > resourcename)
  4482. {
  4483. while(curptr > resourcename && *curptr != ':')
  4484. curptr--;
  4485. bool foundcolon=false;
  4486. while(curptr >resourcename && *curptr == ':')
  4487. {
  4488. curptr--;
  4489. foundcolon = true;
  4490. }
  4491. if(curptr > resourcename || foundcolon)
  4492. {
  4493. int curlen = curptr - resourcename + 1;
  4494. char* curscope = (char*)alloca(curlen + 1);
  4495. strncpy(curscope, resourcename, curlen);
  4496. curscope[curlen] = 0;
  4497. scopeset.insert(curscope);
  4498. }
  4499. }
  4500. }
  4501. if(scopeset.size() == 0)
  4502. return true;
  4503. std::set<const char*, ltstr>::iterator iter;
  4504. for(iter = scopeset.begin(); iter != scopeset.end(); iter++)
  4505. {
  4506. const char* curscope = *iter;
  4507. CSecurityDescriptor* sd = new CSecurityDescriptor(*iter);
  4508. sd->setObjectClass("organizationalUnit");
  4509. sdlist.append(*sd);
  4510. }
  4511. getSecurityDescriptorsScope(sdlist, basedn);
  4512. IArrayOf<CSecurityDescriptor> matched_sdlist;
  4513. ForEachItemIn(y, resources)
  4514. {
  4515. ISecResource& res = resources.item(y);
  4516. const char* rname = res.getName();
  4517. if(rname == NULL || *rname == '\0')
  4518. throw MakeStringException(-1, "resource name can't be empty inside authorizeScope");
  4519. CSecurityDescriptor* matchedsd = NULL;
  4520. ForEachItemIn(z, sdlist)
  4521. {
  4522. CSecurityDescriptor& sd = sdlist.item(z);
  4523. const char* sdname = sd.getName();
  4524. if(sdname == NULL || *sdname == '\0')
  4525. continue;
  4526. if(strncmp(sdname, rname, strlen(sdname)) == 0
  4527. && (matchedsd == NULL
  4528. || ((matchedsd->getDescriptor().length() == 0 && sd.getDescriptor().length() > 0)
  4529. || (sd.getDescriptor().length() > 0 && strlen(sdname) > strlen(matchedsd->getName())))))
  4530. matchedsd = &sd;
  4531. }
  4532. if(matchedsd != NULL)
  4533. matched_sdlist.append(*LINK(matchedsd));
  4534. else
  4535. matched_sdlist.append(*(new CSecurityDescriptor(rname)));
  4536. }
  4537. bool ok = false;
  4538. if(m_pp != NULL)
  4539. ok = m_pp->getPermissions(user, matched_sdlist, resources);
  4540. return ok;
  4541. }
  4542. virtual void getSecurityDescriptors(SecResourceType rtype, IArrayOf<CSecurityDescriptor>& sdlist)
  4543. {
  4544. int len = sdlist.length();
  4545. if(len == 0)
  4546. {
  4547. DBGLOG("CLdapClient::getSecurityDescriptors sdlist cannot be empty");
  4548. return;
  4549. }
  4550. const char* rbasedn = m_ldapconfig->getResourceBasedn(rtype);
  4551. if(rbasedn == NULL || *rbasedn == '\0')
  4552. {
  4553. DBGLOG("corresponding resource basedn is not defined");
  4554. return;
  4555. }
  4556. std::map<std::string, IArrayOf<CSecurityDescriptor>*> sdmap;
  4557. for(int i = 0; i < len; i++)
  4558. {
  4559. CSecurityDescriptor& sd = sdlist.item(i);
  4560. const char* relativeBasedn = sd.getRelativeBasedn();
  4561. StringBuffer basedn;
  4562. if(relativeBasedn != NULL)
  4563. basedn.append(relativeBasedn).append(",");
  4564. basedn.append(rbasedn);
  4565. std::map<std::string, IArrayOf<CSecurityDescriptor>*>::iterator sdit = sdmap.find(basedn.str());
  4566. if(sdit == sdmap.end())
  4567. {
  4568. IArrayOf<CSecurityDescriptor>* newlist = new IArrayOf<CSecurityDescriptor>;
  4569. newlist->append(*LINK(&sd));
  4570. sdmap[basedn.str()] = newlist;
  4571. }
  4572. else
  4573. {
  4574. (*sdit).second->append(*LINK(&sd));
  4575. }
  4576. }
  4577. for(std::map<std::string, IArrayOf<CSecurityDescriptor>*>::iterator cur = sdmap.begin(); cur != sdmap.end(); cur++)
  4578. {
  4579. getSecurityDescriptors(*((*cur).second), (*cur).first.c_str());
  4580. delete (*cur).second;
  4581. }
  4582. }
  4583. virtual void getSecurityDescriptors(IArrayOf<CSecurityDescriptor>& sdlist, const char* basedn)
  4584. {
  4585. char *attribute;
  4586. CLDAPGetValuesLenWrapper valsLen;
  4587. LDAPMessage *message;
  4588. int i;
  4589. const char *id_fieldname;
  4590. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  4591. {
  4592. id_fieldname = "name";
  4593. }
  4594. else
  4595. {
  4596. id_fieldname = "ou";
  4597. }
  4598. const char *des_fieldname = m_ldapconfig->getSdFieldName();
  4599. int len = sdlist.length();
  4600. if(len == 0)
  4601. {
  4602. DBGLOG("CLdapClient::getSecurityDescriptors2 sdlist cannot be empty");
  4603. return;
  4604. }
  4605. StringBuffer filter;
  4606. filter.append("(|");
  4607. for(i = 0; i < len; i++)
  4608. {
  4609. CSecurityDescriptor& sd = sdlist.item(i);
  4610. StringBuffer namebuf;
  4611. namebuf.append(sd.getName());
  4612. namebuf.trim();
  4613. if(namebuf.length() > 0)
  4614. {
  4615. filter.append("(").append(id_fieldname).append("=").append(namebuf.str()).append(")");;
  4616. }
  4617. }
  4618. filter.append(")");
  4619. SDServerCtlWrapper ctlwrapper(m_ldapconfig->isAzureAD());
  4620. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  4621. char* attrs[] = {(char*)id_fieldname, (char*)des_fieldname, NULL};
  4622. Owned<ILdapConnection> lconn = m_connections->getConnection();
  4623. LDAP* ld = lconn.get()->getLd();
  4624. CLDAPMessage searchResult;
  4625. int rc = ldap_search_ext_s(ld, (char*)basedn, LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs, 0, ctlwrapper.ctls, NULL, &timeOut, LDAP_NO_LIMIT, &searchResult.msg ); /* returned results */
  4626. if ( rc != LDAP_SUCCESS )
  4627. {
  4628. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), basedn);
  4629. return;
  4630. }
  4631. // Go through the search results by checking message types
  4632. for(message = LdapFirstEntry(ld, searchResult); message != NULL; message = ldap_next_entry(ld, message))
  4633. {
  4634. StringBuffer resourcename;
  4635. CLDAPGetAttributesWrapper atts(ld, searchResult);
  4636. for ( attribute = atts.getFirst();
  4637. attribute != NULL;
  4638. attribute = atts.getNext())
  4639. {
  4640. if(stricmp(attribute, id_fieldname) == 0)
  4641. {
  4642. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  4643. if (vals.hasValues())
  4644. resourcename.append(vals.queryCharValue(0));
  4645. }
  4646. else if(stricmp(attribute, des_fieldname) == 0)
  4647. {
  4648. valsLen.retrieveBValues(ld, message, attribute);
  4649. }
  4650. }
  4651. for(i = 0; i < len; i++)
  4652. {
  4653. CSecurityDescriptor& sd = sdlist.item(i);
  4654. if(resourcename.length() > 0 && stricmp(resourcename.str(), sd.getName()) == 0)
  4655. {
  4656. if (valsLen.hasValues())
  4657. {
  4658. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  4659. {
  4660. struct berval* val = valsLen.queryBValues()[0];
  4661. if(val != NULL)
  4662. {
  4663. CSecurityDescriptor& sd = sdlist.item(i);
  4664. sd.setDescriptor(val->bv_len, val->bv_val);
  4665. }
  4666. }
  4667. else
  4668. {
  4669. MemoryBuffer allvals;
  4670. int valseq = 0;
  4671. struct berval* val = valsLen.queryBValues()[valseq++];
  4672. while(val != NULL)
  4673. {
  4674. if(val->bv_len > 0)
  4675. {
  4676. allvals.append(val->bv_len, val->bv_val);
  4677. allvals.append('\0'); // my separator between ACIs
  4678. }
  4679. val = valsLen.queryBValues()[valseq++];
  4680. }
  4681. if(allvals.length() > 0)
  4682. {
  4683. CSecurityDescriptor& sd = sdlist.item(i);
  4684. sd.setDescriptor(allvals.length(), (void*)allvals.toByteArray());
  4685. }
  4686. }
  4687. }
  4688. break;
  4689. }
  4690. }
  4691. }
  4692. }
  4693. virtual void getSecurityDescriptorsScope(IArrayOf<CSecurityDescriptor>& sdlist, const char* basedn)
  4694. {
  4695. char *attribute;
  4696. CLDAPGetValuesLenWrapper valsLen;
  4697. LDAPMessage *message;
  4698. int i;
  4699. int len = sdlist.length();
  4700. if(len == 0)
  4701. {
  4702. DBGLOG("CLdapClient::getSecurityDescriptorsScope sdlist cannot be empty");
  4703. return;
  4704. }
  4705. LdapServerType servertype = m_ldapconfig->getServerType();
  4706. char *sd_fieldname = (char*)m_ldapconfig->getSdFieldName();
  4707. StringBuffer filter;
  4708. filter.append("(|");
  4709. for(i = 0; i < len; i++)
  4710. {
  4711. CSecurityDescriptor& sd = sdlist.item(i);
  4712. StringBuffer namebuf;
  4713. namebuf.append(sd.getName());
  4714. namebuf.trim();
  4715. if(namebuf.length() > 0)
  4716. {
  4717. const char* resourcename = namebuf.str();
  4718. int len = namebuf.length();
  4719. const char* curptr = resourcename + len - 1;
  4720. StringBuffer dn, cn;
  4721. bool isleaf = true;
  4722. while(curptr > resourcename)
  4723. {
  4724. const char* lastptr = curptr;
  4725. while(curptr > resourcename && *curptr != ':')
  4726. curptr--;
  4727. int curlen;
  4728. const char* curscope;
  4729. if(*curptr == ':')
  4730. {
  4731. curlen = lastptr - curptr;
  4732. curscope = curptr + 1;
  4733. }
  4734. else
  4735. {
  4736. curlen = lastptr - curptr + 1;
  4737. curscope = curptr;
  4738. }
  4739. if(isleaf && (sd.getObjectClass() != NULL) && (stricmp(sd.getObjectClass(), "Volume") == 0))
  4740. {
  4741. cn.append(curlen, curscope);
  4742. dn.append("cn=").append(curlen, curscope).append(",");
  4743. }
  4744. else
  4745. {
  4746. cn.append(curlen, curscope);
  4747. dn.append("ou=").append(curlen, curscope).append(",");
  4748. }
  4749. isleaf = false;
  4750. if (curptr == resourcename) //handle a single char as the top scope, such as x::abc
  4751. break;
  4752. while(curptr >resourcename && *curptr == ':')
  4753. curptr--;
  4754. if (curptr == resourcename && *curptr != ':') //handle a single char as the top scope, such as x::abc
  4755. {
  4756. dn.append("ou=").append(1, curptr).append(",");
  4757. }
  4758. }
  4759. dn.append(basedn);
  4760. if(servertype == ACTIVE_DIRECTORY)
  4761. {
  4762. filter.append("(distinguishedName=").append(dn.str()).append(")");
  4763. }
  4764. else if(servertype == IPLANET)
  4765. {
  4766. filter.append("(entrydn=").append(dn.str()).append(")");
  4767. }
  4768. else if(servertype == OPEN_LDAP)
  4769. {
  4770. filter.append("(ou=").append(cn.str()).append(")");
  4771. }
  4772. sd.setDn(dn.str());
  4773. }
  4774. }
  4775. filter.append(")");
  4776. SDServerCtlWrapper ctlwrapper(m_ldapconfig->isAzureAD());
  4777. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  4778. char* attrs[] = {sd_fieldname, NULL};
  4779. Owned<ILdapConnection> lconn = m_connections->getConnection();
  4780. LDAP* ld = lconn.get()->getLd();
  4781. CLDAPMessage searchResult;
  4782. int rc = ldap_search_ext_s(ld, (char*)basedn, LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs, 0, ctlwrapper.ctls, NULL, &timeOut, LDAP_NO_LIMIT, &searchResult.msg ); /* returned results */
  4783. if ( rc != LDAP_SUCCESS )
  4784. {
  4785. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), basedn);
  4786. return;
  4787. }
  4788. // Go through the search results by checking message types
  4789. for(message = LdapFirstEntry(ld, searchResult); message != NULL; message = ldap_next_entry(ld, message))
  4790. {
  4791. StringBuffer dn;
  4792. char *p = ldap_get_dn(ld, message);
  4793. dn.append(p);
  4794. ldap_memfree(p);
  4795. CLDAPGetAttributesWrapper atts(ld, searchResult);
  4796. for ( attribute = atts.getFirst();
  4797. attribute != NULL;
  4798. attribute = atts.getNext())
  4799. {
  4800. if(stricmp(attribute, sd_fieldname) == 0)
  4801. {
  4802. valsLen.retrieveBValues(ld, message, attribute);
  4803. }
  4804. }
  4805. for(i = 0; i < len; i++)
  4806. {
  4807. CSecurityDescriptor& sd = sdlist.item(i);
  4808. if(dn.length() > 0 && stricmp(dn.str(), sd.getDn()) == 0)
  4809. {
  4810. if (valsLen.hasValues())
  4811. {
  4812. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  4813. {
  4814. struct berval* val = valsLen.queryBValues()[0];
  4815. if(val != NULL)
  4816. {
  4817. CSecurityDescriptor& sd = sdlist.item(i);
  4818. sd.setDescriptor(val->bv_len, val->bv_val);
  4819. }
  4820. }
  4821. else
  4822. {
  4823. MemoryBuffer allvals;
  4824. int valseq = 0;
  4825. struct berval* val = valsLen.queryBValues()[valseq++];
  4826. while(val != NULL)
  4827. {
  4828. if(val->bv_len > 0)
  4829. {
  4830. allvals.append(val->bv_len, val->bv_val);
  4831. allvals.append('\0'); // my separator between ACIs
  4832. }
  4833. val = valsLen.queryBValues()[valseq++];
  4834. }
  4835. if(allvals.length() > 0)
  4836. {
  4837. CSecurityDescriptor& sd = sdlist.item(i);
  4838. sd.setDescriptor(allvals.length(), (void*)allvals.toByteArray());
  4839. }
  4840. }
  4841. }
  4842. break;
  4843. }
  4844. }
  4845. }
  4846. }
  4847. virtual const bool organizationalUnitExists(const char * ou) const
  4848. {
  4849. Owned<ILdapConnection> lconn = m_connections->getConnection();
  4850. LDAP* sys_ld = lconn.get()->getLd();
  4851. char* attrs[] = {"ou", NULL};
  4852. CLDAPMessage searchResult;
  4853. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  4854. int rc = ldap_search_ext_s(sys_ld,const_cast <char*>(ou),LDAP_SCOPE_ONELEVEL,NULL,attrs,0,NULL,NULL,&timeOut,LDAP_NO_LIMIT,&searchResult.msg);
  4855. return rc == LDAP_SUCCESS;
  4856. }
  4857. virtual void createLdapBasedn(ISecUser* user, const char* basedn, SecPermissionType ptype)
  4858. {
  4859. if(basedn == NULL || basedn[0] == '\0')
  4860. {
  4861. DBGLOG("CLdapClient::createLdapBasedn basedn must be provided");
  4862. return;
  4863. }
  4864. const char* ptr = strstr(basedn, "ou=");
  4865. if(ptr == NULL)
  4866. {
  4867. DBGLOG("CLdapClient::createLdapBasedn OU= missing from basedn");
  4868. return;
  4869. }
  4870. ptr += 3;
  4871. StringBuffer oubuf;
  4872. const char* comma = strchr(ptr, ',');
  4873. if(comma == NULL)
  4874. {
  4875. oubuf.append(ptr);
  4876. ptr = NULL;
  4877. }
  4878. else
  4879. {
  4880. oubuf.append(comma - ptr, ptr);
  4881. ptr = comma + 1;
  4882. }
  4883. if (ptr && strstr(ptr,"ou=") && !organizationalUnitExists(ptr))
  4884. createLdapBasedn(user, ptr, ptype);
  4885. addOrganizationalUnit(user, oubuf.str(), ptr, ptype);
  4886. }
  4887. virtual bool addOrganizationalUnit(ISecUser* user, const char* name, const char* basedn, SecPermissionType ptype)
  4888. {
  4889. if(name == NULL || basedn == NULL)
  4890. {
  4891. DBGLOG("CLdapClient::addOrganizationalUnit OU name must be provided");
  4892. return false;
  4893. }
  4894. if(strchr(name, '/') != NULL || strchr(name, '=') != NULL)
  4895. {
  4896. DBGLOG("CLdapClient::addOrganizationalUnit Invalid characters in OU");
  4897. return false;
  4898. }
  4899. StringBuffer dn;
  4900. dn.append("ou=").append(name).append(",").append(basedn);
  4901. if (organizationalUnitExists(dn.str()))
  4902. return true;
  4903. char *ou_values[] = {(char*)name, NULL };
  4904. LDAPMod ou_attr =
  4905. {
  4906. LDAP_MOD_ADD,
  4907. "ou",
  4908. ou_values
  4909. };
  4910. char *name_values[] = {(char*)name, NULL };
  4911. LDAPMod name_attr =
  4912. {
  4913. LDAP_MOD_ADD,
  4914. "name",
  4915. name_values
  4916. };
  4917. char *oc_values[] = {"OrganizationalUnit", NULL };
  4918. LDAPMod oc_attr =
  4919. {
  4920. LDAP_MOD_ADD,
  4921. "objectClass",
  4922. oc_values
  4923. };
  4924. MemoryBuffer sdbuf;
  4925. Owned<CSecurityDescriptor> default_sd = NULL;
  4926. if(m_pp != NULL)
  4927. default_sd.setown(m_pp->createDefaultSD(user, name, ptype));
  4928. if(default_sd != NULL)
  4929. sdbuf.append(default_sd->getDescriptor());
  4930. LDAPMod *attrs[6];
  4931. int ind = 0;
  4932. attrs[ind++] = &ou_attr;
  4933. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  4934. {
  4935. attrs[ind++] = &name_attr;
  4936. }
  4937. attrs[ind++] = &oc_attr;
  4938. LDAPMod sd_attr;
  4939. struct berval sd_val;
  4940. sd_val.bv_len = sdbuf.length();
  4941. sd_val.bv_val = (char*)sdbuf.toByteArray();
  4942. struct berval* sd_values[] = {&sd_val, NULL};
  4943. sd_attr.mod_op = LDAP_MOD_ADD | LDAP_MOD_BVALUES;
  4944. sd_attr.mod_type = (char*)m_ldapconfig->getSdFieldName();
  4945. sd_attr.mod_vals.modv_bvals = sd_values;
  4946. if(sdbuf.length() > 0)
  4947. attrs[ind++] = &sd_attr;
  4948. attrs[ind] = NULL;
  4949. Owned<ILdapConnection> lconn = m_connections->getConnection();
  4950. LDAP* ld = lconn.get()->getLd();
  4951. int rc = ldap_add_ext_s(ld, (char*)dn.str(), attrs, NULL, NULL);
  4952. if ( rc != LDAP_SUCCESS )
  4953. {
  4954. if(rc == LDAP_ALREADY_EXISTS)
  4955. {
  4956. WARNLOG("CLdapClient::addOrganizationalUnit LDAP object 'ou=%s,%s' already exists", name, basedn);
  4957. return false;
  4958. }
  4959. else
  4960. {
  4961. throw MakeStringException(-1, "ldap_add_ext_s error for ou=%s,%s: %d %s", name, basedn, rc, ldap_err2string( rc ));
  4962. }
  4963. }
  4964. return true;
  4965. }
  4966. virtual void name2dn(SecResourceType rtype, const char* resourcename, const char* basedn, StringBuffer& ldapname)
  4967. {
  4968. StringBuffer namebuf;
  4969. const char* bptr = resourcename;
  4970. const char* sep = strstr(resourcename, "::");
  4971. while(sep != NULL)
  4972. {
  4973. if(sep > bptr)
  4974. {
  4975. StringBuffer onebuf;
  4976. onebuf.append("ou=").append(sep-bptr, bptr).append(",");
  4977. namebuf.insert(0, onebuf.str());
  4978. }
  4979. bptr = sep + 2;
  4980. sep = strstr(bptr, "::");
  4981. }
  4982. if(*bptr != '\0')
  4983. {
  4984. StringBuffer onebuf;
  4985. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY && (rtype == RT_DEFAULT || rtype == RT_MODULE || rtype == RT_SERVICE))
  4986. onebuf.append("cn");
  4987. else
  4988. onebuf.append("ou");
  4989. onebuf.append("=").append(bptr).append(",");
  4990. namebuf.insert(0, onebuf.str());
  4991. }
  4992. namebuf.append(basedn);
  4993. LdapUtils::normalizeDn(namebuf.str(), m_ldapconfig->getBasedn(), ldapname);
  4994. }
  4995. virtual void name2rdn(SecResourceType rtype, const char* resourcename, StringBuffer& ldapname)
  4996. {
  4997. if(resourcename == NULL || *resourcename == '\0')
  4998. {
  4999. DBGLOG("CLdapClient::name2rdn resourcename must be provided");
  5000. return;
  5001. }
  5002. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY && (rtype == RT_DEFAULT || rtype == RT_MODULE || rtype == RT_SERVICE))
  5003. ldapname.append("cn=");
  5004. else
  5005. ldapname.append("ou=");
  5006. const char* prevptr = resourcename;
  5007. const char* nextptr = strstr(resourcename, "::");
  5008. while(nextptr != NULL)
  5009. {
  5010. prevptr = nextptr + 2;
  5011. nextptr = strstr(prevptr, "::");
  5012. }
  5013. if(*prevptr != '\0')
  5014. ldapname.append(prevptr);
  5015. }
  5016. virtual bool addResource(SecResourceType rtype, ISecUser& user, ISecResource* resource, SecPermissionType ptype, const char* basedn)
  5017. {
  5018. Owned<CSecurityDescriptor> template_sd = NULL;
  5019. const char* templatename = m_ldapconfig->getTemplateName();
  5020. if(templatename != NULL && *templatename != '\0')
  5021. {
  5022. IArrayOf<CSecurityDescriptor> sdlist;
  5023. template_sd.setown(new CSecurityDescriptor(templatename));
  5024. sdlist.append(*LINK(template_sd));
  5025. if(basedn && *basedn)
  5026. getSecurityDescriptors(sdlist, basedn);
  5027. else
  5028. getSecurityDescriptors(rtype, sdlist);
  5029. }
  5030. Owned<CSecurityDescriptor> default_sd = NULL;
  5031. if(template_sd != NULL && template_sd->getDescriptor().length() > 0)
  5032. {
  5033. MemoryBuffer template_sd_buf;
  5034. template_sd_buf.append(template_sd->getDescriptor());
  5035. if(m_pp != NULL)
  5036. default_sd.setown(m_pp->createDefaultSD(&user, resource, template_sd_buf));
  5037. }
  5038. else
  5039. {
  5040. if(m_pp != NULL)
  5041. default_sd.setown(m_pp->createDefaultSD(&user, resource, ptype));
  5042. }
  5043. return addResource(rtype, user, resource, ptype, basedn, default_sd.get());
  5044. }
  5045. virtual bool addResource(SecResourceType rtype, ISecUser& user, ISecResource* resource, SecPermissionType ptype, const char* basedn, CSecurityDescriptor* default_sd, bool lessException=true)
  5046. {
  5047. if(resource == NULL)
  5048. {
  5049. DBGLOG("CLdapClient::addResource can't add resource, ISecResource must be specified");
  5050. return true;
  5051. }
  5052. char* resourcename = (char*)resource->getName();
  5053. if(resourcename == NULL)
  5054. {
  5055. DBGLOG("CLdapClient::addResource can't add resource, empty resource name");
  5056. return false;
  5057. }
  5058. const char* rbasedn;
  5059. StringBuffer rbasednbuf;
  5060. if(basedn == NULL)
  5061. rbasedn = m_ldapconfig->getResourceBasedn(rtype);
  5062. else
  5063. {
  5064. LdapUtils::normalizeDn(basedn, m_ldapconfig->getBasedn(), rbasednbuf);
  5065. rbasedn = rbasednbuf.str();
  5066. }
  5067. if(rbasedn == NULL || *rbasedn == '\0')
  5068. {
  5069. DBGLOG("CLdapClient::addResource Can't add resource '%s', corresponding resource basedn is not defined",resourcename);
  5070. return false;
  5071. }
  5072. if(strchr(resourcename, '/') != NULL || strchr(resourcename, '=') != NULL)
  5073. {
  5074. DBGLOG("CLdapClient::addResource Can't add resource '%s', invalid characters specified",resourcename);
  5075. return false;
  5076. }
  5077. if(rtype == RT_FILE_SCOPE || rtype == RT_WORKUNIT_SCOPE)
  5078. {
  5079. StringBuffer extbuf;
  5080. name2dn(rtype, resourcename, rbasedn, extbuf);
  5081. createLdapBasedn(&user, extbuf.str(), ptype);
  5082. return true;
  5083. }
  5084. LdapServerType servertype = m_ldapconfig->getServerType();
  5085. char* description = (char*)((CLdapSecResource*)resource)->getDescription();
  5086. StringBuffer dn;
  5087. char *fieldname, *oc_name;
  5088. if(servertype == ACTIVE_DIRECTORY)
  5089. {
  5090. fieldname = "cn";
  5091. oc_name = "Volume";
  5092. }
  5093. else
  5094. {
  5095. fieldname = "ou";
  5096. oc_name = "OrganizationalUnit";
  5097. }
  5098. dn.append(fieldname).append("=").append(resourcename).append(",");
  5099. dn.append(rbasedn);
  5100. char *cn_values[] = {resourcename, NULL };
  5101. LDAPMod cn_attr =
  5102. {
  5103. LDAP_MOD_ADD,
  5104. fieldname,
  5105. cn_values
  5106. };
  5107. char *oc_values[] = {oc_name, NULL };
  5108. LDAPMod oc_attr =
  5109. {
  5110. LDAP_MOD_ADD,
  5111. "objectClass",
  5112. oc_values
  5113. };
  5114. char* uncname_values[] = {resourcename, NULL};
  5115. LDAPMod uncname_attr =
  5116. {
  5117. LDAP_MOD_ADD,
  5118. "uNCName",
  5119. uncname_values
  5120. };
  5121. StringBuffer descriptionbuf;
  5122. if(description && *description)
  5123. descriptionbuf.append(description);
  5124. else
  5125. descriptionbuf.appendf("Access to %s", resourcename);
  5126. char* description_values[] = {(char*)descriptionbuf.str(), NULL};
  5127. LDAPMod description_attr =
  5128. {
  5129. LDAP_MOD_ADD,
  5130. "description",
  5131. description_values
  5132. };
  5133. Owned<CSecurityDescriptor> template_sd = NULL;
  5134. const char* templatename = m_ldapconfig->getTemplateName();
  5135. if(templatename != NULL && *templatename != '\0')
  5136. {
  5137. IArrayOf<CSecurityDescriptor> sdlist;
  5138. template_sd.setown(new CSecurityDescriptor(templatename));
  5139. sdlist.append(*LINK(template_sd));
  5140. getSecurityDescriptors(rtype, sdlist);
  5141. }
  5142. int numberOfSegs = 0;
  5143. if(default_sd != NULL)
  5144. {
  5145. numberOfSegs = m_pp->sdSegments(default_sd);
  5146. }
  5147. LDAPMod **attrs = (LDAPMod**)(alloca((5+numberOfSegs)*sizeof(LDAPMod*)));
  5148. int ind = 0;
  5149. attrs[ind++] = &cn_attr;
  5150. attrs[ind++] = &oc_attr;
  5151. attrs[ind++] = &description_attr;
  5152. if(servertype == ACTIVE_DIRECTORY)
  5153. {
  5154. attrs[ind++] = &uncname_attr;
  5155. }
  5156. LDAPMod sd_attr;
  5157. if(default_sd != NULL)
  5158. {
  5159. struct berval** sd_values = (struct berval**)alloca(sizeof(struct berval*)*(numberOfSegs+1));
  5160. MemoryBuffer& sdbuf = default_sd->getDescriptor();
  5161. // Active Directory acutally has only one segment.
  5162. if(servertype == ACTIVE_DIRECTORY)
  5163. {
  5164. struct berval* sd_val = (struct berval*)alloca(sizeof(struct berval));
  5165. sd_val->bv_len = sdbuf.length();
  5166. sd_val->bv_val = (char*)sdbuf.toByteArray();
  5167. sd_values[0] = sd_val;
  5168. sd_values[1] = NULL;
  5169. sd_attr.mod_type = "ntSecurityDescriptor";
  5170. }
  5171. else
  5172. {
  5173. const char* bbptr = sdbuf.toByteArray();
  5174. const char* bptr = sdbuf.toByteArray();
  5175. int sdbuflen = sdbuf.length();
  5176. int segind;
  5177. for(segind = 0; segind < numberOfSegs; segind++)
  5178. {
  5179. if(bptr - bbptr >= sdbuflen)
  5180. break;
  5181. while(*bptr == '\0' && (bptr - bbptr) < sdbuflen)
  5182. bptr++;
  5183. const char* eptr = bptr;
  5184. while(*eptr != '\0' && (eptr - bbptr) < sdbuflen)
  5185. eptr++;
  5186. struct berval* sd_val = (struct berval*)alloca(sizeof(struct berval));
  5187. sd_val->bv_len = eptr - bptr;
  5188. sd_val->bv_val = (char*)bptr;
  5189. sd_values[segind] = sd_val;
  5190. bptr = eptr + 1;
  5191. }
  5192. sd_values[segind] = NULL;
  5193. sd_attr.mod_type = (char*)m_ldapconfig->getSdFieldName();
  5194. }
  5195. sd_attr.mod_op = LDAP_MOD_ADD | LDAP_MOD_BVALUES;
  5196. sd_attr.mod_vals.modv_bvals = sd_values;
  5197. attrs[ind++] = &sd_attr;
  5198. }
  5199. attrs[ind] = NULL;
  5200. Owned<ILdapConnection> lconn = m_connections->getConnection();
  5201. LDAP* ld = lconn.get()->getLd();
  5202. int rc = ldap_add_ext_s(ld, (char*)dn.str(), attrs, NULL, NULL);
  5203. if ( rc != LDAP_SUCCESS )
  5204. {
  5205. if(rc == LDAP_ALREADY_EXISTS)
  5206. {
  5207. //WARNLOG("Can't insert %s to Ldap Server, an LDAP object with this name already exists", resourcename);
  5208. if(lessException)
  5209. {
  5210. DBGLOG("CLdapClient::addResource Can't add resource '%s', an LDAP object with this name already exists", resourcename);
  5211. return false;
  5212. }
  5213. else
  5214. throw MakeStringException(-1, "Can't insert %s, an LDAP object with this name already exists", resourcename);
  5215. }
  5216. else
  5217. {
  5218. throw MakeStringException(-1, "ldap_add_ext_s error for %s: %d %s", resourcename, rc, ldap_err2string( rc ));
  5219. }
  5220. }
  5221. return true;
  5222. }
  5223. virtual void enableUser(ISecUser* user, const char* dn, LDAP* ld)
  5224. {
  5225. const char* username = user->getName();
  5226. StringBuffer filter;
  5227. filter.append("sAMAccountName=").append(username);
  5228. char *attribute;
  5229. LDAPMessage *message;
  5230. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  5231. char *attrs[] = {"userAccountControl", NULL};
  5232. CLDAPMessage searchResult;
  5233. int rc = ldap_search_ext_s(ld, (char*)m_ldapconfig->getUserBasedn(), LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs, 0, NULL, NULL, &timeOut, LDAP_NO_LIMIT, &searchResult.msg );
  5234. if ( rc != LDAP_SUCCESS )
  5235. {
  5236. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), m_ldapconfig->getUserBasedn());
  5237. throw MakeStringException(-1, "ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), m_ldapconfig->getUserBasedn());
  5238. }
  5239. StringBuffer act_ctrl;
  5240. message = LdapFirstEntry( ld, searchResult);
  5241. if(message != NULL)
  5242. {
  5243. CLDAPGetAttributesWrapper atts(ld, searchResult);
  5244. for ( attribute = atts.getFirst();
  5245. attribute != NULL;
  5246. attribute = atts.getNext())
  5247. {
  5248. if(0 == stricmp(attribute, "userAccountControl"))
  5249. {
  5250. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  5251. if (vals.hasValues())
  5252. {
  5253. act_ctrl.append(vals.queryCharValue(0));
  5254. break;
  5255. }
  5256. }
  5257. }
  5258. }
  5259. if(act_ctrl.length() == 0)
  5260. {
  5261. DBGLOG("enableUser: userAccountControl doesn't exist for user %s",username);
  5262. throw MakeStringException(-1, "enableUser: userAccountControl doesn't exist for user %s",username);
  5263. }
  5264. unsigned act_ctrl_val = atoi(act_ctrl.str());
  5265. // UF_ACCOUNTDISABLE 0x0002
  5266. act_ctrl_val &= 0xFFFFFFFD;
  5267. #ifdef _DONT_EXPIRE_PASSWORD
  5268. // UF_DONT_EXPIRE_PASSWD 0x10000
  5269. if (m_domainPwdsNeverExpire)
  5270. act_ctrl_val |= 0x10000;
  5271. #endif
  5272. StringBuffer new_act_ctrl;
  5273. new_act_ctrl.append(act_ctrl_val);
  5274. char *ctrl_values[] = {(char*)new_act_ctrl.str(), NULL};
  5275. LDAPMod ctrl_attr = {
  5276. LDAP_MOD_REPLACE,
  5277. "userAccountControl",
  5278. ctrl_values
  5279. };
  5280. LDAPMod *cattrs[2];
  5281. cattrs[0] = &ctrl_attr;
  5282. cattrs[1] = NULL;
  5283. rc = ldap_modify_ext_s(ld, (char*)dn, cattrs, NULL, NULL);
  5284. if ( rc != LDAP_SUCCESS )
  5285. {
  5286. throw MakeStringException(-1, "error enableUser %s, ldap_modify_ext_s error: %s", username, ldap_err2string( rc ));
  5287. }
  5288. // set the password.
  5289. Owned<ISecUser> tmpuser = new CLdapSecUser(user->getName(), "");
  5290. if (!updateUserPassword(*tmpuser, user->credentials().getPassword(), nullptr))
  5291. {
  5292. DBGLOG("Error updating password for %s",username);
  5293. throw MakeStringException(-1, "Error updating password for %s",username);
  5294. }
  5295. //Now that the password is set, we can ensure passwords are always required
  5296. act_ctrl_val &= ~(0x20);// UF_PASSWD_NOTREQD 0x0020
  5297. new_act_ctrl.clear().append(act_ctrl_val);
  5298. LDAPMod attr = {
  5299. LDAP_MOD_REPLACE,
  5300. "userAccountControl",
  5301. ctrl_values
  5302. };
  5303. cattrs[0] = &attr;
  5304. cattrs[1] = NULL;
  5305. rc = ldap_modify_ext_s(ld, (char*)dn, cattrs, NULL, NULL);
  5306. if ( rc != LDAP_SUCCESS )
  5307. {
  5308. throw MakeStringException(-1, "error enableUser2 %s, ldap_modify_ext_s error2: %s", username, ldap_err2string( rc ));
  5309. }
  5310. }
  5311. virtual bool addUser(ISecUser& user)
  5312. {
  5313. const char* username = user.getName();
  5314. if(username == NULL || *username == '\0')
  5315. {
  5316. DBGLOG("Can't add user, username not set");
  5317. throw MakeStringException(-1, "Can't add user, username not set");
  5318. }
  5319. const char* userPassword = user.credentials().getPassword();
  5320. if(isEmptyString(userPassword))
  5321. {
  5322. throw MakeStringException(-1, "Can't add user, password not set");
  5323. }
  5324. const char* fname = user.getFirstName();
  5325. const char* lname = user.getLastName();
  5326. if((lname == NULL || *lname == '\0') && (fname == NULL || *fname == '\0' || m_ldapconfig->getServerType() == IPLANET))
  5327. lname = username;
  5328. const char* fullname = user.getFullName();
  5329. StringBuffer fullname_buf;
  5330. if(fullname == NULL || *fullname == '\0')
  5331. {
  5332. if(fname != NULL && *fname != '\0')
  5333. {
  5334. fullname_buf.append(fname);
  5335. if(lname != NULL && *lname != '\0')
  5336. fullname_buf.append(" ");
  5337. }
  5338. if(lname != NULL && *lname != '\0')
  5339. fullname_buf.append(lname);
  5340. if(fullname_buf.length() == 0)
  5341. {
  5342. fullname_buf.append(username);
  5343. }
  5344. fullname = fullname_buf.str();
  5345. }
  5346. const char* employeeID = user.getEmployeeID();
  5347. const char* employeeNumber = user.getEmployeeNumber();
  5348. StringBuffer dn;
  5349. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  5350. {
  5351. dn.append("cn=").append(fullname).append(",");
  5352. }
  5353. else
  5354. {
  5355. dn.append("uid=").append(user.getName()).append(",");
  5356. }
  5357. dn.append(m_ldapconfig->getUserBasedn());
  5358. char* oc_name;
  5359. char* act_fieldname;
  5360. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  5361. {
  5362. oc_name = "User";
  5363. act_fieldname = "sAMAccountName";
  5364. }
  5365. else
  5366. {
  5367. oc_name = "inetorgperson";
  5368. act_fieldname = "uid";
  5369. }
  5370. char *cn_values[] = {(char*)fullname, NULL };
  5371. LDAPMod cn_attr =
  5372. {
  5373. LDAP_MOD_ADD,
  5374. "cn",
  5375. cn_values
  5376. };
  5377. char *oc_values[] = {oc_name, NULL};
  5378. LDAPMod oc_attr =
  5379. {
  5380. LDAP_MOD_ADD,
  5381. "objectClass",
  5382. oc_values
  5383. };
  5384. char *gn_values[] = { (char*)fname, NULL };
  5385. LDAPMod gn_attr = {
  5386. LDAP_MOD_ADD,
  5387. "givenName",
  5388. gn_values
  5389. };
  5390. char *sn_values[] = { (char*)lname, NULL };
  5391. LDAPMod sn_attr = {
  5392. LDAP_MOD_ADD,
  5393. "sn",
  5394. sn_values
  5395. };
  5396. char* actname_values[] = {(char*)username, NULL};
  5397. LDAPMod actname_attr =
  5398. {
  5399. LDAP_MOD_ADD,
  5400. act_fieldname,
  5401. actname_values
  5402. };
  5403. char* passwd_values[] = {(char*)userPassword, nullptr};//password is set later (in enableUser) if ACTIVE_DIRECTORY
  5404. LDAPMod passwd_attr =
  5405. {
  5406. LDAP_MOD_ADD,
  5407. "userpassword",
  5408. passwd_values
  5409. };
  5410. char *dispname_values[] = {(char*)fullname, NULL };
  5411. LDAPMod dispname_attr =
  5412. {
  5413. LDAP_MOD_ADD,
  5414. "displayName",
  5415. dispname_values
  5416. };
  5417. char* username_values[] = {(char*)username, NULL};
  5418. LDAPMod username_attr =
  5419. {
  5420. LDAP_MOD_ADD,
  5421. "userPrincipalName",
  5422. username_values
  5423. };
  5424. char* employeeID_values[] = {(char*)employeeID, NULL};
  5425. LDAPMod employeeID_attr =
  5426. {
  5427. LDAP_MOD_ADD,
  5428. "employeeId",
  5429. employeeID_values
  5430. };
  5431. char* employeeNumber_values[] = {(char*)employeeNumber, NULL};
  5432. LDAPMod employeeNumber_attr =
  5433. {
  5434. LDAP_MOD_ADD,
  5435. "employeeNumber",
  5436. employeeNumber_values
  5437. };
  5438. LDAPMod *attrs[10];
  5439. int ind = 0;
  5440. attrs[ind++] = &cn_attr;
  5441. attrs[ind++] = &oc_attr;
  5442. if(fname != NULL && *fname != '\0')
  5443. attrs[ind++] = &gn_attr;
  5444. if(lname != NULL && *lname != '\0')
  5445. attrs[ind++] = &sn_attr;
  5446. attrs[ind++] = &actname_attr;
  5447. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  5448. {
  5449. attrs[ind++] = &username_attr;
  5450. attrs[ind++] = &dispname_attr;
  5451. if (employeeID && *employeeID)
  5452. attrs[ind++] = &employeeID_attr;
  5453. if (employeeNumber && *employeeNumber)
  5454. attrs[ind++] = &employeeNumber_attr;
  5455. }
  5456. else
  5457. {
  5458. attrs[ind++] = &passwd_attr;
  5459. }
  5460. attrs[ind] = NULL;
  5461. Owned<ILdapConnection> lconn = m_connections->getConnection();
  5462. LDAP* ld = lconn.get()->getLd();
  5463. int rc = ldap_add_ext_s(ld, (char*)dn.str(), attrs, NULL, NULL);
  5464. if ( rc != LDAP_SUCCESS )
  5465. {
  5466. if(rc == LDAP_ALREADY_EXISTS)
  5467. {
  5468. DBGLOG("Can't add user %s, an LDAP object with this name already exists", username);
  5469. throw MakeStringException(-1, "Can't add user %s, an LDAP object with this name already exists", username);
  5470. }
  5471. else
  5472. {
  5473. DBGLOG("Error addUser %s, ldap_add_ext_s error: %s", username, ldap_err2string( rc ));
  5474. throw MakeStringException(-1, "Error addUser %s, ldap_add_ext_s error: %s", username, ldap_err2string( rc ));
  5475. }
  5476. }
  5477. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  5478. {
  5479. try
  5480. {
  5481. enableUser(&user, dn.str(), ld);
  5482. }
  5483. catch(...)
  5484. {
  5485. deleteUser(&user);
  5486. throw;
  5487. }
  5488. }
  5489. //Add tempfile scope for this user (spill, paused and checkpoint
  5490. //will be created under this user specific scope)
  5491. StringBuffer resName(queryDfsXmlBranchName(DXB_Internal));
  5492. resName.append("::").append(username);
  5493. Owned<ISecResource> resource = new CLdapSecResource(resName.str());
  5494. if (!addResource(RT_FILE_SCOPE, user, resource, PT_ADMINISTRATORS_AND_USER, m_ldapconfig->getResourceBasedn(RT_FILE_SCOPE)))
  5495. {
  5496. throw MakeStringException(-1, "Error adding temp file scope %s",resName.str());
  5497. }
  5498. return true;
  5499. }
  5500. bool createUserScope(ISecUser& user)
  5501. {
  5502. //Add tempfile scope for given user (spill, paused and checkpoint
  5503. //files will be created under this user specific scope)
  5504. StringBuffer resName(queryDfsXmlBranchName(DXB_Internal));
  5505. resName.append("::").append(user.getName());
  5506. Owned<ISecResource> resource = new CLdapSecResource(resName.str());
  5507. return addResource(RT_FILE_SCOPE, user, resource, PT_ADMINISTRATORS_AND_USER, m_ldapconfig->getResourceBasedn(RT_FILE_SCOPE));
  5508. }
  5509. virtual aindex_t getManagedScopeTree(LDAP* ld, SecResourceType rtype, const char * basedn, IArrayOf<ISecResource>& scopes)
  5510. {
  5511. Owned<ILdapConnection> lconn;
  5512. if (nullptr == ld)
  5513. {
  5514. lconn.setown(m_connections->getConnection());
  5515. ld = lconn.get()->getLd();
  5516. }
  5517. //Get array of all file scopes listed in files baseDN
  5518. StringBuffer basednbuf;
  5519. LdapUtils::normalizeDn(basedn ? basedn : m_ldapconfig->getResourceBasedn(rtype), m_ldapconfig->getBasedn(), basednbuf);
  5520. basednbuf.toLowerCase();//Will look something like "ou=files,ou=dataland_ecl,dc=internal,dc=sds". Lowercase ensures proper strstr with StringArray elements below
  5521. //Extract OU path from basedn ("ou=files,ou=dataland_ecl")
  5522. StringBuffer baseOU(basednbuf);
  5523. {
  5524. const char * pDC = strstr(baseOU.str(), ",dc=");
  5525. if (pDC)
  5526. baseOU.setLength(pDC - baseOU.str());//strip out trailing "dc=" portion
  5527. }
  5528. char *attrs[2];
  5529. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  5530. attrs[0] = "canonicalName";
  5531. else
  5532. attrs[0] = "entrydn";//389DirectoryServer
  5533. attrs[1] = nullptr;
  5534. //Call LDAP to get the complete OU tree underneath basdnbuf
  5535. CPagedLDAPSearch pagedSrch(ld, m_ldapconfig->getLdapTimeout(), (char*)basednbuf.str(), LDAP_SCOPE_SUBTREE, "objectClass=*", attrs);
  5536. StringArray arrScopes;
  5537. for (LDAPMessage *message = pagedSrch.getFirstEntry(); message; message = pagedSrch.getNextEntry())
  5538. {
  5539. CLDAPGetAttributesWrapper atts(ld, message);
  5540. for ( char *attribute = atts.getFirst();
  5541. attribute != NULL;
  5542. attribute = atts.getNext())
  5543. {
  5544. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  5545. if (vals.hasValues())
  5546. {
  5547. const char* val = vals.queryCharValue(0);
  5548. if(val)//this check probably isn't necessary since hasValues(), but could prevent a core
  5549. {
  5550. StringArray OUarray;//array to contain OU elements, most nested first (ie roxieuser, hpccinternal)
  5551. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  5552. {
  5553. //Build filescope from everything below the basedn
  5554. OUarray.appendList(val,"/",true);//create StringArray of OU elements. LDAP returns them in the form "internal.sds/files/dataland_ecl/hpccinternal/roxieuser
  5555. //Remove all domain and basedn elements
  5556. OUarray.remove(0, false);//remove domain element
  5557. while (OUarray.ordinality())
  5558. {
  5559. VStringBuffer theOU("ou=%s,", OUarray.item(0));
  5560. theOU.toLowerCase();//Lowercase to ensure proper strstr within basednbuf
  5561. if (nullptr != strstr(basednbuf.str(), theOU.str()))//search baseDN for OU substring
  5562. OUarray.remove(0, false);//remove baseDn element
  5563. else
  5564. break;
  5565. }
  5566. }
  5567. else
  5568. {
  5569. //389DirectoryServer, attribute returned in the form "ou=roxieuser,ou=hpccinternal,ou=files,ou=dataland_ecl,dc=risk,dc=regn,dc=net"
  5570. StringBuffer ouStr(val);
  5571. ouStr.toLowerCase();
  5572. //strip out trailing "dc=" portion
  5573. const char * pDC = strstr(ouStr.str(), ",dc=");
  5574. if (pDC)
  5575. ouStr.setLength(pDC - ouStr.str());
  5576. ouStr.replaceString(baseOU, nullptr);//strip out baseDN (ou=files,ou=dataland_ecl)
  5577. StringArray tmpOUarray;
  5578. if (!ouStr.isEmpty())
  5579. {
  5580. ouStr.replaceString("ou=", nullptr);//strip out all "ou=" strings
  5581. tmpOUarray.appendList(ouStr, ",");//create array of OU entries
  5582. //Populate OUarray in opposite order
  5583. for (int curr = tmpOUarray.ordinality() - 1; curr >= 0; curr--)
  5584. OUarray.append(tmpOUarray.item(curr));
  5585. }
  5586. }
  5587. //build OU string with remaining elements in the form "hpccinternal::roxieuser"
  5588. StringBuffer sb;
  5589. for (int curr = 0; curr < OUarray.ordinality(); curr++)
  5590. {
  5591. sb.appendf("%s%s", sb.isEmpty() ? "" : "::", OUarray.item(curr));
  5592. }
  5593. if (!sb.isEmpty())
  5594. {
  5595. arrScopes.append(sb);
  5596. }
  5597. }
  5598. }
  5599. }
  5600. }
  5601. //Build sorted IArrayOf<ISecResource> from arrScopes
  5602. if (arrScopes.length())
  5603. {
  5604. arrScopes.sortAscii(false);
  5605. ForEachItemIn(i, arrScopes)
  5606. {
  5607. const char * scope= arrScopes.item(i);
  5608. CLdapSecResource* resource = new CLdapSecResource(scope);
  5609. scopes.append(*resource);
  5610. }
  5611. }
  5612. DBGLOG("getManagedScopeTree() found %d scopes under '%s'", scopes.length(), basednbuf.str());
  5613. return scopes.length();
  5614. }
  5615. virtual SecAccessFlags queryDefaultPermission(ISecUser& user)
  5616. {
  5617. const char* basedn = m_ldapconfig->getResourceBasedn(RT_FILE_SCOPE);
  5618. if(basedn == NULL || *basedn == '\0')
  5619. {
  5620. DBGLOG("corresponding basedn is not defined");
  5621. return SecAccess_Unavailable;
  5622. }
  5623. const char* basebasedn = strchr(basedn, ',') + 1;
  5624. StringBuffer baseresource;
  5625. baseresource.append(basebasedn-basedn-4, basedn+3);
  5626. IArrayOf<ISecResource> base_resources;
  5627. base_resources.append(*new CLdapSecResource(baseresource.str()));
  5628. bool baseok = authorizeScope(user, base_resources, basebasedn);
  5629. if(baseok)
  5630. return base_resources.item(0).getAccessFlags();
  5631. else
  5632. return UNK_PERM_VALUE;
  5633. }
  5634. bool isReservedGroupName(const char * groupName)
  5635. {
  5636. if (stricmp(groupName, "Administrators") == 0 ||
  5637. stricmp(groupName, "Authenticated Users") == 0 ||
  5638. stricmp(groupName, "Directory Administrators") == 0)
  5639. {
  5640. return true;
  5641. }
  5642. return false;
  5643. }
  5644. //Data View related interfaces
  5645. void createView(const char * viewName, const char * viewDescription)
  5646. {
  5647. if(viewName == nullptr || *viewName == '\0')
  5648. throw MakeStringException(-1, "Can't add view, viewname is empty");
  5649. if (isReservedGroupName(viewName))
  5650. {
  5651. throw MakeStringException(-1, "Can't add view, '%s' is a reserved name", viewName);
  5652. }
  5653. addGroup(viewName, nullptr, nullptr, m_ldapconfig->getViewBasedn());//TODO Save description
  5654. }
  5655. void deleteView(const char * viewName)
  5656. {
  5657. if(viewName == nullptr || *viewName == '\0')
  5658. throw MakeStringException(-1, "Can't delete view, viewname is empty");
  5659. deleteGroup(viewName, (const char *)m_ldapconfig->getViewBasedn());
  5660. }
  5661. void queryAllViews(StringArray & viewNames, StringArray & viewDescriptions, StringArray & viewManagedBy)
  5662. {
  5663. StringArray names;
  5664. StringArray managedBy;
  5665. StringArray desc;
  5666. getAllGroups(names, managedBy, desc, (const char *)m_ldapconfig->getViewBasedn());
  5667. unsigned len = names.ordinality();
  5668. for(unsigned idx = 0; idx < len; idx++)
  5669. {
  5670. const char * pName = names.item(idx);
  5671. if (!isReservedGroupName(pName))
  5672. {
  5673. viewNames.append(pName);
  5674. viewDescriptions.append(desc.item(idx));
  5675. viewManagedBy.append(managedBy.item(idx));
  5676. }
  5677. }
  5678. }
  5679. bool userInView(const char * user, const char* viewName)
  5680. {
  5681. if(user == nullptr || *user == '\0')
  5682. throw MakeStringException(-1, "Can't check user in view, user name is empty");
  5683. if(viewName == nullptr || *viewName == '\0')
  5684. throw MakeStringException(-1, "Can't check user in view, viewName is empty");
  5685. try
  5686. {
  5687. StringBuffer userDN;
  5688. getUserDN(user, userDN);
  5689. VStringBuffer viewDN("CN=%s,%s",viewName, m_ldapconfig->getViewBasedn());
  5690. return userInGroup(userDN.str(), viewDN.str());
  5691. }
  5692. catch (IException* e)
  5693. {
  5694. #ifdef _DEBUG
  5695. StringBuffer emsg;
  5696. e->errorMessage(emsg);
  5697. DBGLOG("userInView(%s,%s) - %s", user, viewName, emsg.str());
  5698. #endif
  5699. e->Release();
  5700. return false;
  5701. }
  5702. }
  5703. void updateViewContents(const char * viewName, const char * content)
  5704. {
  5705. if(viewName == nullptr || *viewName == '\0')
  5706. throw MakeStringException(-1, "Can't updateViewContents, viewName is empty");
  5707. //Update LDAP description
  5708. char *desc_values[] = { (content && *content != '\0') ? (char*)content : (char*)"|", NULL };
  5709. LDAPMod desc_attr = {
  5710. LDAP_MOD_REPLACE,
  5711. "description",
  5712. desc_values
  5713. };
  5714. LDAPMod *attrs[2];
  5715. attrs[0] = &desc_attr;
  5716. attrs[1] = nullptr;
  5717. TIMEVAL timeOut = { m_ldapconfig->getLdapTimeout(), 0 };
  5718. Owned<ILdapConnection> lconn = m_connections->getConnection();
  5719. LDAP* ld = lconn.get()->getLd();
  5720. StringBuffer dn;
  5721. dn.appendf("CN=%s,%s", viewName, (char*) m_ldapconfig->getViewBasedn());
  5722. unsigned rc = ldap_modify_ext_s(ld, (char*)dn.str(), attrs, nullptr, nullptr);
  5723. if (rc != LDAP_SUCCESS )
  5724. throw MakeStringException(-1, "Error updating view %s - %s", viewName, ldap_err2string( rc ));
  5725. }
  5726. void addViewColumns(const char * viewName, StringArray & files, StringArray & columns)
  5727. {
  5728. if(viewName == nullptr || *viewName == '\0')
  5729. throw MakeStringException(-1, "Can't addViewColumns, viewName is empty");
  5730. StringArray currFiles;
  5731. StringArray currCols;
  5732. queryViewColumns(viewName, currFiles, currCols);
  5733. unsigned vCount = currFiles.ordinality();
  5734. assertex(vCount == currCols.ordinality());
  5735. unsigned len = files.ordinality();
  5736. assertex(len == columns.ordinality());
  5737. bool changed = false;
  5738. for(unsigned idx = 0; idx < len; idx++)
  5739. {
  5740. bool isDup = false;
  5741. for (unsigned vIdx = 0; vIdx < vCount; vIdx++)//look for dups
  5742. {
  5743. if (0 == stricmp(files.item(idx), currFiles.item(vIdx)) &&
  5744. 0 == stricmp(columns.item(idx), currCols.item(vIdx)))
  5745. {
  5746. isDup = true;//skip duplicate entry
  5747. break;
  5748. }
  5749. }
  5750. if (!isDup)
  5751. {
  5752. currFiles.append(files.item(idx));
  5753. currCols.append(columns.item(idx));
  5754. changed = true;
  5755. }
  5756. }
  5757. if (!changed)
  5758. {
  5759. throw MakeStringException(-1, "Specified columns already exist in view");
  5760. }
  5761. ///build description buffer containing one or more ||lfn|col
  5762. StringBuffer description;
  5763. len = currFiles.ordinality();
  5764. for(unsigned idx = 0; idx < len; idx++)
  5765. {
  5766. description.appendf("||%s|%s",currFiles.item(idx), currCols.item(idx));//use illegal LFN character as separators
  5767. }
  5768. updateViewContents(viewName, description.str());
  5769. }
  5770. void removeViewColumns(const char * viewName, StringArray & files, StringArray & columns)
  5771. {
  5772. if(viewName == nullptr || *viewName == '\0')
  5773. throw MakeStringException(-1, "Can't removeViewColumns, viewName is empty");
  5774. StringArray currFiles;
  5775. StringArray currCols;
  5776. queryViewColumns(viewName, currFiles, currCols);
  5777. assertex(currFiles.ordinality() == currCols.ordinality());
  5778. unsigned len = files.ordinality();
  5779. assertex(len == columns.ordinality());
  5780. bool changed = false;
  5781. for(unsigned idx = 0; idx < len; idx++)//for all pairs to be removed
  5782. {
  5783. unsigned len2 = currFiles.ordinality();
  5784. for(unsigned idx2 = 0; idx2 < len2; idx2++)
  5785. {
  5786. if (0 == stricmp(files.item(idx), currFiles.item(idx2)) &&
  5787. 0 == stricmp(columns.item(idx), currCols.item(idx2)))
  5788. {
  5789. currFiles.remove(idx2);
  5790. currCols.remove(idx2);
  5791. changed = true;
  5792. break;
  5793. }
  5794. }
  5795. }
  5796. if (!changed)
  5797. {
  5798. throw MakeStringException(-1, "Specified columns do not exist in view");
  5799. }
  5800. ///build description buffer containing one or more ||lfn|col
  5801. StringBuffer description;
  5802. len = currFiles.ordinality();
  5803. for(unsigned idx = 0; idx < len; idx++)
  5804. {
  5805. description.appendf("||%s|%s",currFiles.item(idx), currCols.item(idx));//use illegal LFN character as separators
  5806. }
  5807. updateViewContents(viewName, description.str());
  5808. }
  5809. void queryViewColumns(const char * viewName, StringArray & files, StringArray & columns)
  5810. {
  5811. if(viewName == nullptr || *viewName == '\0')
  5812. throw MakeStringException(-1, "Can't queryViewColumns, viewName is empty");
  5813. StringBuffer filter;
  5814. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  5815. filter.append("objectClass=group");
  5816. else
  5817. filter.append("objectClass=groupofuniquenames");
  5818. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  5819. Owned<ILdapConnection> lconn = m_connections->getConnection();
  5820. LDAP* ld = lconn.get()->getLd();
  5821. char *attrs[] = {"description", NULL};
  5822. StringBuffer dn;
  5823. dn.appendf("CN=%s,%s", viewName, (char*)m_ldapconfig->getViewBasedn() );
  5824. CPagedLDAPSearch pagedSrch(ld, m_ldapconfig->getLdapTimeout(), (char*)dn.str(), LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs);
  5825. int idx = 0;
  5826. LDAPMessage *message = pagedSrch.getFirstEntry();
  5827. if (message)
  5828. {
  5829. CLDAPGetAttributesWrapper atts(ld, message);
  5830. char * attribute = atts.getFirst();
  5831. if (attribute)
  5832. {
  5833. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  5834. if(vals.hasValues() && stricmp(attribute, "description") == 0)
  5835. {
  5836. StringBuffer sb(vals.queryCharValue(0));
  5837. if (!sb.isEmpty())
  5838. {
  5839. StringBuffer sbFile;
  5840. StringBuffer sbCol;
  5841. unsigned finger = 0;
  5842. unsigned len = sb.length();
  5843. while (finger < len)
  5844. {
  5845. while (finger < len && sb.charAt(finger) == '|')
  5846. finger++;//skip to lfn
  5847. sbFile.clear();
  5848. while (finger < len && sb.charAt(finger) != '|')
  5849. sbFile.append(sb.charAt(finger++));
  5850. while (finger < len && sb.charAt(finger) == '|')
  5851. finger++;//skip to column name
  5852. sbCol.clear();
  5853. while (finger < len && sb.charAt(finger) != '|')
  5854. sbCol.append(sb.charAt(finger++));
  5855. if (!sbFile.isEmpty() && !sbCol.isEmpty())
  5856. {
  5857. files.append(sbFile.str());
  5858. columns.append(sbCol.str());
  5859. }
  5860. }
  5861. }
  5862. }
  5863. }
  5864. }
  5865. }
  5866. void addViewMembers(const char * viewName, StringArray & viewUsers, StringArray & viewGroups)
  5867. {
  5868. if(viewName == nullptr || *viewName == '\0')
  5869. throw MakeStringException(-1, "Can't addViewMembers, viewName is empty");
  5870. unsigned len = viewUsers.ordinality();
  5871. for (unsigned idx = 0; idx < len; idx++)
  5872. {
  5873. changeUserGroup("add", viewUsers.item(idx), viewName, m_ldapconfig->getViewBasedn());
  5874. }
  5875. //TODO handle viewGroups
  5876. }
  5877. void removeViewMembers(const char * viewName, StringArray & viewUsers, StringArray & viewGroups)
  5878. {
  5879. if(viewName == nullptr || *viewName == '\0')
  5880. throw MakeStringException(-1, "Can't removeViewMembers, viewName is empty");
  5881. unsigned len = viewUsers.ordinality();
  5882. for (unsigned idx = 0; idx < len; idx++)
  5883. {
  5884. changeUserGroup("delete", viewUsers.item(idx), viewName, m_ldapconfig->getViewBasedn());
  5885. }
  5886. //TODO handle viewGroups
  5887. }
  5888. void queryViewMembers(const char * viewName, StringArray & viewUsers, StringArray & viewGroups)
  5889. {
  5890. if(viewName == nullptr || *viewName == '\0')
  5891. throw MakeStringException(-1, "Can't queryViewMembers, viewName is empty");
  5892. getGroupMembers(viewName, viewUsers, m_ldapconfig->getViewBasedn());
  5893. //TODO get viewGroups
  5894. }
  5895. };
  5896. #ifdef _WIN32
  5897. bool verifyServerCert(LDAP* ld, PCCERT_CONTEXT pServerCert)
  5898. {
  5899. return true;
  5900. }
  5901. #endif
  5902. ILdapClient* createLdapClient(IPropertyTree* cfg)
  5903. {
  5904. return new CLdapClient(cfg);
  5905. }