ldapconnection.cpp 240 KB

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