ldapconnection.cpp 241 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696
  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 if (strstr(ldap_errstring, "data 533"))
  1579. {
  1580. DBGLOG("LDAP: User %s Account Disabled", username);
  1581. user.setAuthenticateStatus(AS_ACCOUNT_DISABLED);
  1582. }
  1583. else if (strstr(ldap_errstring, "data 701"))
  1584. {
  1585. DBGLOG("LDAP: User %s Account Expired", username);
  1586. user.setAuthenticateStatus(AS_ACCOUNT_EXPIRED);
  1587. }
  1588. else if (strstr(ldap_errstring, "data 775"))
  1589. {
  1590. DBGLOG("LDAP: User %s Account Locked Out", username);
  1591. user.setAuthenticateStatus(AS_ACCOUNT_LOCKED);
  1592. }
  1593. else
  1594. {
  1595. DBGLOG("LDAP: Authentication(1) (%c) for user %s failed - %s", isWorkunitDAToken(password) ? 't' :'f', username, ldap_err2string(rc));
  1596. user.setAuthenticateStatus(AS_INVALID_CREDENTIALS);
  1597. }
  1598. }
  1599. else
  1600. {
  1601. //This path is typical if running ESP on Windows. We have no way
  1602. //to determine if password entered is valid but expired
  1603. if (user.getPasswordDaysRemaining() == scPasswordExpired)
  1604. {
  1605. DBGLOG("LDAP: Password Expired(2) for user %s", username);
  1606. user.setAuthenticateStatus(AS_PASSWORD_EXPIRED);
  1607. }
  1608. else
  1609. {
  1610. DBGLOG("LDAP: Authentication(2) for user %s failed - %s", username, ldap_err2string(rc));
  1611. user.setAuthenticateStatus(AS_INVALID_CREDENTIALS);
  1612. }
  1613. }
  1614. return false;
  1615. }
  1616. user.setAuthenticateStatus(AS_AUTHENTICATED);
  1617. }
  1618. //Always retrieve user info(SID, UID, fullname, etc) for Active Directory, when the user first logs in.
  1619. if((m_ldapconfig->getServerType() == ACTIVE_DIRECTORY) && (m_pp != NULL))
  1620. m_pp->retrieveUserInfo(user);
  1621. return true;
  1622. };
  1623. virtual bool authorize(SecResourceType rtype, ISecUser& user, IArrayOf<ISecResource>& resources, const char * resName = nullptr)
  1624. {
  1625. bool ok = false;
  1626. const char* basedn = m_ldapconfig->getResourceBasedn(rtype);
  1627. if(basedn == NULL || *basedn == '\0')
  1628. {
  1629. DBGLOG("corresponding basedn is not defined for authorize");
  1630. return false;
  1631. }
  1632. const char* username = user.getName();
  1633. if(!username || !*username)
  1634. {
  1635. DBGLOG("CLdapClient::authorize username must be specified");
  1636. return false;
  1637. }
  1638. const char* sysuser = m_ldapconfig->getSysUser();
  1639. if(sysuser && *sysuser && (strcmp(username, sysuser) == 0))
  1640. {
  1641. ForEachItemIn(x, resources)
  1642. {
  1643. ISecResource* res = &resources.item(x);
  1644. if(!res)
  1645. continue;
  1646. if(rtype == RT_MODULE)
  1647. {
  1648. StringBuffer filter;
  1649. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  1650. filter.append("name=");
  1651. else
  1652. filter.append("ou=");
  1653. filter.append(res->getName());
  1654. int count = countEntries(m_ldapconfig->getResourceBasedn(rtype), (char*)filter.str(), 10);
  1655. if(count != 0)
  1656. res->setAccessFlags(SecAccess_Full);
  1657. else
  1658. res->setAccessFlags(SecAccess_Unavailable);
  1659. }
  1660. else
  1661. res->setAccessFlags(SecAccess_Full);
  1662. }
  1663. return true;
  1664. }
  1665. if(rtype == RT_FILE_SCOPE)
  1666. {
  1667. SecAccessFlags defaultFileScopePermission = queryDefaultPermission(user);
  1668. IArrayOf<ISecResource> non_emptylist;
  1669. ForEachItemIn(x, resources)
  1670. {
  1671. ISecResource& res = resources.item(x);
  1672. const char* res_name = res.getName();
  1673. if(res_name == NULL || *res_name == '\0')
  1674. res.setAccessFlags(defaultFileScopePermission); //res.setAccessFlags(m_defaultFileScopePermission);
  1675. else
  1676. non_emptylist.append(*LINK(&res));
  1677. }
  1678. ok = authorizeScope(user, non_emptylist, basedn);
  1679. //if(ok && m_defaultFileScopePermission != -2)
  1680. if(ok && defaultFileScopePermission != UNK_PERM_VALUE)
  1681. {
  1682. ForEachItemIn(x, non_emptylist)
  1683. {
  1684. ISecResource& res = non_emptylist.item(x);
  1685. if(res.getAccessFlags() == -1)
  1686. res.setAccessFlags(defaultFileScopePermission); //res.setAccessFlags(m_defaultFileScopePermission);
  1687. }
  1688. }
  1689. return ok;
  1690. }
  1691. else if(rtype == RT_WORKUNIT_SCOPE)
  1692. {
  1693. SecAccessFlags defaultWorkunitScopePermission = UNK_PERM_VALUE;//init to invalid SecAccessFlags value
  1694. //if(m_defaultWorkunitScopePermission == -2)
  1695. {
  1696. const char* basebasedn = strchr(basedn, ',') + 1;
  1697. StringBuffer baseresource;
  1698. baseresource.append(basebasedn-basedn-4, basedn+3);
  1699. IArrayOf<ISecResource> base_resources;
  1700. base_resources.append(*(new CLdapSecResource(baseresource.str())));
  1701. bool baseok = authorizeScope(user, base_resources, basebasedn);
  1702. if(baseok)
  1703. {
  1704. defaultWorkunitScopePermission = base_resources.item(0).getAccessFlags();//replace UNK_PERM_VALUE with a valid flag
  1705. }
  1706. }
  1707. IArrayOf<ISecResource> non_emptylist;
  1708. ForEachItemIn(x, resources)
  1709. {
  1710. ISecResource& res = resources.item(x);
  1711. const char* res_name = res.getName();
  1712. if(res_name == NULL || *res_name == '\0')
  1713. res.setAccessFlags(defaultWorkunitScopePermission);
  1714. else
  1715. non_emptylist.append(*LINK(&res));
  1716. }
  1717. ok = authorizeScope(user, non_emptylist, basedn);
  1718. if(ok && defaultWorkunitScopePermission != UNK_PERM_VALUE)//if default perm is known, use it
  1719. {
  1720. ForEachItemIn(x, non_emptylist)
  1721. {
  1722. ISecResource& res = non_emptylist.item(x);
  1723. if(res.getAccessFlags() == -1)
  1724. res.setAccessFlags(defaultWorkunitScopePermission);
  1725. }
  1726. }
  1727. return ok;
  1728. }
  1729. else if (rtype == RT_VIEW_SCOPE)
  1730. {
  1731. SecAccessFlags defPerm = queryDefaultPermission(user); //default perm to be applied when no lfn or column provided
  1732. //Get view lfn/col mappings for this view
  1733. assertex(resources.ordinality() > 0);
  1734. assertex(resName && *resName != '\0');
  1735. StringArray viewFiles;
  1736. StringArray viewColumns;
  1737. queryViewColumns(resName, viewFiles, viewColumns);
  1738. unsigned numViewMembers = viewFiles.ordinality();
  1739. assertex(numViewMembers == viewColumns.ordinality());
  1740. StringAttr lfn;
  1741. StringAttr col;
  1742. unsigned fails = 0;
  1743. ForEachItemIn(idx, resources) //Iterate over all resources in list
  1744. {
  1745. ISecResource& res = resources.item(idx);
  1746. assertex(RT_VIEW_SCOPE == res.getResourceType());
  1747. lfn.set(res.getParameter("file"));
  1748. col.set(res.getParameter("column"));
  1749. #ifdef _DEBUG
  1750. DBGLOG("Checking '%s' RT_VIEW_SCOPE for lfn %s, col %s", resName, lfn.str(), col.str());
  1751. #endif
  1752. if (lfn.isEmpty() || col.isEmpty())
  1753. res.setAccessFlags(defPerm);
  1754. else
  1755. {
  1756. //Check LDAP
  1757. res.setAccessFlags(SecAccess_None);
  1758. ++fails;
  1759. for (unsigned vIdx = 0; vIdx < numViewMembers; vIdx++)
  1760. {
  1761. if (0 == stricmp(lfn.str(), viewFiles.item(vIdx)) &&
  1762. 0 == stricmp(col.str(), viewColumns.item(vIdx)))
  1763. {
  1764. res.setAccessFlags(SecAccess_Full);
  1765. --fails;
  1766. break;
  1767. }
  1768. }
  1769. }
  1770. }
  1771. return fails == 0 ? true : false;
  1772. }
  1773. else
  1774. {
  1775. IArrayOf<CSecurityDescriptor> sdlist;
  1776. ForEachItemIn(x, resources)
  1777. {
  1778. ISecResource& res = resources.item(x);
  1779. const char* resourcename = res.getName();
  1780. CSecurityDescriptor* sd = new CSecurityDescriptor(resourcename);
  1781. sdlist.append(*sd);
  1782. }
  1783. getSecurityDescriptors(rtype, sdlist);
  1784. if(m_pp != NULL)
  1785. ok = m_pp->getPermissions(user, sdlist, resources);
  1786. return ok;
  1787. }
  1788. }
  1789. // Returns true if all resources are correctly added, otherwise returns false.
  1790. virtual bool addResources(SecResourceType rtype, ISecUser& user, IArrayOf<ISecResource>& resources, SecPermissionType ptype, const char* basedn)
  1791. {
  1792. bool ret = true;
  1793. for(unsigned i = 0; i < resources.length(); i++)
  1794. {
  1795. ISecResource* resource = &resources.item(i);
  1796. if(resource != NULL)
  1797. {
  1798. bool oneret = addResource(rtype, user, resource, ptype, basedn);
  1799. ret = ret && oneret;
  1800. }
  1801. }
  1802. return ret;
  1803. }
  1804. virtual bool getUserInfo(ISecUser& user, const char* infotype)
  1805. {
  1806. char *attribute;
  1807. LDAPMessage *message;
  1808. const char* username = user.getName();
  1809. if(username == NULL || strlen(username) == 0)
  1810. {
  1811. DBGLOG("LDAP: getUserInfo : username is empty");
  1812. return false;
  1813. }
  1814. if(infotype && stricmp(infotype, "sudoers") == 0)
  1815. {
  1816. CLdapSecUser* ldapuser = dynamic_cast<CLdapSecUser*>(&user);
  1817. if (ldapuser == nullptr)
  1818. {
  1819. throw MakeStringException(-1, "Unable to cast user %s to CLdapSecUser", username);
  1820. }
  1821. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  1822. Owned<ILdapConnection> lconn = m_connections->getConnection();
  1823. LDAP* ld = lconn.get()->getLd();
  1824. StringBuffer filter("sudoUser=");
  1825. filter.append(username);
  1826. char *attrs[] = {"sudoHost", "sudoCommand", "sudoOption", NULL};
  1827. const char* basedn = m_ldapconfig->getResourceBasedn(RT_SUDOERS);
  1828. CLDAPMessage searchResult;
  1829. 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);
  1830. if ( rc != LDAP_SUCCESS )
  1831. {
  1832. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), basedn);
  1833. ldapuser->setSudoersEnabled(false);
  1834. ldapuser->setInSudoers(false);
  1835. return false;
  1836. }
  1837. ldapuser->setSudoersEnabled(true);
  1838. unsigned entries = ldap_count_entries(ld, searchResult);
  1839. if(entries == 0)
  1840. {
  1841. ldapuser->setInSudoers(false);
  1842. return true;
  1843. }
  1844. message = LdapFirstEntry(ld, searchResult);
  1845. if(message == NULL)
  1846. {
  1847. ldapuser->setInSudoers(false);
  1848. return true;
  1849. }
  1850. ldapuser->setInSudoers(true);
  1851. CLDAPGetAttributesWrapper atts(ld, searchResult);
  1852. for ( attribute = atts.getFirst();
  1853. attribute != NULL;
  1854. attribute = atts.getNext())
  1855. {
  1856. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  1857. if (vals.hasValues())
  1858. {
  1859. if(stricmp(attribute, "sudoHost") == 0)
  1860. ldapuser->setSudoHost(vals.queryCharValue(0));
  1861. else if(stricmp(attribute, "sudoCommand") == 0)
  1862. ldapuser->setSudoCommand(vals.queryCharValue(0));
  1863. else if(stricmp(attribute, "sudoOption") == 0)
  1864. ldapuser->setSudoOption(vals.queryCharValue(0));
  1865. }
  1866. }
  1867. return true;
  1868. }
  1869. else
  1870. {
  1871. StringBuffer filter;
  1872. const char* basedn = m_ldapconfig->getUserBasedn();
  1873. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  1874. {
  1875. filter.append("sAMAccountName=");
  1876. }
  1877. else
  1878. {
  1879. filter.append("uid=");
  1880. if(stricmp(username, m_ldapconfig->getSysUser()) == 0)
  1881. basedn = m_ldapconfig->getSysUserBasedn();
  1882. }
  1883. filter.append(user.getName());
  1884. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  1885. Owned<ILdapConnection> lconn = m_connections->getConnection();
  1886. LDAP* ld = lconn.get()->getLd();
  1887. char *attrs[] = {"cn", "givenName", "sn", "gidnumber", "uidnumber", "homedirectory", "loginshell", "objectClass", "employeeId", "employeeNumber", "distinguishedName", "userAccountControl", "pwdLastSet", NULL};
  1888. CLDAPMessage searchResult;
  1889. 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 );
  1890. if ( rc != LDAP_SUCCESS )
  1891. {
  1892. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), basedn);
  1893. return false;
  1894. }
  1895. bool accountPwdNeverExpires = false;
  1896. ((CLdapSecUser*)&user)->setPosixenabled(false);
  1897. // Go through the search results by checking message types
  1898. for(message = LdapFirstEntry( ld, searchResult); message != NULL; message = ldap_next_entry(ld, message))
  1899. {
  1900. CLDAPGetAttributesWrapper atts(ld, searchResult);
  1901. for ( attribute = atts.getFirst();
  1902. attribute != NULL;
  1903. attribute = atts.getNext())
  1904. {
  1905. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  1906. if (vals.hasValues())
  1907. {
  1908. if(stricmp(attribute, "cn") == 0)
  1909. user.setFullName(vals.queryCharValue(0));
  1910. else if(stricmp(attribute, "givenName") == 0)
  1911. user.setFirstName(vals.queryCharValue(0));
  1912. else if(stricmp(attribute, "sn") == 0)
  1913. user.setLastName(vals.queryCharValue(0));
  1914. else if(stricmp(attribute, "gidnumber") == 0)
  1915. ((CLdapSecUser*)&user)->setGidnumber(vals.queryCharValue(0));
  1916. else if(stricmp(attribute, "uidnumber") == 0)
  1917. ((CLdapSecUser*)&user)->setUidnumber(vals.queryCharValue(0));
  1918. else if(stricmp(attribute, "homedirectory") == 0)
  1919. ((CLdapSecUser*)&user)->setHomedirectory(vals.queryCharValue(0));
  1920. else if(stricmp(attribute, "loginshell") == 0)
  1921. ((CLdapSecUser*)&user)->setLoginshell(vals.queryCharValue(0));
  1922. else if(stricmp(attribute, "distinguishedName") == 0)
  1923. ((CLdapSecUser*)&user)->setDistinguishedName(vals.queryCharValue(0));
  1924. else if((stricmp(attribute, "userAccountControl") == 0))
  1925. {
  1926. //UF_DONT_EXPIRE_PASSWD 0x10000
  1927. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  1928. if (vals.hasValues())
  1929. if (atoi((char*)vals.queryCharValue(0)) & 0x10000)//this can be true at the account level, even if domain policy requires password
  1930. accountPwdNeverExpires = true;
  1931. }
  1932. else if(stricmp(attribute, "pwdLastSet") == 0)
  1933. {
  1934. CLDAPGetValuesLenWrapper valsLen(ld, message, attribute);
  1935. if (!m_domainPwdsNeverExpire && !accountPwdNeverExpires && valsLen.hasValues())
  1936. {
  1937. CDateTime expiry;
  1938. char * val = (char*)valsLen.queryCharValue(0);
  1939. calcPWExpiry(expiry, (unsigned)strlen(val), val);
  1940. ((CLdapSecUser*)&user)->setPasswordExpiration(expiry);
  1941. }
  1942. }
  1943. else if(stricmp(attribute, "objectClass") == 0)
  1944. {
  1945. int valind = 0;
  1946. while(vals.queryCharValue(valind))
  1947. {
  1948. if(stricmp(vals.queryCharValue(valind), "posixAccount") == 0)
  1949. {
  1950. ((CLdapSecUser*)&user)->setPosixenabled(true);
  1951. break;
  1952. }
  1953. valind++;
  1954. }
  1955. }
  1956. else if(stricmp(attribute, "employeeId") == 0)
  1957. user.setEmployeeID(vals.queryCharValue(0));
  1958. else if(stricmp(attribute, "employeeNumber") == 0)
  1959. user.setEmployeeNumber(vals.queryCharValue(0));
  1960. }
  1961. }
  1962. }
  1963. return true;
  1964. }
  1965. }
  1966. ISecUser* lookupUser(unsigned uid)
  1967. {
  1968. StringBuffer sysuser;
  1969. sysuser.append(m_ldapconfig->getSysUser());
  1970. if(sysuser.length() == 0)
  1971. {
  1972. #ifdef _WIN32
  1973. char uname[128];
  1974. unsigned long len = 128;
  1975. int rc = GetUserName(uname, &len);
  1976. if(rc != 0)
  1977. sysuser.append(len, uname);
  1978. else
  1979. throw MakeStringException(-1, "Error getting current user's username, error code = %d", rc);
  1980. #else
  1981. throw MakeStringException(-1, "systemUser not found in config");
  1982. #endif
  1983. }
  1984. MemoryBuffer usersidbuf;
  1985. StringBuffer usersidstr;
  1986. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  1987. {
  1988. if(m_pp != NULL)
  1989. m_pp->lookupSid(sysuser.str(), usersidbuf);
  1990. if(usersidbuf.length() == 0)
  1991. {
  1992. throw MakeStringException(-1, "system user %s's SID not found", sysuser.str());
  1993. }
  1994. int sidlen = usersidbuf.length();
  1995. char* uidbuf = (char*)&uid;
  1996. for(int i = 0; i < 4; i++)
  1997. {
  1998. usersidbuf.writeDirect(sidlen -4 + i, 1, (uidbuf + 3 - i));
  1999. }
  2000. LdapUtils::bin2str(usersidbuf, usersidstr);
  2001. }
  2002. else
  2003. {
  2004. usersidbuf.append(uid);
  2005. }
  2006. char *attribute;
  2007. LDAPMessage *message;
  2008. StringBuffer filter;
  2009. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2010. {
  2011. filter.append("objectSid=").append(usersidstr.str());
  2012. }
  2013. else
  2014. {
  2015. filter.appendf("entryid=%d", uid);
  2016. }
  2017. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  2018. Owned<ILdapConnection> lconn = m_connections->getConnection();
  2019. LDAP* ld = lconn.get()->getLd();
  2020. char* act_fieldname;
  2021. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2022. {
  2023. act_fieldname = "sAMAccountName";
  2024. }
  2025. else
  2026. {
  2027. act_fieldname = "uid";
  2028. }
  2029. char *attrs[] = {"cn", act_fieldname, NULL};
  2030. CLDAPMessage searchResult;
  2031. 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 );
  2032. if ( rc != LDAP_SUCCESS )
  2033. {
  2034. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), m_ldapconfig->getUserBasedn());
  2035. return NULL;
  2036. }
  2037. if(ldap_count_entries(ld, searchResult) < 1)
  2038. {
  2039. DBGLOG("No entries are found for user with uid %0X", uid);
  2040. return NULL;
  2041. }
  2042. CLdapSecUser* ldapuser = new CLdapSecUser("", "");
  2043. // Go through the search results by checking message types
  2044. for(message = LdapFirstEntry( ld, searchResult); message != NULL; message = ldap_next_entry(ld, message))
  2045. {
  2046. CLDAPGetAttributesWrapper atts(ld, searchResult);
  2047. for ( attribute = atts.getFirst();
  2048. attribute != NULL;
  2049. attribute = atts.getNext())
  2050. {
  2051. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  2052. if (vals.hasValues())
  2053. {
  2054. if(stricmp(attribute, "cn") == 0)
  2055. ldapuser->setFullName(vals.queryCharValue(0));
  2056. else if(stricmp(attribute, act_fieldname) == 0)
  2057. ldapuser->setName(vals.queryCharValue(0));
  2058. }
  2059. }
  2060. }
  2061. ldapuser->setUserID(uid);
  2062. ldapuser->setUserSid(usersidbuf.length(), usersidbuf.toByteArray());
  2063. // Since we've got the SID for the user, cache it for later uses.
  2064. MemoryBuffer mb;
  2065. if(m_pp != NULL)
  2066. {
  2067. m_pp->getCachedSid(ldapuser->getName(), mb);
  2068. if(mb.length() == 0)
  2069. {
  2070. m_pp->cacheSid(ldapuser->getName(), usersidbuf.length(), usersidbuf.toByteArray());
  2071. }
  2072. }
  2073. return ldapuser;
  2074. }
  2075. bool lookupAccount(MemoryBuffer& sidbuf, StringBuffer& account_name, ACT_TYPE& act_type)
  2076. {
  2077. {
  2078. int sidLen = sidbuf.length();
  2079. ReadLockBlock readLock(m_unknownSIDCacheLock);
  2080. ForEachItemIn(idx, m_unknownSIDCache)
  2081. {
  2082. MemoryAttrItem& sid = m_unknownSIDCache.item(idx);
  2083. if (sid.length()==sidLen && 0==memcmp(sid.bufferBase(), sidbuf.bufferBase(), sidLen))
  2084. {
  2085. return false;
  2086. }
  2087. }
  2088. }
  2089. char *attribute;
  2090. LDAPMessage *message;
  2091. char* act_fieldname;
  2092. StringBuffer filter;
  2093. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2094. {
  2095. act_fieldname = "sAMAccountName";
  2096. StringBuffer usersidstr;
  2097. LdapUtils::bin2str(sidbuf, usersidstr);
  2098. filter.append("objectSid=").append(usersidstr.str());
  2099. }
  2100. else
  2101. {
  2102. unsigned* uid = (unsigned*)sidbuf.toByteArray();
  2103. filter.appendf("entryid=%d", *uid);
  2104. act_fieldname = "uid";
  2105. }
  2106. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  2107. Owned<ILdapConnection> lconn = m_connections->getConnection();
  2108. LDAP* ld = lconn.get()->getLd();
  2109. char *attrs[] = {"cn", act_fieldname, "objectClass", NULL};
  2110. CLDAPMessage searchResult;
  2111. 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 );
  2112. if ( rc != LDAP_SUCCESS )
  2113. {
  2114. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), m_ldapconfig->getUserBasedn());
  2115. return false;
  2116. }
  2117. if(ldap_count_entries(ld, searchResult) < 1)
  2118. {
  2119. searchResult.ldapMsgFree();
  2120. 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 );
  2121. if(ldap_count_entries(ld, searchResult) < 1)
  2122. {
  2123. searchResult.ldapMsgFree();
  2124. 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 );
  2125. if(ldap_count_entries(ld, searchResult) < 1)
  2126. {
  2127. MemoryAttrItem *pItem = new MemoryAttrItem();
  2128. pItem->set(sidbuf.length(), sidbuf.bufferBase());
  2129. WriteLockBlock writeLock(m_unknownSIDCacheLock);
  2130. m_unknownSIDCache.append(*pItem);//remember orphaned SID so won't try to look up again
  2131. return false;
  2132. }
  2133. }
  2134. }
  2135. StringBuffer act_name;
  2136. StringBuffer cnbuf;
  2137. // Go through the search results by checking message types
  2138. for(message = LdapFirstEntry( ld, searchResult); message != NULL; message = ldap_next_entry(ld, message))
  2139. {
  2140. CLDAPGetAttributesWrapper atts(ld, searchResult);
  2141. for ( attribute = atts.getFirst();
  2142. attribute != NULL;
  2143. attribute = atts.getNext())
  2144. {
  2145. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  2146. if (vals.hasValues())
  2147. {
  2148. if(stricmp(attribute, act_fieldname) == 0)
  2149. act_name.clear().append(vals.queryCharValue(0));
  2150. else if(stricmp(attribute, "cn") == 0)
  2151. cnbuf.clear().append(vals.queryCharValue(0));
  2152. else if(stricmp(attribute, "objectClass") == 0)
  2153. {
  2154. int i = 0;
  2155. while(vals.queryCharValue(i) != NULL)
  2156. {
  2157. if(stricmp(vals.queryCharValue(i), "person") == 0)
  2158. act_type = USER_ACT;
  2159. else if(stricmp(vals.queryCharValue(i), "group") == 0)
  2160. act_type = GROUP_ACT;
  2161. i++;
  2162. }
  2163. }
  2164. }
  2165. }
  2166. }
  2167. if(act_type == USER_ACT)
  2168. account_name.append(act_name.str());
  2169. else
  2170. account_name.append(cnbuf.str());
  2171. return true;
  2172. }
  2173. virtual void lookupSid(const char* basedn, const char* filter, MemoryBuffer& act_sid)
  2174. {
  2175. char *attribute;
  2176. LDAPMessage *message;
  2177. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  2178. Owned<ILdapConnection> lconn = m_connections->getConnection();
  2179. LDAP* ld = lconn.get()->getLd();
  2180. char* fieldname;
  2181. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2182. fieldname = "objectSid";
  2183. else
  2184. fieldname = "entryid";
  2185. char *attrs[] = {fieldname, NULL};
  2186. CLDAPMessage searchResult;
  2187. int rc = ldap_search_ext_s(ld, (char*)basedn, LDAP_SCOPE_SUBTREE, (char*)filter, attrs, 0, NULL, NULL, &timeOut, LDAP_NO_LIMIT, &searchResult.msg );
  2188. if ( rc != LDAP_SUCCESS )
  2189. {
  2190. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter, basedn);
  2191. return;
  2192. }
  2193. message = LdapFirstEntry( ld, searchResult);
  2194. if(message != NULL)
  2195. {
  2196. CLDAPGetAttributesWrapper atts(ld, searchResult);
  2197. for ( attribute = atts.getFirst();
  2198. attribute != NULL;
  2199. attribute = atts.getNext())
  2200. {
  2201. if(0 == stricmp(attribute, fieldname))
  2202. {
  2203. CLDAPGetValuesLenWrapper valsLen(ld, message, attribute);
  2204. if (valsLen.hasValues())
  2205. {
  2206. struct berval* val = valsLen.queryBValues()[0];
  2207. if(val != NULL)
  2208. {
  2209. int len = val->bv_len;
  2210. act_sid.append(val->bv_len, val->bv_val);
  2211. }
  2212. }
  2213. break;
  2214. }
  2215. }
  2216. }
  2217. }
  2218. virtual void lookupSid(const char* act_name, MemoryBuffer& act_sid, ACT_TYPE act_type)
  2219. {
  2220. StringBuffer filter;
  2221. const char* basedn;
  2222. if(act_type == USER_ACT)
  2223. {
  2224. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2225. filter.append("sAMAccountName=").append(act_name);
  2226. else
  2227. filter.append("uid=").append(act_name);
  2228. basedn = m_ldapconfig->getUserBasedn();
  2229. if (m_ldapconfig->isAzureAD() && strieq(act_name, m_ldapconfig->getSysUser()))
  2230. basedn = m_ldapconfig->getSysUserBasedn();
  2231. lookupSid(basedn, filter.str(), act_sid);
  2232. if(act_sid.length() == 0)
  2233. {
  2234. StringBuffer basebuf;
  2235. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2236. basebuf.append("cn=Users,").append(m_ldapconfig->getBasedn());
  2237. else if(stricmp(act_name, m_ldapconfig->getSysUser()) == 0)
  2238. basebuf.append(m_ldapconfig->getSysUserBasedn());
  2239. else
  2240. basebuf.append("ou=People,").append(m_ldapconfig->getBasedn());
  2241. lookupSid(basebuf.str(), filter.str(), act_sid);
  2242. }
  2243. }
  2244. else
  2245. {
  2246. filter.append("cn=").append(act_name);
  2247. basedn = m_ldapconfig->getGroupBasedn();
  2248. lookupSid(basedn, filter.str(), act_sid);
  2249. if(act_sid.length() == 0)
  2250. {
  2251. StringBuffer basebuf;
  2252. basebuf.append("cn=Users,").append(m_ldapconfig->getBasedn());
  2253. lookupSid(basebuf.str(), filter.str(), act_sid);
  2254. if(act_sid.length() == 0)
  2255. {
  2256. basebuf.clear();
  2257. basebuf.append("cn=Builtin,").append(m_ldapconfig->getBasedn());
  2258. lookupSid(basebuf.str(), filter.str(), act_sid);
  2259. }
  2260. }
  2261. }
  2262. }
  2263. virtual void setPermissionProcessor(IPermissionProcessor* pp)
  2264. {
  2265. m_pp = pp;
  2266. }
  2267. virtual bool retrieveUsers(IUserArray& users)
  2268. {
  2269. return retrieveUsers("", users);
  2270. }
  2271. virtual bool retrieveUsers(const char* searchstr, IUserArray& users)
  2272. {
  2273. char *attribute;
  2274. LDAPMessage *message;
  2275. StringBuffer filter;
  2276. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2277. filter.append("objectClass=User");
  2278. else
  2279. filter.append("objectClass=inetorgperson");
  2280. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  2281. Owned<ILdapConnection> lconn = m_connections->getConnection();
  2282. LDAP* ld = lconn.get()->getLd();
  2283. char* act_fieldname;
  2284. char* sid_fieldname;
  2285. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2286. {
  2287. act_fieldname = "sAMAccountName";
  2288. sid_fieldname = "objectSid";
  2289. }
  2290. else
  2291. {
  2292. act_fieldname = "uid";
  2293. sid_fieldname = "entryid";
  2294. }
  2295. if(searchstr && *searchstr && strcmp(searchstr, "*") != 0)
  2296. {
  2297. filter.insert(0, "(&(");
  2298. filter.appendf(")(|(%s=*%s*)(%s=*%s*)(%s=*%s*)))", act_fieldname, searchstr, "givenName", searchstr, "sn", searchstr);
  2299. }
  2300. char *attrs[] = {act_fieldname, sid_fieldname, "cn", "userAccountControl", "pwdLastSet", "employeeId", "employeeNumber", NULL};
  2301. CPagedLDAPSearch pagedSrch(ld, m_ldapconfig->getLdapTimeout(), (char*)m_ldapconfig->getUserBasedn(), LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs);
  2302. for (message = pagedSrch.getFirstEntry(); message; message = pagedSrch.getNextEntry())
  2303. {
  2304. bool accountPwdNeverExpires = false;
  2305. Owned<ISecUser> user = new CLdapSecUser("", "");
  2306. // Go through the search results by checking message types
  2307. CLDAPGetAttributesWrapper atts(ld, message);
  2308. for ( attribute = atts.getFirst();
  2309. attribute != NULL;
  2310. attribute = atts.getNext())
  2311. {
  2312. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  2313. if (!vals.hasValues())
  2314. continue;
  2315. if(stricmp(attribute, "cn") == 0)
  2316. {
  2317. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  2318. if (vals.hasValues())
  2319. user->setFullName(vals.queryCharValue(0));
  2320. }
  2321. else if (stricmp(attribute, "userAccountControl") == 0)
  2322. {
  2323. //UF_DONT_EXPIRE_PASSWD 0x10000
  2324. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  2325. if (vals.hasValues())
  2326. if (atoi((char*)vals.queryCharValue(0)) & 0x10000)//this can be true at the account level, even if domain policy requires password
  2327. accountPwdNeverExpires = true;
  2328. }
  2329. else if(stricmp(attribute, "pwdLastSet") == 0)
  2330. {
  2331. CDateTime expiry;
  2332. if (!m_domainPwdsNeverExpire && !accountPwdNeverExpires)
  2333. {
  2334. CLDAPGetValuesLenWrapper valsLen(ld, message, attribute);
  2335. if (valsLen.hasValues())
  2336. {
  2337. struct berval* val = valsLen.queryBValues()[0];
  2338. calcPWExpiry(expiry, (unsigned)val->bv_len, val->bv_val);
  2339. }
  2340. }
  2341. else
  2342. expiry.clear();
  2343. user->setPasswordExpiration(expiry);
  2344. }
  2345. else if(stricmp(attribute, act_fieldname) == 0)
  2346. {
  2347. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  2348. if (vals.hasValues())
  2349. user->setName(vals.queryCharValue(0));
  2350. }
  2351. else if(stricmp(attribute, sid_fieldname) == 0)
  2352. {
  2353. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2354. {
  2355. CLDAPGetValuesLenWrapper valsLen(ld, message, attribute);
  2356. if (valsLen.hasValues())
  2357. {
  2358. struct berval* val = valsLen.queryBValues()[0];
  2359. if(val != NULL)
  2360. {
  2361. unsigned uid = val->bv_val[val->bv_len - 4];
  2362. int i;
  2363. for(i = 3; i > 0; i--)
  2364. {
  2365. uid = (uid << 8) + val->bv_val[val->bv_len - i];
  2366. }
  2367. ((CLdapSecUser*)user.get())->setUserID(uid);
  2368. }
  2369. }
  2370. }
  2371. else
  2372. {
  2373. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  2374. if (vals.hasValues())
  2375. ((CLdapSecUser*)user.get())->setUserID(atoi(vals.queryCharValue(0)));
  2376. }
  2377. }
  2378. else if(stricmp(attribute, "employeeId") == 0)
  2379. {
  2380. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  2381. if (vals.hasValues())
  2382. user->setEmployeeID(vals.queryCharValue(0));
  2383. }
  2384. else if(stricmp(attribute, "employeeNumber") == 0)
  2385. {
  2386. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  2387. if (vals.hasValues())
  2388. user->setEmployeeNumber(vals.queryCharValue(0));
  2389. }
  2390. }
  2391. if (user->getName() && *user->getName())
  2392. users.append(*LINK(user.get()));
  2393. }
  2394. return true;
  2395. }
  2396. virtual IPropertyTreeIterator* getUserIterator(const char* userName)
  2397. {
  2398. IUserArray users;
  2399. retrieveUsers(userName, users);
  2400. Owned<IPropertyTree> usersTree = createPTree("Users");
  2401. ForEachItemIn(i, users)
  2402. addUserTree(users.item(i), usersTree);
  2403. return usersTree->getElements("*");
  2404. }
  2405. void addUserTree(ISecUser& usr, IPropertyTree* users)
  2406. {
  2407. const char* usrName = usr.getName();
  2408. if(!usrName || !*usrName)
  2409. {
  2410. DBGLOG("CLdapClient::addUserTree username must be provided");
  2411. return;
  2412. }
  2413. const char* fullName = usr.getFullName();
  2414. StringBuffer sb;
  2415. switch (usr.getPasswordDaysRemaining())//-1 if expired, -2 if never expires
  2416. {
  2417. case scPasswordExpired:
  2418. sb.set("Expired");
  2419. break;
  2420. case scPasswordNeverExpires:
  2421. sb.set("Never");
  2422. break;
  2423. default:
  2424. CDateTime dt;
  2425. usr.getPasswordExpiration(dt);
  2426. dt.getDateString(sb);
  2427. break;
  2428. }
  2429. Owned<IPTree> userTree = createPTree("User");
  2430. userTree->addProp(getUserFieldNames(UFName), usrName);
  2431. if (fullName && *fullName)
  2432. userTree->addProp(getUserFieldNames(UFFullName), fullName);
  2433. userTree->addPropInt(getUserFieldNames(UFUserID), usr.getUserID());
  2434. userTree->addProp(getUserFieldNames(UFPasswordExpiration), sb.str());
  2435. userTree->addProp(getUserFieldNames(UFEmployeeID), usr.getEmployeeID());
  2436. userTree->addProp(getUserFieldNames(UFEmployeeNumber), usr.getEmployeeNumber());
  2437. users->addPropTree("User", userTree.getClear());
  2438. }
  2439. ISecItemIterator* getUsersSorted(const char* userName, UserField* sortOrder, const unsigned pageStartFrom, const unsigned pageSize, unsigned* total, __int64* cacheHint)
  2440. {
  2441. class CElementsPager : public CSimpleInterface, implements IElementsPager
  2442. {
  2443. ILdapClient* ldapClient;
  2444. StringAttr userName;
  2445. StringAttr sortOrder;
  2446. public:
  2447. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  2448. CElementsPager(ILdapClient* _ldapClient, const char* _userName, const char*_sortOrder)
  2449. : ldapClient(_ldapClient), userName(_userName), sortOrder(_sortOrder) { };
  2450. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree>& elements)
  2451. {
  2452. StringArray unknownAttributes;
  2453. Owned<IPropertyTreeIterator> iter = ldapClient->getUserIterator(userName.get());
  2454. sortElements(iter, sortOrder.get(), NULL, NULL, unknownAttributes, elements);
  2455. return NULL;
  2456. }
  2457. virtual bool allMatchingElementsReceived() { return true; }//For now, ldap always returns all of matched users.
  2458. };
  2459. StringBuffer so;
  2460. if (sortOrder)
  2461. {
  2462. for (unsigned i=0;sortOrder[i]!=UFterm;i++)
  2463. {
  2464. if (so.length())
  2465. so.append(',');
  2466. int fmt = sortOrder[i];
  2467. if (fmt&UFreverse)
  2468. so.append('-');
  2469. if (fmt&UFnocase)
  2470. so.append('?');
  2471. if (fmt&UFnumeric)
  2472. so.append('#');
  2473. so.append(getUserFieldNames((UserField) (fmt&0xff)));
  2474. }
  2475. }
  2476. IArrayOf<IPropertyTree> results;
  2477. Owned<IElementsPager> elementsPager = new CElementsPager(this, userName, so.length()?so.str():NULL);
  2478. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager, pageStartFrom, pageSize, NULL, "", cacheHint, results, total, NULL, false);
  2479. return new CSecItemIterator(results);
  2480. }
  2481. virtual bool userInGroup(const char* userdn, const char* groupdn)
  2482. {
  2483. const char* fldname;
  2484. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2485. fldname = "member";
  2486. else
  2487. fldname = "uniquemember";
  2488. Owned<ILdapConnection> lconn = m_connections->getConnection();
  2489. LDAP* ld = lconn.get()->getLd();
  2490. int rc = LDAP_COMPARE_EXT_S(ld, (const char*)groupdn, (const char*)fldname, (const char*)userdn,0,0,0);
  2491. #ifndef _WIN32
  2492. if (rc == -3)//389DirectoryServer always seems to return -3
  2493. rc = ldap_compare_s(ld, groupdn, fldname, userdn);
  2494. #endif
  2495. if(rc == LDAP_COMPARE_TRUE)
  2496. return true;
  2497. else
  2498. return false;
  2499. }
  2500. // Update user's firstname, lastname (plus displayname for active directory).
  2501. virtual bool updateUser(const char* type, ISecUser& user)
  2502. {
  2503. const char* username = user.getName();
  2504. if(!username || !*username)
  2505. {
  2506. DBGLOG("CLdapClient::updateUser username must be provided");
  2507. return false;
  2508. }
  2509. StringBuffer userdn;
  2510. getUserDN(username, userdn);
  2511. int rc = LDAP_SUCCESS;
  2512. if(!type || !*type || stricmp(type, "names") == 0)
  2513. {
  2514. StringBuffer cnbuf;
  2515. const char* fname = user.getFirstName();
  2516. const char* lname = user.getLastName();
  2517. if(fname && *fname && lname && *lname)
  2518. {
  2519. cnbuf.append(fname).append(" ").append(lname);
  2520. }
  2521. else
  2522. throw MakeStringException(-1, "Please specify both firstname and lastname");
  2523. char *gn_values[] = { (char*)fname, NULL };
  2524. LDAPMod gn_attr = {
  2525. LDAP_MOD_REPLACE,
  2526. "givenName",
  2527. gn_values
  2528. };
  2529. char *sn_values[] = { (char*)lname, NULL };
  2530. LDAPMod sn_attr = {
  2531. LDAP_MOD_REPLACE,
  2532. "sn",
  2533. sn_values
  2534. };
  2535. char *cn_values[] = {(char*)cnbuf.str(), NULL };
  2536. LDAPMod cn_attr =
  2537. {
  2538. LDAP_MOD_REPLACE,
  2539. "cn",
  2540. cn_values
  2541. };
  2542. char *dispname_values[] = {(char*)cnbuf.str(), NULL };
  2543. LDAPMod dispname_attr =
  2544. {
  2545. LDAP_MOD_REPLACE,
  2546. "displayName",
  2547. dispname_values
  2548. };
  2549. const char * emplID = user.getEmployeeID();
  2550. char *employeeID_values[] = {(emplID && *emplID) ? (char*)emplID : nullptr, nullptr };
  2551. LDAPMod employeeID_attr =
  2552. {
  2553. LDAP_MOD_REPLACE,
  2554. "employeeId",
  2555. employeeID_values
  2556. };
  2557. const char * emplNumber = user.getEmployeeNumber();
  2558. char *employeeNumber_values[] = {(emplNumber && *emplNumber) ? (char*)emplNumber : nullptr, nullptr };
  2559. LDAPMod employeeNumber_attr =
  2560. {
  2561. LDAP_MOD_REPLACE,
  2562. "employeeNumber",
  2563. employeeNumber_values
  2564. };
  2565. LDAPMod *attrs[6];
  2566. int ind = 0;
  2567. attrs[ind++] = &gn_attr;
  2568. attrs[ind++] = &sn_attr;
  2569. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2570. {
  2571. attrs[ind++] = &dispname_attr;
  2572. }
  2573. else
  2574. {
  2575. attrs[ind++] = &cn_attr;
  2576. }
  2577. attrs[ind++] = &employeeID_attr;
  2578. attrs[ind++] = &employeeNumber_attr;
  2579. attrs[ind] = NULL;
  2580. Owned<ILdapConnection> lconn = m_connections->getConnection();
  2581. LDAP* ld = lconn.get()->getLd();
  2582. rc = ldap_modify_ext_s(ld, (char*)userdn.str(), attrs, NULL, NULL);
  2583. if (rc == LDAP_SUCCESS && m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2584. {
  2585. StringBuffer newrdn("cn=");
  2586. newrdn.append(cnbuf.str());
  2587. rc = LdapRename(ld, (char*)userdn.str(), (char*)newrdn.str(), NULL, true, NULL, NULL);
  2588. }
  2589. }
  2590. else if(stricmp(type, "posixenable") == 0)
  2591. {
  2592. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2593. throw MakeStringException(-1, "posixAccount isn't applicable to Active Directory");
  2594. CLdapSecUser* ldapuser = dynamic_cast<CLdapSecUser*>(&user);
  2595. if (ldapuser == nullptr)
  2596. {
  2597. throw MakeStringException(-1, "Unable to cast user %s to CLdapSecUser", username);
  2598. }
  2599. char* oc_values[] = {"posixAccount", NULL};
  2600. LDAPMod oc_attr = {
  2601. LDAP_MOD_ADD,
  2602. "objectclass",
  2603. oc_values
  2604. };
  2605. char* oc1_values[] = {"shadowAccount", NULL};
  2606. LDAPMod oc1_attr = {
  2607. LDAP_MOD_ADD,
  2608. "objectclass",
  2609. oc1_values
  2610. };
  2611. char *gidnum_values[] = { (char*)ldapuser->getGidnumber(), NULL };
  2612. LDAPMod gidnum_attr = {
  2613. LDAP_MOD_REPLACE,
  2614. "gidnumber",
  2615. gidnum_values
  2616. };
  2617. char *uidnum_values[] = { (char*)ldapuser->getUidnumber(), NULL };
  2618. LDAPMod uidnum_attr = {
  2619. LDAP_MOD_REPLACE,
  2620. "uidnumber",
  2621. uidnum_values
  2622. };
  2623. char *homedir_values[] = {(char*)ldapuser->getHomedirectory(), NULL };
  2624. LDAPMod homedir_attr =
  2625. {
  2626. LDAP_MOD_REPLACE,
  2627. "homedirectory",
  2628. homedir_values
  2629. };
  2630. char *loginshell_values[] = {(char*)ldapuser->getLoginshell(), NULL };
  2631. LDAPMod loginshell_attr =
  2632. {
  2633. LDAP_MOD_REPLACE,
  2634. "loginshell",
  2635. loginshell_values
  2636. };
  2637. LDAPMod *attrs[7];
  2638. int ind = 0;
  2639. attrs[ind++] = &gidnum_attr;
  2640. attrs[ind++] = &uidnum_attr;
  2641. attrs[ind++] = &homedir_attr;
  2642. attrs[ind++] = &loginshell_attr;
  2643. Owned<ILdapConnection> lconn = m_connections->getConnection();
  2644. LDAP* ld = lconn.get()->getLd();
  2645. int compresult = LDAP_COMPARE_EXT_S(ld, (const char*)userdn.str(), (const char*)"objectclass", (const char*)"posixAccount",0,0,0);
  2646. #ifndef _WIN32
  2647. if (compresult == -3)//389DirectoryServer always seems to return -3
  2648. compresult = ldap_compare_s(ld, userdn.str(), "objectclass", "posixAccount");
  2649. #endif
  2650. if(compresult != LDAP_COMPARE_TRUE)
  2651. attrs[ind++] = &oc_attr;
  2652. compresult = LDAP_COMPARE_EXT_S(ld, (const char*)userdn.str(), (const char*)"objectclass", (const char*)"shadowAccount",0,0,0);
  2653. #ifndef _WIN32
  2654. if (compresult == -3)//389DirectoryServer always seems to return -3
  2655. compresult = ldap_compare_s(ld, userdn.str(), "objectclass", "shadowAccount");
  2656. #endif
  2657. if(compresult != LDAP_COMPARE_TRUE)
  2658. attrs[ind++] = &oc1_attr;
  2659. attrs[ind] = NULL;
  2660. rc = ldap_modify_ext_s(ld, (char*)userdn.str(), attrs, NULL, NULL);
  2661. }
  2662. else if(stricmp(type, "posixdisable") == 0)
  2663. {
  2664. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  2665. throw MakeStringException(-1, "posixAccount isn't applicable to Active Directory");
  2666. Owned<ILdapConnection> lconn = m_connections->getConnection();
  2667. LDAP* ld = lconn.get()->getLd();
  2668. int compresult = LDAP_COMPARE_EXT_S(ld, (const char*)userdn.str(), (const char*)"objectclass", (const char*)"posixAccount",0,0,0);
  2669. #ifndef _WIN32
  2670. if (compresult == -3)//389DirectoryServer always seems to return -3
  2671. compresult = ldap_compare_s(ld, userdn.str(), "objectclass", "posixAccount");
  2672. #endif
  2673. if(compresult != LDAP_COMPARE_TRUE)
  2674. {
  2675. rc = LDAP_SUCCESS;
  2676. }
  2677. else
  2678. {
  2679. char* oc_values[] = {"posixAccount", NULL};
  2680. LDAPMod oc_attr = {
  2681. LDAP_MOD_DELETE,
  2682. "objectclass",
  2683. oc_values
  2684. };
  2685. char* oc1_values[] = {"shadowAccount", NULL};
  2686. LDAPMod oc1_attr = {
  2687. LDAP_MOD_DELETE,
  2688. "objectclass",
  2689. oc1_values
  2690. };
  2691. char *gidnum_values[] = { NULL };
  2692. LDAPMod gidnum_attr = {
  2693. LDAP_MOD_DELETE,
  2694. "gidnumber",
  2695. gidnum_values
  2696. };
  2697. char *uidnum_values[] = {NULL };
  2698. LDAPMod uidnum_attr = {
  2699. LDAP_MOD_DELETE,
  2700. "uidnumber",
  2701. uidnum_values
  2702. };
  2703. char *homedir_values[] = { NULL };
  2704. LDAPMod homedir_attr =
  2705. {
  2706. LDAP_MOD_DELETE,
  2707. "homedirectory",
  2708. homedir_values
  2709. };
  2710. char *loginshell_values[] = { NULL };
  2711. LDAPMod loginshell_attr =
  2712. {
  2713. LDAP_MOD_DELETE,
  2714. "loginshell",
  2715. loginshell_values
  2716. };
  2717. LDAPMod *attrs[7];
  2718. int ind = 0;
  2719. attrs[ind++] = &gidnum_attr;
  2720. attrs[ind++] = &uidnum_attr;
  2721. attrs[ind++] = &homedir_attr;
  2722. attrs[ind++] = &loginshell_attr;
  2723. attrs[ind++] = &oc_attr;
  2724. attrs[ind++] = &oc1_attr;
  2725. attrs[ind] = NULL;
  2726. rc = ldap_modify_ext_s(ld, (char*)userdn.str(), attrs, NULL, NULL);
  2727. }
  2728. }
  2729. else if(stricmp(type, "sudoersadd") == 0)
  2730. {
  2731. CLdapSecUser* ldapuser = dynamic_cast<CLdapSecUser*>(&user);
  2732. if (ldapuser == nullptr)
  2733. {
  2734. throw MakeStringException(-1, "Unable to cast user %s to CLdapSecUser", username);
  2735. }
  2736. char *cn_values[] = {(char*)username, NULL };
  2737. LDAPMod cn_attr =
  2738. {
  2739. LDAP_MOD_ADD,
  2740. "cn",
  2741. cn_values
  2742. };
  2743. char *oc_values[] = {"sudoRole", NULL };
  2744. LDAPMod oc_attr =
  2745. {
  2746. LDAP_MOD_ADD,
  2747. "objectClass",
  2748. oc_values
  2749. };
  2750. char *user_values[] = {(char*)username, NULL };
  2751. LDAPMod user_attr =
  2752. {
  2753. LDAP_MOD_ADD,
  2754. "sudoUser",
  2755. user_values
  2756. };
  2757. char* sudoHost = (char*)ldapuser->getSudoHost();
  2758. char* sudoCommand = (char*)ldapuser->getSudoCommand();
  2759. char* sudoOption = (char*)ldapuser->getSudoOption();
  2760. char *host_values[] = {sudoHost, NULL };
  2761. LDAPMod host_attr =
  2762. {
  2763. LDAP_MOD_ADD,
  2764. "sudoHost",
  2765. host_values
  2766. };
  2767. char *cmd_values[] = {sudoCommand, NULL };
  2768. LDAPMod cmd_attr =
  2769. {
  2770. LDAP_MOD_ADD,
  2771. "sudoCommand",
  2772. cmd_values
  2773. };
  2774. char *option_values[] = {sudoOption, NULL };
  2775. LDAPMod option_attr =
  2776. {
  2777. LDAP_MOD_ADD,
  2778. "sudoOption",
  2779. option_values
  2780. };
  2781. LDAPMod *attrs[8];
  2782. int ind = 0;
  2783. attrs[ind++] = &cn_attr;
  2784. attrs[ind++] = &oc_attr;
  2785. attrs[ind++] = &user_attr;
  2786. if(sudoHost && *sudoHost)
  2787. attrs[ind++] = &host_attr;
  2788. if(sudoCommand && *sudoCommand)
  2789. attrs[ind++] = &cmd_attr;
  2790. if(sudoOption && *sudoOption)
  2791. attrs[ind++] = &option_attr;
  2792. attrs[ind] = NULL;
  2793. Owned<ILdapConnection> lconn = m_connections->getConnection();
  2794. LDAP* ld = lconn.get()->getLd();
  2795. StringBuffer dn;
  2796. dn.append("cn=").append(username).append(",").append(m_ldapconfig->getResourceBasedn(RT_SUDOERS));
  2797. int rc = ldap_add_ext_s(ld, (char*)dn.str(), attrs, NULL, NULL);
  2798. if ( rc != LDAP_SUCCESS )
  2799. {
  2800. if(rc == LDAP_ALREADY_EXISTS)
  2801. {
  2802. throw MakeStringException(-1, "can't add %s to sudoers, an LDAP object with this name already exists", username);
  2803. }
  2804. else
  2805. {
  2806. DBGLOG("error adding %s to sudoers: %s", username, ldap_err2string( rc ));
  2807. throw MakeStringException(-1, "error adding %s to sudoers: %s", username, ldap_err2string( rc ));
  2808. }
  2809. }
  2810. }
  2811. else if(stricmp(type, "sudoersdelete") == 0)
  2812. {
  2813. StringBuffer dn;
  2814. dn.append("cn=").append(username).append(",").append(m_ldapconfig->getResourceBasedn(RT_SUDOERS));
  2815. Owned<ILdapConnection> lconn = m_connections->getConnection();
  2816. LDAP* ld = lconn.get()->getLd();
  2817. int rc = ldap_delete_ext_s(ld, (char*)dn.str(), NULL, NULL);
  2818. if ( rc != LDAP_SUCCESS )
  2819. {
  2820. throw MakeStringException(-1, "Error deleting user %s from sudoers: %s", username, ldap_err2string(rc));
  2821. }
  2822. }
  2823. else if(stricmp(type, "sudoersupdate") == 0)
  2824. {
  2825. CLdapSecUser* ldapuser = dynamic_cast<CLdapSecUser*>(&user);
  2826. if (ldapuser == nullptr)
  2827. {
  2828. throw MakeStringException(-1, "Unable to cast user %s to CLdapSecUser", username);
  2829. }
  2830. char* sudoHost = (char*)ldapuser->getSudoHost();
  2831. char* sudoCommand = (char*)ldapuser->getSudoCommand();
  2832. char* sudoOption = (char*)ldapuser->getSudoOption();
  2833. char *host_values[] = {(sudoHost&&*sudoHost)?sudoHost:NULL, NULL };
  2834. LDAPMod host_attr =
  2835. {
  2836. LDAP_MOD_REPLACE,
  2837. "sudoHost",
  2838. host_values
  2839. };
  2840. char *cmd_values[] = {(sudoCommand&&*sudoCommand)?sudoCommand:NULL, NULL };
  2841. LDAPMod cmd_attr =
  2842. {
  2843. LDAP_MOD_REPLACE,
  2844. "sudoCommand",
  2845. cmd_values
  2846. };
  2847. char *option_values[] = {(sudoOption&&*sudoOption)?sudoOption:NULL, NULL };
  2848. LDAPMod option_attr =
  2849. {
  2850. LDAP_MOD_REPLACE,
  2851. "sudoOption",
  2852. option_values
  2853. };
  2854. LDAPMod *attrs[4];
  2855. int ind = 0;
  2856. attrs[ind++] = &host_attr;
  2857. attrs[ind++] = &cmd_attr;
  2858. attrs[ind++] = &option_attr;
  2859. attrs[ind] = NULL;
  2860. Owned<ILdapConnection> lconn = m_connections->getConnection();
  2861. LDAP* ld = lconn.get()->getLd();
  2862. StringBuffer dn;
  2863. dn.append("cn=").append(username).append(",").append(m_ldapconfig->getResourceBasedn(RT_SUDOERS));
  2864. int rc = ldap_modify_ext_s(ld, (char*)dn.str(), attrs, NULL, NULL);
  2865. if ( rc != LDAP_SUCCESS )
  2866. {
  2867. DBGLOG("error modifying sudoers for user %s: %s", username, ldap_err2string( rc ));
  2868. throw MakeStringException(-1, "error modifying sudoers for user %s: %s", username, ldap_err2string( rc ));
  2869. }
  2870. }
  2871. if (rc == LDAP_SUCCESS )
  2872. DBGLOG("User %s successfully updated", username);
  2873. else
  2874. throw MakeStringException(-1, "Error updating user %s - %s", username, ldap_err2string( rc ));
  2875. return true;
  2876. }
  2877. virtual bool changePasswordSSL(const char* username, const char* newPassword)
  2878. {
  2879. Owned<ILdapConnection> lconn;
  2880. try
  2881. {
  2882. lconn.setown(m_connections->getSSLConnection());
  2883. }
  2884. catch(IException*)
  2885. {
  2886. 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);
  2887. }
  2888. LDAP* ld = lconn.get()->getLd();
  2889. char *attribute, **values = NULL;
  2890. LDAPMessage *message;
  2891. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  2892. StringBuffer filter;
  2893. filter.append("sAMAccountName=").append(username);
  2894. char *attrs[] = {"distinguishedName", NULL};
  2895. CLDAPMessage searchResult;
  2896. 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 );
  2897. if ( rc != LDAP_SUCCESS )
  2898. {
  2899. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), m_ldapconfig->getUserBasedn());
  2900. return false;
  2901. }
  2902. StringBuffer userdn;
  2903. message = LdapFirstEntry( ld, searchResult);
  2904. if(message != NULL)
  2905. {
  2906. CLDAPGetAttributesWrapper atts(ld, searchResult);
  2907. for ( attribute = atts.getFirst();
  2908. attribute != NULL;
  2909. attribute = atts.getNext())
  2910. {
  2911. if(0 == stricmp(attribute, "distinguishedName"))
  2912. {
  2913. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  2914. if (vals.hasValues())
  2915. userdn.set(vals.queryCharValue(0));
  2916. break;
  2917. }
  2918. }
  2919. }
  2920. if(userdn.length() == 0)
  2921. {
  2922. throw MakeStringException(-1, "can't find dn for user %s", username);
  2923. }
  2924. LDAPMod modPassword;
  2925. LDAPMod *modEntry[2];
  2926. struct berval pwdBerVal;
  2927. struct berval *pwd_attr[2];
  2928. unsigned short pszPasswordWithQuotes[1024];
  2929. modEntry[0] = &modPassword;
  2930. modEntry[1] = NULL;
  2931. modPassword.mod_op = LDAP_MOD_REPLACE | LDAP_MOD_BVALUES;
  2932. modPassword.mod_type = "unicodePwd";
  2933. modPassword.mod_vals.modv_bvals = pwd_attr;
  2934. pwd_attr[0] = &pwdBerVal;
  2935. pwd_attr[1]= NULL;
  2936. StringBuffer quotedPasswd("\"");
  2937. quotedPasswd.append(newPassword).append("\"");
  2938. ConvertCToW(pszPasswordWithQuotes, quotedPasswd);
  2939. pwdBerVal.bv_len = quotedPasswd.length() * sizeof(unsigned short);
  2940. pwdBerVal.bv_val = (char*)pszPasswordWithQuotes;
  2941. rc = ldap_modify_ext_s(ld, (char*)userdn.str(), modEntry, NULL, NULL);
  2942. if (rc == LDAP_SUCCESS )
  2943. DBGLOG("User %s's password has been changed successfully", username);
  2944. else
  2945. {
  2946. StringBuffer errmsg;
  2947. errmsg.appendf("Error setting password for %s - (%d) %s.", username, rc, ldap_err2string( rc ));
  2948. if(rc == LDAP_UNWILLING_TO_PERFORM)
  2949. errmsg.append(" The ldap server refused to change the password. Usually this is because your new password doesn't satisfy the domain policy.");
  2950. throw MakeStringExceptionDirect(-1, errmsg.str());
  2951. }
  2952. return true;
  2953. }
  2954. virtual bool queryPasswordStatus(ISecUser& user, const char* password)
  2955. {
  2956. char *ldap_errstring = NULL;
  2957. const char * username = user.getName();
  2958. StringBuffer userdn;
  2959. getUserDN(user.getName(), userdn);
  2960. StringBuffer hostbuf;
  2961. m_ldapconfig->getLdapHost(hostbuf);
  2962. LDAP* user_ld = LdapUtils::LdapInit(m_ldapconfig->getProtocol(), hostbuf.str(), m_ldapconfig->getLdapPort(), m_ldapconfig->getLdapSecurePort());
  2963. int rc = LdapUtils::LdapBind(user_ld, m_ldapconfig->getLdapTimeout(),m_ldapconfig->getDomain(), username, password, userdn, m_ldapconfig->getServerType(), m_ldapconfig->getAuthMethod());
  2964. if(rc != LDAP_SUCCESS)
  2965. ldap_get_option(user_ld, LDAP_OPT_ERROR_STRING, &ldap_errstring);
  2966. LDAP_UNBIND(user_ld);
  2967. //Error string ""80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 532, v1db0."
  2968. //is returned if pw valid but expired
  2969. if(rc == LDAP_SUCCESS || strstr(ldap_errstring, "data 532") || strstr(ldap_errstring, "data 773"))//
  2970. return true;
  2971. else
  2972. return false;
  2973. }
  2974. virtual bool updateUserPassword(ISecUser& user, const char* newPassword, const char* currPassword)
  2975. {
  2976. const char* username = user.getName();
  2977. if(!username || !*username)
  2978. {
  2979. DBGLOG("CLdapClient::updateUserPassword username must be provided");
  2980. return false;
  2981. }
  2982. if (currPassword)
  2983. {
  2984. //User will not be authenticated if their password was expired,
  2985. //so check here that they provided a valid one in the "change
  2986. //password" form (use the one they type, not the one in the secuser)
  2987. bool validated = queryPasswordStatus(user, currPassword);
  2988. if (!validated)
  2989. throw MakeStringException(-1, "Password not changed, invalid credentials");
  2990. }
  2991. return updateUserPassword(username, newPassword);
  2992. }
  2993. virtual bool updateUserPassword(const char* username, const char* newPassword)
  2994. {
  2995. if(!username || !*username)
  2996. {
  2997. DBGLOG("CLdapClient::updateUserPassword username must be provided");
  2998. return false;
  2999. }
  3000. const char* sysuser = m_ldapconfig->getSysUser();
  3001. if(sysuser && *sysuser && strcmp(username, sysuser) == 0)
  3002. throw MakeStringException(-1, "You can't change password of the system user.");
  3003. LdapServerType servertype = m_ldapconfig->getServerType();
  3004. bool ret = true;
  3005. if(servertype == ACTIVE_DIRECTORY)
  3006. {
  3007. #ifdef _WIN32
  3008. DWORD nStatus = 0;
  3009. // The application has to run on the same domain as ldap host, and under an administrative user.
  3010. USER_INFO_1003 usriSetPassword;
  3011. StringBuffer fullserver("\\\\");
  3012. StringBuffer server;
  3013. m_ldapconfig->getLdapHost(server);
  3014. fullserver.append(server.str());
  3015. LPWSTR whost = (LPWSTR)alloca((fullserver.length() +1) * sizeof(WCHAR));
  3016. ConvertCToW((unsigned short *)whost, fullserver.str());
  3017. LPWSTR wusername = (LPWSTR)alloca((strlen(username) + 1) * sizeof(WCHAR));
  3018. ConvertCToW((unsigned short *)wusername, username);
  3019. LPWSTR wnewpasswd = (LPWSTR)alloca((strlen(newPassword) + 1) * sizeof(WCHAR));
  3020. ConvertCToW((unsigned short *)wnewpasswd, newPassword);
  3021. usriSetPassword.usri1003_password = wnewpasswd;
  3022. nStatus = NetUserSetInfo(whost, wusername, 1003, (LPBYTE)&usriSetPassword, NULL);
  3023. if (nStatus == NERR_Success)
  3024. {
  3025. DBGLOG("User %s's password has been changed successfully", username);
  3026. return true;
  3027. }
  3028. else
  3029. {
  3030. StringBuffer errcode, errmsg;
  3031. if(nStatus == ERROR_ACCESS_DENIED)
  3032. {
  3033. errcode.append("ERROR_ACCESS_DENIED");
  3034. errmsg.append("The user does not have access to the requested information.");
  3035. }
  3036. else if(nStatus == ERROR_INVALID_PASSWORD)
  3037. {
  3038. errcode.append("ERROR_INVALID_PASSWORD");
  3039. errmsg.append("The user has entered an invalid password.");
  3040. }
  3041. else if(nStatus == NERR_InvalidComputer)
  3042. {
  3043. errcode.append("NERR_InvalidComputer");
  3044. errmsg.append("The computer name is invalid.");
  3045. }
  3046. else if(nStatus == NERR_NotPrimary)
  3047. {
  3048. errcode.append("NERR_NotPrimary");
  3049. errmsg.append("The operation is allowed only on the primary domain controller of the domain.");
  3050. }
  3051. else if(nStatus == NERR_UserNotFound)
  3052. {
  3053. errcode.append("NERR_UserNotFound");
  3054. errmsg.append("The user name could not be found.");
  3055. }
  3056. else if(nStatus == NERR_PasswordTooShort)
  3057. {
  3058. errcode.append("NERR_PasswordTooShort");
  3059. errmsg.append("The password is shorter than required. ");
  3060. }
  3061. else if(nStatus == ERROR_LOGON_FAILURE)
  3062. {
  3063. errcode.append("ERROR_LOGON_FAILURE");
  3064. 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. ");
  3065. }
  3066. else
  3067. {
  3068. errcode.appendf("%d", nStatus);
  3069. errmsg.append("");
  3070. }
  3071. // For certain errors just return, other errors try changePasswordSSL.
  3072. if(nStatus == ERROR_INVALID_PASSWORD || nStatus == NERR_UserNotFound || nStatus == NERR_PasswordTooShort)
  3073. throw MakeStringException(-1, "An error has occurred while setting password with NetUserSetInfo for %s: %s - %s\n", username, errcode.str(), errmsg.str());
  3074. else
  3075. DBGLOG("An error has occurred while setting password with NetUserSetInfo for %s: %s - %s\n", username, errcode.str(), errmsg.str());
  3076. }
  3077. DBGLOG("Trying changePasswordSSL to change password over regular SSL connection.");
  3078. #endif
  3079. changePasswordSSL(username, newPassword);
  3080. }
  3081. else
  3082. {
  3083. StringBuffer filter;
  3084. filter.append("uid=").append(username);
  3085. char **values = NULL;
  3086. LDAPMessage *message;
  3087. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  3088. Owned<ILdapConnection> lconn = m_connections->getConnection();
  3089. LDAP* ld = lconn.get()->getLd();
  3090. char *attrs[] = {LDAP_NO_ATTRS, NULL};
  3091. CLDAPMessage searchResult;
  3092. 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 );
  3093. if ( rc != LDAP_SUCCESS )
  3094. {
  3095. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), m_ldapconfig->getUserBasedn());
  3096. return false;
  3097. }
  3098. StringBuffer userdn;
  3099. message = LdapFirstEntry( ld, searchResult);
  3100. if(message != NULL)
  3101. {
  3102. char *p = ldap_get_dn(ld, message);
  3103. userdn.append(p);
  3104. ldap_memfree(p);
  3105. }
  3106. char* passwdvalue[] = { (char*)newPassword, NULL };
  3107. LDAPMod pmod =
  3108. {
  3109. LDAP_MOD_REPLACE,
  3110. "userpassword",
  3111. passwdvalue
  3112. };
  3113. LDAPMod* pmods[] = {&pmod, NULL};
  3114. rc = ldap_modify_ext_s(ld, (char*)userdn.str(), pmods, NULL, NULL);
  3115. if (rc == LDAP_SUCCESS )
  3116. DBGLOG("User %s's password has been changed successfully", username);
  3117. else
  3118. {
  3119. StringBuffer errmsg;
  3120. errmsg.appendf("Error changing password for %s - (%d) %s.", username, rc, ldap_err2string( rc ));
  3121. if(rc == LDAP_UNWILLING_TO_PERFORM)
  3122. 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.");
  3123. throw MakeStringExceptionDirect(-1, errmsg.str());
  3124. }
  3125. }
  3126. return true;
  3127. }
  3128. virtual bool getResources(SecResourceType rtype, const char * basedn, const char * prefix, const char * searchstr, IArrayOf<ISecResource>& resources)
  3129. {
  3130. return getResources(nullptr, rtype, basedn, prefix, searchstr, resources);
  3131. }
  3132. virtual bool getResources(LDAP* ld, SecResourceType rtype, const char * basedn, const char * prefix, const char * searchstr, IArrayOf<ISecResource>& resources)
  3133. {
  3134. Owned<ILdapConnection> lconn;
  3135. if (nullptr == ld)
  3136. {
  3137. lconn.setown(m_connections->getConnection());
  3138. ld = lconn.get()->getLd();
  3139. }
  3140. if(rtype == RT_FILE_SCOPE || rtype == RT_WORKUNIT_SCOPE)
  3141. {
  3142. assertex(isEmptyString(searchstr));
  3143. assertex(isEmptyString(prefix));
  3144. getManagedScopeTree(ld, rtype, basedn, resources);
  3145. return true;
  3146. }
  3147. char *attribute;
  3148. LDAPMessage *message;
  3149. StringBuffer basednbuf;
  3150. LdapUtils::normalizeDn(basedn, m_ldapconfig->getBasedn(), basednbuf);
  3151. StringBuffer filter("objectClass=*");
  3152. if(searchstr && *searchstr && strcmp(searchstr, "*") != 0)
  3153. {
  3154. filter.insert(0, "(&(");
  3155. filter.appendf(")(|(%s=*%s*)))", "uNCName", searchstr);
  3156. }
  3157. const char* fldname;
  3158. LdapServerType servertype = m_ldapconfig->getServerType();
  3159. if(servertype == ACTIVE_DIRECTORY && (rtype == RT_DEFAULT || rtype == RT_MODULE || rtype == RT_SERVICE))
  3160. fldname = "name";
  3161. else
  3162. fldname = "ou";
  3163. char *attrs[] = {(char*)fldname, "description", NULL};
  3164. CPagedLDAPSearch pagedSrch(ld, m_ldapconfig->getLdapTimeout(), (char*)basednbuf.str(), LDAP_SCOPE_ONELEVEL, (char*)filter.str(), attrs);
  3165. for (message = pagedSrch.getFirstEntry(); message; message = pagedSrch.getNextEntry())
  3166. {
  3167. CLDAPGetAttributesWrapper atts(ld, message);
  3168. for ( attribute = atts.getFirst(); attribute != NULL; attribute = atts.getNext())
  3169. {
  3170. StringBuffer descbuf;
  3171. StringBuffer curname;
  3172. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  3173. if (vals.hasValues())
  3174. {
  3175. const char* val = vals.queryCharValue(0);
  3176. if(val != NULL)
  3177. {
  3178. if(stricmp(attribute, fldname) == 0)
  3179. {
  3180. curname.append(val);
  3181. }
  3182. else if(stricmp(attribute, "description") == 0)
  3183. {
  3184. descbuf.append(val);
  3185. }
  3186. }
  3187. }
  3188. if(curname.length() == 0)
  3189. continue;
  3190. StringBuffer resourcename;
  3191. if(prefix != NULL && *prefix != '\0')
  3192. resourcename.append(prefix);
  3193. resourcename.append(curname.str());
  3194. CLdapSecResource* resource = new CLdapSecResource(resourcename.str());
  3195. resource->setDescription(descbuf.str());
  3196. resources.append(*resource);
  3197. }
  3198. }
  3199. return true;
  3200. }
  3201. virtual IPropertyTreeIterator* getResourceIterator(SecResourceType rtype, const char * basedn,
  3202. const char* prefix, const char* resourceName, unsigned extraNameFilter)
  3203. {
  3204. IArrayOf<ISecResource> resources;
  3205. getResources(nullptr, rtype, basedn, prefix, resourceName, resources);
  3206. Owned<IPTree> resourceTree = createPTree("Resources");
  3207. ForEachItemIn(i, resources)
  3208. {
  3209. ISecResource& resource = resources.item(i);
  3210. const char* resourceName = resource.getName();
  3211. if (!resourceName || !*resourceName)
  3212. continue;
  3213. if (checkResourceNameExtraFilter(rtype, resourceName, extraNameFilter))
  3214. addResourceTree(resourceName, resource.getDescription(), resourceTree);
  3215. }
  3216. return resourceTree->getElements("*");
  3217. }
  3218. bool checkResourceNameExtraFilter(SecResourceType rtype, const char* name, unsigned extraNameFilter)
  3219. {
  3220. if((rtype == RT_FILE_SCOPE) && (extraNameFilter & RF_RT_FILE_SCOPE_FILE) && strieq(name, "file"))
  3221. return false;
  3222. if((rtype == RT_MODULE) && (extraNameFilter & RF_RT_MODULE_NO_REPOSITORY) && strnicmp(name, "repository.", 11))
  3223. return false;
  3224. return true;
  3225. }
  3226. void addResourceTree(const char* name, const char* desc, IPropertyTree* elements)
  3227. {
  3228. if (!name || !*name)
  3229. {
  3230. DBGLOG("CLdapClient::addResourceTree resource name must be provided");
  3231. return;
  3232. }
  3233. Owned<IPTree> element = createPTree();
  3234. element->addProp(getResourceFieldNames(RFName), name);
  3235. if (desc && *desc)
  3236. element->addProp(getResourceFieldNames(RFDesc), desc);
  3237. elements->addPropTree("Resource", element.getClear());
  3238. }
  3239. ISecItemIterator* getResourcesSorted(SecResourceType rtype, const char * basedn, const char* resourceName, unsigned extraNameFilter,
  3240. ResourceField* sortOrder, const unsigned pageStartFrom, const unsigned pageSize, unsigned* total, __int64* cacheHint)
  3241. {
  3242. class CElementsPager : public CSimpleInterface, implements IElementsPager
  3243. {
  3244. ILdapClient* ldapClient;
  3245. StringAttr sortOrder, basedn, resourceName;
  3246. SecResourceType rtype;
  3247. unsigned extraNameFilter;
  3248. public:
  3249. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  3250. CElementsPager(ILdapClient* _ldapClient, SecResourceType _rtype, const char * _basedn, const char* _resourceName,
  3251. unsigned _extraNameFilter, const char*_sortOrder) : ldapClient(_ldapClient), rtype(_rtype), basedn(_basedn),
  3252. resourceName(_resourceName), extraNameFilter(_extraNameFilter), sortOrder(_sortOrder) { };
  3253. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree>& elements)
  3254. {
  3255. StringArray unknownAttributes;
  3256. Owned<IPropertyTreeIterator> iter = ldapClient->getResourceIterator(rtype, basedn.get(), "", resourceName.get(), extraNameFilter);
  3257. sortElements(iter, sortOrder.get(), NULL, NULL, unknownAttributes, elements);
  3258. return NULL;
  3259. }
  3260. virtual bool allMatchingElementsReceived() { return true; }//For now, ldap always returns all of matched users.
  3261. };
  3262. StringBuffer so;
  3263. if (sortOrder)
  3264. {
  3265. for (unsigned i=0;sortOrder[i]!=RFterm;i++)
  3266. {
  3267. if (so.length())
  3268. so.append(',');
  3269. int fmt = sortOrder[i];
  3270. if (fmt & RFreverse)
  3271. so.append('-');
  3272. if (fmt & RFnocase)
  3273. so.append('?');
  3274. if (fmt & RFnumeric)
  3275. so.append('#');
  3276. so.append(getResourceFieldNames((ResourceField) (fmt&0xff)));
  3277. }
  3278. }
  3279. IArrayOf<IPropertyTree> results;
  3280. Owned<IElementsPager> elementsPager = new CElementsPager(this, rtype, basedn, resourceName, extraNameFilter, so.length()?so.str():NULL);
  3281. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager, pageStartFrom, pageSize, NULL, "", cacheHint, results, total, NULL, false);
  3282. return new CSecItemIterator(results);
  3283. }
  3284. virtual bool getPermissionsArray(const char* basedn, SecResourceType rtype, const char* name, IArrayOf<CPermission>& permissions)
  3285. {
  3286. StringBuffer basednbuf;
  3287. LdapUtils::normalizeDn(basedn, m_ldapconfig->getBasedn(), basednbuf);
  3288. Owned<CSecurityDescriptor> sd = new CSecurityDescriptor(name);
  3289. IArrayOf<CSecurityDescriptor> sdlist;
  3290. sdlist.append(*LINK(sd));
  3291. if(rtype == RT_FILE_SCOPE || rtype == RT_WORKUNIT_SCOPE)
  3292. getSecurityDescriptorsScope(sdlist, basednbuf.str());
  3293. else
  3294. getSecurityDescriptors(sdlist, basednbuf.str());
  3295. m_pp->getPermissionsArray(sd.get(), permissions);
  3296. return true;
  3297. }
  3298. SecResourceType str2RType(const char* rtstr)
  3299. {
  3300. if(isEmptyString(rtstr))
  3301. return RT_DEFAULT;
  3302. else if(strieq(rtstr, "module"))
  3303. return RT_MODULE;
  3304. else if(strieq(rtstr, "service"))
  3305. return RT_SERVICE;
  3306. else if(strieq(rtstr, "file"))
  3307. return RT_FILE_SCOPE;
  3308. else if(strieq(rtstr, "workunit"))
  3309. return RT_WORKUNIT_SCOPE;
  3310. else
  3311. return RT_DEFAULT;
  3312. }
  3313. void addPermissionTree(CPermission& permission, enum ACCOUNT_TYPE_REQ accountType, IPropertyTree* permissionTree)
  3314. {
  3315. const char* accountName = permission.getAccount_name();
  3316. if(isEmptyString(accountName))
  3317. return;
  3318. ACT_TYPE type = permission.getAccount_type();
  3319. if ((accountType != REQ_ANY_ACT) && (type != (ACT_TYPE) accountType))
  3320. return;
  3321. Owned<IPTree> permissionNode = createPTree();
  3322. permissionNode->setProp(getResourcePermissionFieldNames(RPFName), accountName);
  3323. permissionNode->setPropInt(getResourcePermissionFieldNames(RPFType), type);
  3324. permissionNode->setPropInt(getResourcePermissionFieldNames(RPFAllow), permission.getAllows());
  3325. permissionNode->setPropInt(getResourcePermissionFieldNames(RPFDeny), permission.getDenies());
  3326. permissionTree->addPropTree("Permission", permissionNode.getClear());
  3327. }
  3328. virtual IPropertyTreeIterator* getResourcePermissionIterator(const char* name, enum ACCOUNT_TYPE_REQ accountType, const char* baseDN,
  3329. const char* rtype, const char* prefix)
  3330. {
  3331. StringBuffer namebuf(name);
  3332. SecResourceType type = str2RType(rtype);
  3333. if((type == RT_MODULE) && !strieq(name, "repository") && (strnicmp(name, "repository.", 11) != 0))
  3334. namebuf.insert(0, "repository.");
  3335. if(prefix && *prefix)
  3336. namebuf.insert(0, prefix);
  3337. IArrayOf<CPermission> permissions;
  3338. getPermissionsArray(baseDN, type, namebuf.str(), permissions);
  3339. Owned<IPropertyTree> permissionTree = createPTree("Permissions");
  3340. ForEachItemIn(i, permissions)
  3341. addPermissionTree(permissions.item(i), accountType, permissionTree);
  3342. return permissionTree->getElements("*");
  3343. }
  3344. ISecItemIterator* getResourcePermissionsSorted(const char* name, enum ACCOUNT_TYPE_REQ accountType, const char* baseDN, const char* rtype,
  3345. const char* prefix, ResourcePermissionField* sortOrder, const unsigned pageStartFrom, const unsigned pageSize,
  3346. unsigned* total, __int64* cacheHint)
  3347. {
  3348. class CElementsPager : public CSimpleInterface, implements IElementsPager
  3349. {
  3350. ILdapClient* ldapClient;
  3351. StringAttr sortOrder, name, baseDN, rtype, prefix;
  3352. enum ACCOUNT_TYPE_REQ accountType;
  3353. public:
  3354. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  3355. CElementsPager(ILdapClient* _ldapClient, const char* _name, enum ACCOUNT_TYPE_REQ _accountType, const char* _baseDN,
  3356. const char* _rtype, const char* _prefix, const char*_sortOrder) : ldapClient(_ldapClient), name(_name),
  3357. accountType(_accountType), baseDN(_baseDN), rtype(_rtype), prefix(_prefix), sortOrder(_sortOrder) { };
  3358. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree>& elements)
  3359. {
  3360. StringArray unknownAttributes;
  3361. Owned<IPropertyTreeIterator> iter = ldapClient->getResourcePermissionIterator(name.get(), accountType, baseDN.get(), rtype.get(), prefix.get());
  3362. sortElements(iter, sortOrder.get(), NULL, NULL, unknownAttributes, elements);
  3363. return NULL;
  3364. }
  3365. virtual bool allMatchingElementsReceived() { return true; }//For now, ldap always returns all of matched users.
  3366. };
  3367. StringBuffer so;
  3368. if (sortOrder)
  3369. {
  3370. for (unsigned i=0; sortOrder[i]!=RPFterm; i++)
  3371. {
  3372. if (so.length())
  3373. so.append(',');
  3374. int fmt = sortOrder[i];
  3375. if (fmt&RPFreverse)
  3376. so.append('-');
  3377. if (fmt&RPFnocase)
  3378. so.append('?');
  3379. if (fmt&RPFnumeric)
  3380. so.append('#');
  3381. so.append(getResourcePermissionFieldNames((ResourcePermissionField) (fmt&0xff)));
  3382. }
  3383. }
  3384. IArrayOf<IPropertyTree> results;
  3385. Owned<IElementsPager> elementsPager = new CElementsPager(this, name, accountType, baseDN, rtype, prefix, so.length()?so.str():NULL);
  3386. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager, pageStartFrom, pageSize, NULL, "", cacheHint, results, total, NULL, false);
  3387. return new CSecItemIterator(results);
  3388. }
  3389. virtual void getAllGroups(StringArray & groups, StringArray & managedBy, StringArray & descriptions, const char * baseDN=nullptr)
  3390. {
  3391. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  3392. {
  3393. groups.append("Authenticated Users");
  3394. managedBy.append("");
  3395. descriptions.append("");
  3396. if (!m_ldapconfig->isAzureAD())
  3397. {
  3398. groups.append("Administrators");
  3399. managedBy.append("");
  3400. descriptions.append("");
  3401. }
  3402. }
  3403. else
  3404. {
  3405. groups.append("Directory Administrators");
  3406. managedBy.append("");
  3407. descriptions.append("");
  3408. }
  3409. char *attribute;
  3410. LDAPMessage *message;
  3411. StringBuffer filter;
  3412. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  3413. filter.append("objectClass=group");
  3414. else
  3415. filter.append("objectClass=groupofuniquenames");
  3416. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  3417. Owned<ILdapConnection> lconn = m_connections->getConnection();
  3418. LDAP* ld = lconn.get()->getLd();
  3419. char *attrs[] = {"cn", "managedBy", "description", NULL};
  3420. CPagedLDAPSearch pagedSrch(ld, m_ldapconfig->getLdapTimeout(), baseDN==nullptr ? (char*)m_ldapconfig->getGroupBasedn() : (char*)baseDN, LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs);
  3421. for (message = pagedSrch.getFirstEntry(); message; message = pagedSrch.getNextEntry())
  3422. {
  3423. // Go through the search results by checking message types
  3424. CLDAPGetAttributesWrapper atts(ld, message);
  3425. for ( attribute = atts.getFirst();
  3426. attribute != NULL;
  3427. attribute = atts.getNext())
  3428. {
  3429. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  3430. if (!vals.hasValues())
  3431. continue;
  3432. if(stricmp(attribute, "cn") == 0)
  3433. {
  3434. groups.append(vals.queryCharValue(0));
  3435. managedBy.append("");
  3436. descriptions.append("");
  3437. }
  3438. else if(stricmp(attribute, "managedBy") == 0)
  3439. managedBy.replace(vals.queryCharValue(0), groups.length() - 1);
  3440. else if(stricmp(attribute, "description") == 0)
  3441. descriptions.replace(vals.queryCharValue(0), groups.length() - 1);
  3442. }
  3443. }
  3444. }
  3445. virtual IPropertyTreeIterator* getGroupIterator()
  3446. {
  3447. StringArray groupNames, managedBy, descriptions;
  3448. getAllGroups(groupNames, managedBy, descriptions);
  3449. Owned<IPTree> groups = createPTree("Groups");
  3450. ForEachItemIn(i, groupNames)
  3451. addGroupTree(groupNames.item(i), managedBy.item(i), descriptions.item(i), groups);
  3452. return groups->getElements("*");
  3453. }
  3454. void addGroupTree(const char* name, const char* manageBy, const char* desc, IPropertyTree* groups)
  3455. {
  3456. if (!name || !*name)
  3457. {
  3458. DBGLOG("CLdapClient::addGroupTree groupname must be provided");
  3459. return;
  3460. }
  3461. Owned<IPTree> group = createPTree();
  3462. group->addProp(getGroupFieldNames(GFName), name);
  3463. if (manageBy && *manageBy)
  3464. group->addProp(getGroupFieldNames(GFManagedBy), manageBy);
  3465. if (desc && *desc)
  3466. group->addProp(getGroupFieldNames(GFDesc), desc);
  3467. groups->addPropTree("Group", group.getClear());
  3468. }
  3469. ISecItemIterator* getGroupsSorted(GroupField* sortOrder, const unsigned pageStartFrom, const unsigned pageSize, unsigned* total, __int64* cacheHint)
  3470. {
  3471. class CElementsPager : public CSimpleInterface, implements IElementsPager
  3472. {
  3473. ILdapClient* ldapClient;
  3474. StringAttr sortOrder;
  3475. public:
  3476. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  3477. CElementsPager(ILdapClient* _ldapClient, const char*_sortOrder)
  3478. : ldapClient(_ldapClient), sortOrder(_sortOrder) { };
  3479. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree>& elements)
  3480. {
  3481. StringArray unknownAttributes;
  3482. Owned<IPropertyTreeIterator> iter = ldapClient->getGroupIterator();
  3483. sortElements(iter, sortOrder.get(), NULL, NULL, unknownAttributes, elements);
  3484. return NULL;
  3485. }
  3486. virtual bool allMatchingElementsReceived() { return true; }//For now, ldap always returns all of matched users.
  3487. };
  3488. StringBuffer so;
  3489. if (sortOrder)
  3490. {
  3491. for (unsigned i=0;sortOrder[i]!=GFterm;i++)
  3492. {
  3493. if (so.length())
  3494. so.append(',');
  3495. int fmt = sortOrder[i];
  3496. if (fmt & GFreverse)
  3497. so.append('-');
  3498. if (fmt & GFnocase)
  3499. so.append('?');
  3500. if (fmt & GFnumeric)
  3501. so.append('#');
  3502. so.append(getGroupFieldNames((GroupField) (fmt&0xff)));
  3503. }
  3504. }
  3505. IArrayOf<IPropertyTree> results;
  3506. Owned<IElementsPager> elementsPager = new CElementsPager(this, so.length()?so.str():NULL);
  3507. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager, pageStartFrom, pageSize, NULL, "", cacheHint, results, total, NULL, false);
  3508. return new CSecItemIterator(results);
  3509. }
  3510. virtual bool changePermission(CPermissionAction& action)
  3511. {
  3512. StringBuffer basednbuf;
  3513. LdapUtils::normalizeDn(action.m_basedn.str(), m_ldapconfig->getBasedn(), basednbuf);
  3514. Owned<CSecurityDescriptor> sd = new CSecurityDescriptor(action.m_rname.str());
  3515. IArrayOf<CSecurityDescriptor> sdlist;
  3516. sdlist.append(*LINK(sd));
  3517. if(action.m_rtype == RT_FILE_SCOPE || action.m_rtype == RT_WORKUNIT_SCOPE)
  3518. getSecurityDescriptorsScope(sdlist, basednbuf.str());
  3519. else
  3520. getSecurityDescriptors(sdlist, basednbuf.str());
  3521. if(m_ldapconfig->getServerType() != ACTIVE_DIRECTORY)
  3522. {
  3523. StringBuffer act_dn;
  3524. if(action.m_account_type == GROUP_ACT)
  3525. getGroupDN(action.m_account_name.str(), act_dn);
  3526. else
  3527. getUserDN(action.m_account_name.str(), act_dn);
  3528. action.m_account_name.clear().append(act_dn.str());
  3529. }
  3530. Owned<CSecurityDescriptor> newsd = m_pp->changePermission(sd.get(), action);
  3531. StringBuffer normdnbuf;
  3532. LdapServerType servertype = m_ldapconfig->getServerType();
  3533. name2dn(action.m_rtype, action.m_rname.str(), action.m_basedn.str(), normdnbuf);
  3534. char *empty_values[] = { NULL };
  3535. int numberOfSegs = m_pp->sdSegments(newsd.get());
  3536. LDAPMod *attrs[2];
  3537. LDAPMod sd_attr;
  3538. if(newsd->getDescriptor().length() > 0)
  3539. {
  3540. struct berval** sd_values = (struct berval**)alloca(sizeof(struct berval*)*(numberOfSegs+1));
  3541. MemoryBuffer& sdbuf = newsd->getDescriptor();
  3542. // Active Directory acutally has only one segment.
  3543. if(servertype == ACTIVE_DIRECTORY)
  3544. {
  3545. struct berval* sd_val = (struct berval*)alloca(sizeof(struct berval));
  3546. sd_val->bv_len = sdbuf.length();
  3547. sd_val->bv_val = (char*)sdbuf.toByteArray();
  3548. sd_values[0] = sd_val;
  3549. sd_values[1] = NULL;
  3550. sd_attr.mod_type = "nTSecurityDescriptor";
  3551. }
  3552. else
  3553. {
  3554. const char* bbptr = sdbuf.toByteArray();
  3555. const char* bptr = sdbuf.toByteArray();
  3556. int sdbuflen = sdbuf.length();
  3557. int segind;
  3558. for(segind = 0; segind < numberOfSegs; segind++)
  3559. {
  3560. if(bptr - bbptr >= sdbuflen)
  3561. break;
  3562. while(*bptr == '\0' && (bptr - bbptr) < sdbuflen)
  3563. bptr++;
  3564. const char* eptr = bptr;
  3565. while(*eptr != '\0' && (eptr - bbptr) < sdbuflen)
  3566. eptr++;
  3567. struct berval* sd_val = (struct berval*)alloca(sizeof(struct berval));
  3568. sd_val->bv_len = eptr - bptr;
  3569. sd_val->bv_val = (char*)bptr;
  3570. sd_values[segind] = sd_val;
  3571. bptr = eptr + 1;
  3572. }
  3573. sd_values[segind] = NULL;
  3574. sd_attr.mod_type = (char*)m_ldapconfig->getSdFieldName();
  3575. }
  3576. sd_attr.mod_op = LDAP_MOD_REPLACE | LDAP_MOD_BVALUES;
  3577. sd_attr.mod_vals.modv_bvals = sd_values;
  3578. attrs[0] = &sd_attr;
  3579. }
  3580. else
  3581. {
  3582. if(m_ldapconfig->getServerType() == OPEN_LDAP)
  3583. throw MakeStringException(-1, "removing all permissions for openldap is currently not supported");
  3584. sd_attr.mod_op = LDAP_MOD_DELETE;
  3585. sd_attr.mod_type = (char*)m_ldapconfig->getSdFieldName();
  3586. sd_attr.mod_vals.modv_strvals = empty_values;
  3587. attrs[0] = &sd_attr;
  3588. }
  3589. attrs[1] = NULL;
  3590. SDServerCtlWrapper ctlwrapper(m_ldapconfig->isAzureAD());
  3591. Owned<ILdapConnection> lconn = m_connections->getConnection();
  3592. LDAP* ld = lconn.get()->getLd();
  3593. int rc = ldap_modify_ext_s(ld, (char*)normdnbuf.str(), attrs, ctlwrapper.ctls, NULL);
  3594. if ( rc != LDAP_SUCCESS )
  3595. {
  3596. throw MakeStringException(-1, "ldap_modify_ext_s error: %d %s", rc, ldap_err2string( rc ));
  3597. }
  3598. return true;
  3599. }
  3600. virtual void getGroups(const char *user, StringArray& groups)
  3601. {
  3602. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  3603. {
  3604. char *attribute;
  3605. LDAPMessage *message;
  3606. if(user == NULL || strlen(user) == 0)
  3607. {
  3608. DBGLOG("CLdapClient::getGroups username must be provided");
  3609. return;
  3610. }
  3611. StringBuffer filter("sAMAccountName=");
  3612. filter.append(user);
  3613. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  3614. Owned<ILdapConnection> lconn = m_connections->getConnection();
  3615. LDAP* ld = lconn.get()->getLd();
  3616. char *attrs[] = {"memberOf", NULL};
  3617. CLDAPMessage searchResult;
  3618. 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 );
  3619. if ( rc != LDAP_SUCCESS )
  3620. {
  3621. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), m_ldapconfig->getUserBasedn());
  3622. return;
  3623. }
  3624. unsigned entries = ldap_count_entries(ld, searchResult);
  3625. if(entries == 0)
  3626. {
  3627. searchResult.ldapMsgFree();
  3628. 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 );
  3629. if ( rc != LDAP_SUCCESS )
  3630. {
  3631. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), m_ldapconfig->getSysUserBasedn());
  3632. return;
  3633. }
  3634. }
  3635. // Go through the search results by checking message types
  3636. for(message = LdapFirstEntry( ld, searchResult); message != NULL; message = ldap_next_entry(ld, message))
  3637. {
  3638. CLDAPGetAttributesWrapper atts(ld, searchResult);
  3639. for ( attribute = atts.getFirst();
  3640. attribute != NULL;
  3641. attribute = atts.getNext())
  3642. {
  3643. if(0 == stricmp(attribute, "memberOf"))
  3644. {
  3645. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  3646. if (vals.hasValues())
  3647. {
  3648. for (int i = 0; vals.queryBValues()[ i ] != NULL; i++ )
  3649. {
  3650. const char* val = vals.queryCharValue(i);
  3651. char* comma = strchr((char*)val, ',');
  3652. StringBuffer groupname;
  3653. groupname.append(comma - val -3, val+3);
  3654. groups.append(groupname.str());
  3655. }
  3656. }
  3657. }
  3658. }
  3659. }
  3660. }
  3661. else
  3662. {
  3663. StringArray allgroups;
  3664. StringArray allgroupManagedBy;
  3665. StringArray allgroupDescription;
  3666. getAllGroups(allgroups, allgroupManagedBy, allgroupDescription);
  3667. for(unsigned i = 0; i < allgroups.length(); i++)
  3668. {
  3669. const char* grp = allgroups.item(i);
  3670. StringBuffer grpdn, usrdn;
  3671. getUserDN(user, usrdn);
  3672. getGroupDN(grp, grpdn);
  3673. if(userInGroup(usrdn.str(), grpdn.str()))
  3674. {
  3675. groups.append(grp);
  3676. }
  3677. }
  3678. }
  3679. }
  3680. virtual void changeUserGroup(const char* action, const char* username, const char* groupname, const char * groupDN=nullptr)
  3681. {
  3682. StringBuffer userdn, groupdn;
  3683. getUserDN(username, userdn);
  3684. getGroupDN(groupname, groupdn, groupDN);
  3685. // Not needed for Active Directory
  3686. // changeUserMemberOf(action, userdn.str(), groupdn.str());
  3687. changeGroupMember(action, groupdn.str(), userdn.str());
  3688. }
  3689. virtual bool deleteUser(ISecUser* user)
  3690. {
  3691. if(user == NULL)
  3692. {
  3693. DBGLOG("CLdapClient::deleteUser ISecUser must be provided");
  3694. return false;
  3695. }
  3696. const char* username = user->getName();
  3697. if(username == NULL || *username == '\0')
  3698. {
  3699. DBGLOG("CLdapClient::deleteUser username must be provided");
  3700. return false;
  3701. }
  3702. StringBuffer userdn;
  3703. getUserDN(username, userdn);
  3704. Owned<ILdapConnection> lconn = m_connections->getConnection();
  3705. LDAP* ld = lconn.get()->getLd();
  3706. int rc = ldap_delete_ext_s(ld, (char*)userdn.str(), NULL, NULL);
  3707. if ( rc != LDAP_SUCCESS )
  3708. {
  3709. throw MakeStringException(-1, "error deleting user %s: %s", username, ldap_err2string(rc));
  3710. }
  3711. StringArray grps;
  3712. getGroups(username, grps);
  3713. ForEachItemIn(x, grps)
  3714. {
  3715. const char* grp = grps.item(x);
  3716. if(!grp || !*grp)
  3717. continue;
  3718. changeUserGroup("delete", username, grp);
  3719. }
  3720. //Remove tempfile scope for this user
  3721. StringBuffer resName(queryDfsXmlBranchName(DXB_Internal));
  3722. resName.append("::").append(username);
  3723. deleteResource(RT_FILE_SCOPE, resName.str(), m_ldapconfig->getResourceBasedn(RT_FILE_SCOPE));
  3724. return true;
  3725. }
  3726. virtual void addGroup(const char* groupname, const char * groupOwner, const char * groupDesc)
  3727. {
  3728. if(groupname == NULL || *groupname == '\0')
  3729. throw MakeStringException(-1, "Can't add group, groupname is empty");
  3730. addGroup(groupname, groupOwner, groupDesc, m_ldapconfig->getGroupBasedn());
  3731. }
  3732. virtual void addGroup(const char* groupname, const char * groupOwner, const char * groupDesc, const char* basedn)
  3733. {
  3734. if(groupname == NULL || *groupname == '\0')
  3735. {
  3736. DBGLOG("CLdapClient::addGroup groupname must be provided");
  3737. return;
  3738. }
  3739. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  3740. {
  3741. if(stricmp(groupname, "Administrators") == 0)
  3742. throw MakeStringException(-1, "Can't add group %s, it's reserved by the system.", groupname);
  3743. }
  3744. else
  3745. {
  3746. if(stricmp(groupname, "Directory Administrators") == 0)
  3747. throw MakeStringException(-1, "Can't add group %s, it's reserved by the system.", groupname);
  3748. }
  3749. StringBuffer dn;
  3750. dn.append("cn=").append(groupname).append(",").append(basedn);
  3751. char* oc_name;
  3752. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  3753. {
  3754. oc_name = "group";
  3755. }
  3756. else
  3757. {
  3758. oc_name = "groupofuniquenames";
  3759. }
  3760. char *cn_values[] = {(char*)groupname, NULL };
  3761. LDAPMod cn_attr =
  3762. {
  3763. LDAP_MOD_ADD,
  3764. "cn",
  3765. cn_values
  3766. };
  3767. char *oc_values[] = {oc_name, NULL };
  3768. LDAPMod oc_attr =
  3769. {
  3770. LDAP_MOD_ADD,
  3771. "objectClass",
  3772. oc_values
  3773. };
  3774. char *member_values[] = {"", NULL};
  3775. LDAPMod member_attr =
  3776. {
  3777. LDAP_MOD_ADD,
  3778. "uniqueMember",
  3779. member_values
  3780. };
  3781. char *owner_values[] = {(char*)groupOwner, NULL};
  3782. LDAPMod owner_attr =
  3783. {
  3784. LDAP_MOD_ADD,
  3785. "managedBy",
  3786. owner_values
  3787. };
  3788. char *desc_values[] = {(char*)groupDesc, NULL};
  3789. LDAPMod desc_attr =
  3790. {
  3791. LDAP_MOD_ADD,
  3792. "description",
  3793. desc_values
  3794. };
  3795. LDAPMod *attrs[6];
  3796. int ind = 0;
  3797. attrs[ind++] = &cn_attr;
  3798. attrs[ind++] = &oc_attr;
  3799. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  3800. {
  3801. if (groupOwner && *groupOwner)
  3802. attrs[ind++] = &owner_attr;
  3803. }
  3804. if (groupDesc && *groupDesc)
  3805. attrs[ind++] = &desc_attr;
  3806. attrs[ind] = NULL;
  3807. Owned<ILdapConnection> lconn = m_connections->getConnection();
  3808. LDAP* ld = lconn.get()->getLd();
  3809. int rc = ldap_add_ext_s(ld, (char*)dn.str(), attrs, NULL, NULL);
  3810. if ( rc == LDAP_INVALID_SYNTAX && m_ldapconfig->getServerType() == OPEN_LDAP)//Fedora389 does not 'seem' to need this, openLDAP does
  3811. {
  3812. attrs[ind++] = &member_attr;
  3813. attrs[ind] = NULL;
  3814. rc = ldap_add_ext_s(ld, (char*)dn.str(), attrs, NULL, NULL);
  3815. }
  3816. if ( rc != LDAP_SUCCESS)
  3817. {
  3818. if(rc == LDAP_ALREADY_EXISTS)
  3819. {
  3820. throw MakeStringException(-1, "can't add group %s, an LDAP object with this name already exists", groupname);
  3821. }
  3822. else
  3823. {
  3824. DBGLOG("error addGroup %s, ldap_add_ext_s error: %s", groupname, ldap_err2string( rc ));
  3825. throw MakeStringException(-1, "error addGroup %s, ldap_add_ext_s error: %s", groupname, ldap_err2string( rc ));
  3826. }
  3827. }
  3828. }
  3829. virtual void deleteGroup(const char* groupname, const char * groupsDN=nullptr)
  3830. {
  3831. if(groupname == NULL || *groupname == '\0')
  3832. throw MakeStringException(-1, "group name can't be empty");
  3833. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  3834. {
  3835. if(stricmp(groupname, "Administrators") == 0 || stricmp(groupname, "Authenticated Users") == 0)
  3836. throw MakeStringException(-1, "you can't delete Authenticated Users or Administrators group");
  3837. }
  3838. else
  3839. {
  3840. if(stricmp(groupname, "Directory Administrators") == 0)
  3841. throw MakeStringException(-1, "you can't delete Directory Administrators group");
  3842. }
  3843. StringBuffer dn;
  3844. getGroupDN(groupname, dn, groupsDN);
  3845. Owned<ILdapConnection> lconn = m_connections->getConnection();
  3846. LDAP* ld = lconn.get()->getLd();
  3847. int rc = ldap_delete_ext_s(ld, (char*)dn.str(), NULL, NULL);
  3848. if ( rc != LDAP_SUCCESS )
  3849. {
  3850. throw MakeStringException(-1, "error deleting group %s: %s", groupname, ldap_err2string(rc));
  3851. }
  3852. }
  3853. virtual void getGroupMembers(const char* groupname, StringArray & users, const char * groupsDN=nullptr)
  3854. {
  3855. char *attribute;
  3856. LDAPMessage *message;
  3857. if(groupname == NULL || strlen(groupname) == 0)
  3858. throw MakeStringException(-1, "group name can't be empty");
  3859. StringBuffer grpdn;
  3860. getGroupDN(groupname, grpdn, groupsDN);
  3861. StringBuffer filter;
  3862. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  3863. {
  3864. filter.append("distinguishedName=").append(grpdn.str());
  3865. }
  3866. else if(m_ldapconfig->getServerType() == IPLANET)
  3867. {
  3868. filter.append("entrydn=").append(grpdn.str());
  3869. }
  3870. else if(m_ldapconfig->getServerType() == OPEN_LDAP)
  3871. {
  3872. filter.append("cn=").append(groupname);
  3873. }
  3874. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  3875. Owned<ILdapConnection> lconn = m_connections->getConnection();
  3876. LDAP* ld = lconn.get()->getLd();
  3877. const char* memfieldname;
  3878. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  3879. {
  3880. memfieldname = "member";
  3881. }
  3882. else
  3883. {
  3884. memfieldname = "uniquemember";
  3885. }
  3886. char *attrs[] = {(char*)memfieldname, NULL};
  3887. StringBuffer groupbasedn;
  3888. getGroupBaseDN(groupname, groupbasedn, groupsDN);
  3889. CPagedLDAPSearch pagedSrch(ld, m_ldapconfig->getLdapTimeout(), (char*)groupbasedn.str(), LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs);
  3890. for (message = pagedSrch.getFirstEntry(); message; message = pagedSrch.getNextEntry())
  3891. {
  3892. // Go through the search results by checking message types
  3893. CLDAPGetAttributesWrapper atts(ld, message);
  3894. for ( attribute = atts.getFirst();
  3895. attribute != NULL;
  3896. attribute = atts.getNext())
  3897. {
  3898. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  3899. if (vals.hasValues())
  3900. {
  3901. for (int i = 0; vals.queryBValues()[ i ] != NULL; i++ )
  3902. {
  3903. const char* val = vals.queryCharValue(i);
  3904. StringBuffer uid;
  3905. getUidFromDN(ld, val, uid);
  3906. if(uid.length() > 0)
  3907. users.append(uid.str());
  3908. }
  3909. }
  3910. }
  3911. }
  3912. }
  3913. virtual IPropertyTreeIterator* getGroupMemberIterator(const char* groupName)
  3914. {
  3915. StringArray users;
  3916. getGroupMembers(groupName, users);
  3917. Owned<IPropertyTree> usersTree = createPTree("Users");
  3918. ForEachItemIn(i, users)
  3919. {
  3920. const char* usrName = users.item(i);
  3921. if (!usrName || !*usrName)
  3922. continue;
  3923. IUserArray usersInBaseDN;
  3924. retrieveUsers(usrName, usersInBaseDN);
  3925. ForEachItemIn(x, usersInBaseDN)
  3926. {
  3927. ISecUser& usr = usersInBaseDN.item(x);
  3928. const char* usrName0 = usr.getName();
  3929. if(usrName0 && strieq(usrName, usrName0))
  3930. {
  3931. //BUG#41536: The users in the Administrators group are all the users on the whole
  3932. //active directory, while the users in the users list are only the users who are
  3933. //under the "usersBasedn" of this environment. So, we should only return the users
  3934. //who are in the usersBasedn.
  3935. addUserTree(usr, usersTree);
  3936. break;
  3937. }
  3938. }
  3939. }
  3940. return usersTree->getElements("*");
  3941. }
  3942. ISecItemIterator* getGroupMembersSorted(const char* groupName, UserField* sortOrder, const unsigned pageStartFrom, const unsigned pageSize,
  3943. unsigned* total, __int64* cacheHint)
  3944. {
  3945. class CElementsPager : public CSimpleInterface, implements IElementsPager
  3946. {
  3947. ILdapClient* ldapClient;
  3948. StringAttr sortOrder, groupName;
  3949. public:
  3950. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  3951. CElementsPager(ILdapClient* _ldapClient, const char*_groupName, const char*_sortOrder)
  3952. : ldapClient(_ldapClient), groupName(_groupName), sortOrder(_sortOrder) { };
  3953. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree>& elements)
  3954. {
  3955. StringArray unknownAttributes;
  3956. Owned<IPropertyTreeIterator> iter = ldapClient->getGroupMemberIterator(groupName.str());
  3957. sortElements(iter, sortOrder.get(), NULL, NULL, unknownAttributes, elements);
  3958. return NULL;
  3959. }
  3960. virtual bool allMatchingElementsReceived() { return true; }//For now, ldap always returns all of matched users.
  3961. };
  3962. StringBuffer so;
  3963. if (sortOrder)
  3964. {
  3965. for (unsigned i=0;sortOrder[i]!=UFterm;i++)
  3966. {
  3967. if (so.length())
  3968. so.append(',');
  3969. int fmt = sortOrder[i];
  3970. if (fmt&UFreverse)
  3971. so.append('-');
  3972. if (fmt&UFnocase)
  3973. so.append('?');
  3974. if (fmt&UFnumeric)
  3975. so.append('#');
  3976. so.append(getUserFieldNames((UserField) (fmt&0xff)));
  3977. }
  3978. }
  3979. IArrayOf<IPropertyTree> results;
  3980. Owned<IElementsPager> elementsPager = new CElementsPager(this, groupName, so.length()?so.str():NULL);
  3981. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager, pageStartFrom, pageSize, NULL, "", cacheHint, results, total, NULL, false);
  3982. return new CSecItemIterator(results);
  3983. }
  3984. virtual void deleteResource(SecResourceType rtype, const char* name, const char* basedn)
  3985. {
  3986. if(basedn == NULL || *basedn == '\0')
  3987. basedn = m_ldapconfig->getResourceBasedn(rtype);
  3988. StringBuffer dn;
  3989. name2dn(rtype, name, basedn, dn);
  3990. Owned<ILdapConnection> lconn = m_connections->getConnection();
  3991. LDAP* ld = lconn.get()->getLd();
  3992. int rc = ldap_delete_ext_s(ld, (char*)dn.str(), NULL, NULL);
  3993. if ( rc != LDAP_SUCCESS )
  3994. {
  3995. DBGLOG("error deleting %s: %s", dn.str(), ldap_err2string(rc));
  3996. //throw MakeStringException(-1, "error deleting %s: %s", dn.str(), ldap_err2string(rc));
  3997. }
  3998. }
  3999. virtual void renameResource(SecResourceType rtype, const char* oldname, const char* newname, const char* basedn)
  4000. {
  4001. if(oldname == NULL || *oldname == '\0' || newname == NULL || *newname == '\0')
  4002. throw MakeStringException(-1, "please specfiy old and new names");
  4003. if(basedn == NULL || *basedn == '\0')
  4004. basedn = m_ldapconfig->getResourceBasedn(rtype);
  4005. StringBuffer olddn, newrdn;
  4006. name2dn(rtype, oldname, basedn, olddn);
  4007. name2rdn(rtype, newname, newrdn);
  4008. Owned<ILdapConnection> lconn = m_connections->getConnection();
  4009. LDAP* ld = lconn.get()->getLd();
  4010. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY && (rtype == RT_DEFAULT || rtype == RT_MODULE || rtype == RT_SERVICE))
  4011. {
  4012. char* uncname_values[] = {(char*)newname, NULL};
  4013. LDAPMod uncname_attr =
  4014. {
  4015. LDAP_MOD_REPLACE,
  4016. "uNCName",
  4017. uncname_values
  4018. };
  4019. LDAPMod *attrs[2];
  4020. attrs[0] = &uncname_attr;
  4021. attrs[1] = NULL;
  4022. int rc = ldap_modify_ext_s(ld, (char*)olddn.str(), attrs, NULL, NULL);
  4023. if (rc != LDAP_SUCCESS )
  4024. {
  4025. DBGLOG("Error changing unc %s to %s - %s", oldname, newname, ldap_err2string( rc ));
  4026. //throw MakeStringException(-1, "Error changing unc %s to %s - %s", oldname, newname, ldap_err2string( rc ));
  4027. }
  4028. }
  4029. #ifdef _WIN32
  4030. int rc = ldap_rename_ext_s(ld, (char*)olddn.str(), (char*)newrdn.str(), NULL, true, NULL, NULL);
  4031. #else
  4032. int rc = ldap_rename_s(ld, (char*)olddn.str(), (char*)newrdn.str(), NULL, true, NULL, NULL);
  4033. #endif
  4034. if (rc != LDAP_SUCCESS )
  4035. {
  4036. DBGLOG("Error renaming %s to %s - %s", oldname, newname, ldap_err2string( rc ));
  4037. //throw MakeStringException(-1, "Error renaming %s to %s - %s", oldname, newname, ldap_err2string( rc ));
  4038. }
  4039. }
  4040. virtual void copyResource(SecResourceType rtype, const char* oldname, const char* newname, const char* basedn)
  4041. {
  4042. if(oldname == NULL || *oldname == '\0' || newname == NULL || *newname == '\0')
  4043. throw MakeStringException(-1, "please specfiy old and new names");
  4044. if(basedn == NULL || *basedn == '\0')
  4045. basedn = m_ldapconfig->getResourceBasedn(rtype);
  4046. Owned<CSecurityDescriptor> sd = new CSecurityDescriptor(oldname);
  4047. IArrayOf<CSecurityDescriptor> sdlist;
  4048. sdlist.append(*LINK(sd));
  4049. if(rtype == RT_FILE_SCOPE || rtype == RT_WORKUNIT_SCOPE)
  4050. getSecurityDescriptorsScope(sdlist, basedn);
  4051. else
  4052. getSecurityDescriptors(sdlist, basedn);
  4053. if(sd->getDescriptor().length() == 0)
  4054. throw MakeStringException(-1, "error copying %s to %s, %s doesn't exist", oldname, newname, oldname);
  4055. ISecUser* user = NULL;
  4056. CLdapSecResource resource(newname);
  4057. addResource(rtype, *user, &resource, PT_DEFAULT, basedn, sd.get(), false);
  4058. }
  4059. void normalizeDn(const char* dn, StringBuffer& ndn)
  4060. {
  4061. LdapUtils::normalizeDn(dn, m_ldapconfig->getBasedn(), ndn);
  4062. }
  4063. virtual bool isSuperUser(ISecUser* user)
  4064. {
  4065. if(user == NULL || user->getName() == NULL)
  4066. {
  4067. DBGLOG("CLdapClient::isSuperUser Populated ISecUser must be provided");
  4068. return false;
  4069. }
  4070. const char* username = user->getName();
  4071. const char* sysuser = m_ldapconfig->getSysUser();
  4072. if(sysuser != NULL && stricmp(sysuser, username) == 0)
  4073. return true;
  4074. StringBuffer userdn;
  4075. getUserDN(username, userdn);
  4076. return userInGroup(userdn.str(), m_ldapconfig->getAdminGroupDN());
  4077. }
  4078. virtual ILdapConfig* queryConfig()
  4079. {
  4080. return m_ldapconfig.get();
  4081. }
  4082. virtual int countUsers(const char* searchstr, int limit)
  4083. {
  4084. StringBuffer filter;
  4085. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  4086. filter.append("objectClass=User");
  4087. else
  4088. filter.append("objectClass=inetorgperson");
  4089. if(searchstr && *searchstr && strcmp(searchstr, "*") != 0)
  4090. {
  4091. filter.insert(0, "(&(");
  4092. filter.appendf(")(|(%s=*%s*)(%s=*%s*)(%s=*%s*)))", (m_ldapconfig->getServerType()==ACTIVE_DIRECTORY)?"sAMAcccountName":"uid", searchstr, "givenName", searchstr, "sn", searchstr);
  4093. }
  4094. return countEntries(m_ldapconfig->getUserBasedn(), filter.str(), limit);
  4095. }
  4096. virtual int countResources(const char* basedn, const char* searchstr, int limit)
  4097. {
  4098. StringBuffer filter;
  4099. filter.append("objectClass=*");
  4100. if(searchstr && *searchstr && strcmp(searchstr, "*") != 0)
  4101. {
  4102. filter.insert(0, "(&(");
  4103. filter.appendf(")(|(%s=*%s*)))", "uNCName", searchstr);
  4104. }
  4105. return countEntries(basedn, filter.str(), limit);
  4106. }
  4107. virtual int countEntries(const char* basedn, const char* filter, int limit)
  4108. {
  4109. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  4110. Owned<ILdapConnection> lconn = m_connections->getConnection();
  4111. LDAP* ld = lconn.get()->getLd();
  4112. char *attrs[] = { LDAP_NO_ATTRS, NULL };
  4113. CPagedLDAPSearch pagedSrch(ld, m_ldapconfig->getLdapTimeout(), (char*)basedn, LDAP_SCOPE_SUBTREE, (char*)filter, attrs);
  4114. int entries = pagedSrch.countEntries();
  4115. return entries;
  4116. }
  4117. virtual const char* getPasswordStorageScheme()
  4118. {
  4119. if(m_pwscheme.length() == 0)
  4120. {
  4121. if(m_ldapconfig->getServerType() == IPLANET)
  4122. {
  4123. Owned<ILdapConnection> lconn = m_connections->getConnection();
  4124. LDAP* ld = lconn.get()->getLd();
  4125. char* pw_attrs[] = {"nsslapd-rootpwstoragescheme", NULL};
  4126. CLDAPMessage msg;
  4127. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  4128. int err = ldap_search_ext_s(ld, "cn=config", LDAP_SCOPE_BASE, "objectClass=*", pw_attrs, false, NULL, NULL, &timeOut, LDAP_NO_LIMIT, &msg.msg);
  4129. if(err != LDAP_SUCCESS)
  4130. {
  4131. DBGLOG("ldap_search_ext_s error: %s", ldap_err2string( err ));
  4132. return NULL;
  4133. }
  4134. LDAPMessage* entry = LdapFirstEntry(ld, msg);
  4135. if(entry != NULL)
  4136. {
  4137. CLDAPGetValuesLenWrapper vals(ld, entry, "nsslapd-rootpwstoragescheme");
  4138. if (vals.hasValues())
  4139. m_pwscheme.append(vals.queryCharValue(0));
  4140. }
  4141. ldap_msgfree(msg);
  4142. }
  4143. }
  4144. if(m_pwscheme.length() == 0)
  4145. return NULL;
  4146. else
  4147. return m_pwscheme.str();
  4148. }
  4149. private:
  4150. class SDServerCtlWrapper
  4151. {
  4152. public:
  4153. LDAPControl **ctls = nullptr;
  4154. LDAPControl* ctl = nullptr;
  4155. StringBuffer oidbuf, valbuf;
  4156. SDServerCtlWrapper(bool isAzureAD)
  4157. {
  4158. if (isAzureAD)
  4159. {
  4160. oidbuf.append(AAD_LDAP_SERVER_SD_FLAGS_OID);
  4161. //48,3,2 are for ber-ans.1 encoding
  4162. //1 is the length of the data
  4163. //7 is the data, which is bit wise OR of owner info (0x1), group info (0x2) and discretionary ACL (0x4)
  4164. valbuf.appendf("%c%c%c%c%c", 48, 3, 2, 1, 7);
  4165. ctl = new LDAPControl;
  4166. ctl->ldctl_oid = (char*)oidbuf.str();
  4167. ctl->ldctl_value.bv_len = valbuf.length();
  4168. ctl->ldctl_value.bv_val = (char*)valbuf.str();
  4169. ctls = new LDAPControl*[2];
  4170. ctls[0] = ctl;
  4171. ctls[1] = nullptr;
  4172. }
  4173. }
  4174. ~SDServerCtlWrapper()
  4175. {
  4176. if (ctl)
  4177. delete ctl;
  4178. if (ctls)
  4179. delete []ctls;
  4180. }
  4181. };
  4182. virtual void addDC(const char* dc)
  4183. {
  4184. if(dc == NULL || *dc == '\0')
  4185. {
  4186. DBGLOG("CLdapClient::addDC dc must be provided");
  4187. return;
  4188. }
  4189. StringBuffer dcname;
  4190. LdapUtils::getName(dc, dcname);
  4191. char *dc_values[] = {(char*)dcname.str(), NULL };
  4192. LDAPMod dc_attr =
  4193. {
  4194. LDAP_MOD_ADD,
  4195. "dc",
  4196. dc_values
  4197. };
  4198. char *o_values[] = {(char*)dcname.str(), NULL };
  4199. LDAPMod o_attr =
  4200. {
  4201. LDAP_MOD_ADD,
  4202. "o",
  4203. o_values
  4204. };
  4205. char *oc_values[] = {"organization", "dcObject", NULL };
  4206. LDAPMod oc_attr =
  4207. {
  4208. LDAP_MOD_ADD,
  4209. "objectClass",
  4210. oc_values
  4211. };
  4212. LDAPMod *attrs[4];
  4213. attrs[0] = &oc_attr;
  4214. attrs[1] = &o_attr;
  4215. attrs[2] = &dc_attr;
  4216. attrs[3] = NULL;
  4217. Owned<ILdapConnection> lconn = m_connections->getConnection();
  4218. LDAP* ld = lconn.get()->getLd();
  4219. int rc = ldap_add_ext_s(ld, (char*)dc, attrs, NULL, NULL);
  4220. if ( rc != LDAP_SUCCESS )
  4221. {
  4222. if(rc == LDAP_ALREADY_EXISTS)
  4223. {
  4224. throw MakeStringException(-1, "can't add dc %s, an LDAP object with this name already exists", dc);
  4225. }
  4226. else
  4227. {
  4228. DBGLOG("error addDC %s, ldap_add_ext_s error: 0x%0x %s", dc, rc, ldap_err2string( rc ));
  4229. throw MakeStringException(-1, "error addDC %s, ldap_add_ext_s error: %s", dc, ldap_err2string( rc ));
  4230. }
  4231. }
  4232. }
  4233. virtual void getUserDN(const char* username, StringBuffer& userdn)
  4234. {
  4235. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  4236. {
  4237. StringBuffer filter;
  4238. filter.append("sAMAccountName=");
  4239. filter.append(username);
  4240. char *attribute;
  4241. LDAPMessage *message;
  4242. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  4243. char *dn_fieldname;
  4244. dn_fieldname = "distinguishedName";
  4245. Owned<ILdapConnection> lconn = m_connections->getConnection();
  4246. LDAP* ld = lconn.get()->getLd();
  4247. char *attrs[] = {dn_fieldname, NULL};
  4248. CLDAPMessage searchResult;
  4249. 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 );
  4250. if ( rc != LDAP_SUCCESS )
  4251. {
  4252. throw MakeStringException(-1, "ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), m_ldapconfig->getUserBasedn());
  4253. }
  4254. unsigned entries = ldap_count_entries(ld, searchResult);
  4255. if(entries == 0)
  4256. {
  4257. searchResult.ldapMsgFree();
  4258. 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 );
  4259. if ( rc != LDAP_SUCCESS )
  4260. {
  4261. throw MakeStringException(-1, "ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), m_ldapconfig->getSysUserBasedn());
  4262. }
  4263. }
  4264. message = LdapFirstEntry( ld, searchResult);
  4265. if(message != NULL)
  4266. {
  4267. CLDAPGetAttributesWrapper atts(ld, searchResult);
  4268. attribute = atts.getFirst();
  4269. if(attribute != NULL)
  4270. {
  4271. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  4272. if (vals.hasValues())
  4273. userdn.append(vals.queryCharValue(0));
  4274. }
  4275. }
  4276. if(userdn.length() == 0)
  4277. throw MakeStringException(-1, "user %s can't be found", username);
  4278. }
  4279. else
  4280. {
  4281. if(stricmp(username, "anyone") == 0)
  4282. userdn.append(username);
  4283. else
  4284. userdn.append("uid=").append(username).append(",").append(m_ldapconfig->getUserBasedn());
  4285. }
  4286. }
  4287. virtual void getUidFromDN(LDAP* ld, const char* dn, StringBuffer& uid)
  4288. {
  4289. if(dn == NULL || *dn == '\0')
  4290. {
  4291. DBGLOG("CLdapClient::getUidFromDN dn must be provided");
  4292. return;
  4293. }
  4294. if(m_ldapconfig->getServerType() != ACTIVE_DIRECTORY)
  4295. {
  4296. if (strncmp(dn,"uid=",4))//Fedora389 returns "cn=Directory Administrators"
  4297. return;
  4298. const char* comma = strchr(dn, ',');
  4299. // DN is in the format of "uid=uuu,ou=ooo,dc=dd"
  4300. uid.append(comma - dn - 4, dn + 4);
  4301. return;
  4302. }
  4303. StringBuffer filter;
  4304. filter.append("distinguishedName=").append(dn);
  4305. filter.replaceString("\\", "\\5c");//Replace special characters with valid UTF-8 string (see valueencoding rule in RFC 4515)
  4306. filter.replaceString("*", "\\2a");
  4307. filter.replaceString("(", "\\28");
  4308. filter.replaceString(")", "\\29");
  4309. char *attribute;
  4310. LDAPMessage *message;
  4311. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  4312. char *uid_fieldname = "sAMAccountName";
  4313. char *attrs[] = {uid_fieldname, NULL};
  4314. CLDAPMessage searchResult;
  4315. 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 );
  4316. if ( rc != LDAP_SUCCESS )
  4317. {
  4318. throw MakeStringException(-1, "ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), m_ldapconfig->getUserBasedn());
  4319. }
  4320. message = LdapFirstEntry( ld, searchResult);
  4321. if(message != NULL)
  4322. {
  4323. CLDAPGetAttributesWrapper atts(ld, searchResult);
  4324. attribute = atts.getFirst();
  4325. if(attribute != NULL)
  4326. {
  4327. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  4328. if (vals.hasValues())
  4329. uid.append(vals.queryCharValue(0));
  4330. }
  4331. }
  4332. }
  4333. virtual void getGroupDN(const char* groupname, StringBuffer& groupdn, const char * groupBaseDN=nullptr)
  4334. {
  4335. if(groupname == NULL)
  4336. {
  4337. DBGLOG("CLdapClient::getGroupDN groupname must be provided");
  4338. return;
  4339. }
  4340. LdapServerType stype = m_ldapconfig->getServerType();
  4341. groupdn.append("cn=").append(groupname).append(",");
  4342. if(stype == ACTIVE_DIRECTORY && stricmp(groupname, "Administrators") == 0)
  4343. {
  4344. groupdn.append("cn=Builtin,").append(m_ldapconfig->getBasedn());
  4345. }
  4346. else if((stype == IPLANET || stype == OPEN_LDAP) && stricmp(groupname, "Directory Administrators") == 0)
  4347. {
  4348. groupdn.append(m_ldapconfig->getBasedn());
  4349. }
  4350. else
  4351. {
  4352. groupdn.append(groupBaseDN == nullptr ? m_ldapconfig->getGroupBasedn() : groupBaseDN);
  4353. }
  4354. }
  4355. virtual void getGroupBaseDN(const char* groupname, StringBuffer& groupbasedn, const char * groupBaseDN=nullptr)
  4356. {
  4357. if(groupname == NULL)
  4358. {
  4359. DBGLOG("CLdapClient::getGroupBaseDN groupname must be provided");
  4360. return;
  4361. }
  4362. LdapServerType stype = m_ldapconfig->getServerType();
  4363. if(stype == ACTIVE_DIRECTORY && stricmp(groupname, "Administrators") == 0)
  4364. {
  4365. groupbasedn.append("cn=Builtin,").append(m_ldapconfig->getBasedn());
  4366. }
  4367. else if((stype == IPLANET || stype == OPEN_LDAP) && stricmp(groupname, "Directory Administrators") == 0)
  4368. {
  4369. groupbasedn.append(m_ldapconfig->getBasedn());
  4370. }
  4371. else
  4372. {
  4373. groupbasedn.append(groupBaseDN==nullptr ? m_ldapconfig->getGroupBasedn() : groupBaseDN);
  4374. }
  4375. }
  4376. virtual void changeUserMemberOf(const char* action, const char* userdn, const char* groupdn)
  4377. {
  4378. char *grp_values[] = {(char*)groupdn, NULL};
  4379. LDAPMod grp_attr = {
  4380. (action != NULL && stricmp(action, "delete") == 0)?LDAP_MOD_DELETE:LDAP_MOD_ADD,
  4381. "memberOf",
  4382. grp_values
  4383. };
  4384. LDAPMod *grp_attrs[2];
  4385. grp_attrs[0] = &grp_attr;
  4386. grp_attrs[1] = NULL;
  4387. Owned<ILdapConnection> lconn = m_connections->getConnection();
  4388. LDAP* ld = lconn.get()->getLd();
  4389. int rc = ldap_modify_ext_s(ld, (char*)userdn, grp_attrs, NULL, NULL);
  4390. if ( rc != LDAP_SUCCESS )
  4391. {
  4392. throw MakeStringException(-1, "error changing group for user %s, ldap_modify_ext_s error: %s", userdn, ldap_err2string( rc ));
  4393. }
  4394. }
  4395. virtual void changeGroupMember(const char* action, const char* groupdn, const char* userdn)
  4396. {
  4397. Owned<ILdapConnection> lconn = m_connections->getConnection();
  4398. LDAP* ld = lconn.get()->getLd();
  4399. const char* memberfieldname;
  4400. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  4401. {
  4402. memberfieldname = "member";
  4403. }
  4404. else
  4405. {
  4406. memberfieldname = "uniquemember";
  4407. }
  4408. char *member_values[] = {(char*)userdn, NULL};
  4409. LDAPMod member_attr = {
  4410. (action != NULL && stricmp(action, "delete") == 0)?LDAP_MOD_DELETE:LDAP_MOD_ADD,
  4411. (char*)memberfieldname,
  4412. member_values
  4413. };
  4414. LDAPMod *member_attrs[2];
  4415. member_attrs[0] = &member_attr;
  4416. member_attrs[1] = NULL;
  4417. int rc = ldap_modify_ext_s(ld, (char*)groupdn, member_attrs, NULL, NULL);
  4418. if ( rc != LDAP_SUCCESS )
  4419. {
  4420. if (action != NULL && stricmp(action, "delete") == 0)
  4421. throw MakeStringException(-1, "Failed in deleting member from group: ldap_modify_ext_s error: %s; userdn: %s; groupdn: %s", ldap_err2string( rc ), userdn, groupdn);
  4422. else
  4423. throw MakeStringException(-1, "Failed in adding member to group, ldap_modify_ext_s error: %s; userdn: %s; groupdn: %s", ldap_err2string( rc ), userdn, groupdn);
  4424. }
  4425. }
  4426. void ConvertCToW(unsigned short* pszDest, const char * pszSrc)
  4427. {
  4428. unsigned i = 0;
  4429. for(i = 0; i < strlen(pszSrc); i++)
  4430. pszDest[i] = (unsigned short) pszSrc[i];
  4431. pszDest[i] = (unsigned short)'\0';
  4432. }
  4433. virtual bool authorizeScope(ISecUser& user, IArrayOf<ISecResource>& resources, const char* basedn)
  4434. {
  4435. IArrayOf<CSecurityDescriptor> sdlist;
  4436. std::set<const char*, ltstr> scopeset;
  4437. ForEachItemIn(x, resources)
  4438. {
  4439. ISecResource& res = resources.item(x);
  4440. const char* resourcename = res.getName();
  4441. if(resourcename == NULL || *resourcename == '\0')
  4442. continue;
  4443. // Add one extra Volume type SecurityDescriptor for each resource for ActiveDirectory.
  4444. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  4445. {
  4446. CSecurityDescriptor* sd = new CSecurityDescriptor(resourcename);
  4447. sd->setObjectClass("Volume");
  4448. sdlist.append(*sd);
  4449. }
  4450. scopeset.insert(resourcename);
  4451. int len = strlen(resourcename);
  4452. const char* curptr = resourcename + len - 1;
  4453. while(curptr > resourcename)
  4454. {
  4455. while(curptr > resourcename && *curptr != ':')
  4456. curptr--;
  4457. bool foundcolon=false;
  4458. while(curptr >resourcename && *curptr == ':')
  4459. {
  4460. curptr--;
  4461. foundcolon = true;
  4462. }
  4463. if(curptr > resourcename || foundcolon)
  4464. {
  4465. int curlen = curptr - resourcename + 1;
  4466. char* curscope = (char*)alloca(curlen + 1);
  4467. strncpy(curscope, resourcename, curlen);
  4468. curscope[curlen] = 0;
  4469. scopeset.insert(curscope);
  4470. }
  4471. }
  4472. }
  4473. if(scopeset.size() == 0)
  4474. return true;
  4475. std::set<const char*, ltstr>::iterator iter;
  4476. for(iter = scopeset.begin(); iter != scopeset.end(); iter++)
  4477. {
  4478. const char* curscope = *iter;
  4479. CSecurityDescriptor* sd = new CSecurityDescriptor(*iter);
  4480. sd->setObjectClass("organizationalUnit");
  4481. sdlist.append(*sd);
  4482. }
  4483. getSecurityDescriptorsScope(sdlist, basedn);
  4484. IArrayOf<CSecurityDescriptor> matched_sdlist;
  4485. ForEachItemIn(y, resources)
  4486. {
  4487. ISecResource& res = resources.item(y);
  4488. const char* rname = res.getName();
  4489. if(rname == NULL || *rname == '\0')
  4490. throw MakeStringException(-1, "resource name can't be empty inside authorizeScope");
  4491. CSecurityDescriptor* matchedsd = NULL;
  4492. ForEachItemIn(z, sdlist)
  4493. {
  4494. CSecurityDescriptor& sd = sdlist.item(z);
  4495. const char* sdname = sd.getName();
  4496. if(sdname == NULL || *sdname == '\0')
  4497. continue;
  4498. if(strncmp(sdname, rname, strlen(sdname)) == 0
  4499. && (matchedsd == NULL
  4500. || ((matchedsd->getDescriptor().length() == 0 && sd.getDescriptor().length() > 0)
  4501. || (sd.getDescriptor().length() > 0 && strlen(sdname) > strlen(matchedsd->getName())))))
  4502. matchedsd = &sd;
  4503. }
  4504. if(matchedsd != NULL)
  4505. matched_sdlist.append(*LINK(matchedsd));
  4506. else
  4507. matched_sdlist.append(*(new CSecurityDescriptor(rname)));
  4508. }
  4509. bool ok = false;
  4510. if(m_pp != NULL)
  4511. ok = m_pp->getPermissions(user, matched_sdlist, resources);
  4512. return ok;
  4513. }
  4514. virtual void getSecurityDescriptors(SecResourceType rtype, IArrayOf<CSecurityDescriptor>& sdlist)
  4515. {
  4516. int len = sdlist.length();
  4517. if(len == 0)
  4518. {
  4519. DBGLOG("CLdapClient::getSecurityDescriptors sdlist cannot be empty");
  4520. return;
  4521. }
  4522. const char* rbasedn = m_ldapconfig->getResourceBasedn(rtype);
  4523. if(rbasedn == NULL || *rbasedn == '\0')
  4524. {
  4525. DBGLOG("corresponding resource basedn is not defined");
  4526. return;
  4527. }
  4528. std::map<std::string, IArrayOf<CSecurityDescriptor>*> sdmap;
  4529. for(int i = 0; i < len; i++)
  4530. {
  4531. CSecurityDescriptor& sd = sdlist.item(i);
  4532. const char* relativeBasedn = sd.getRelativeBasedn();
  4533. StringBuffer basedn;
  4534. if(relativeBasedn != NULL)
  4535. basedn.append(relativeBasedn).append(",");
  4536. basedn.append(rbasedn);
  4537. std::map<std::string, IArrayOf<CSecurityDescriptor>*>::iterator sdit = sdmap.find(basedn.str());
  4538. if(sdit == sdmap.end())
  4539. {
  4540. IArrayOf<CSecurityDescriptor>* newlist = new IArrayOf<CSecurityDescriptor>;
  4541. newlist->append(*LINK(&sd));
  4542. sdmap[basedn.str()] = newlist;
  4543. }
  4544. else
  4545. {
  4546. (*sdit).second->append(*LINK(&sd));
  4547. }
  4548. }
  4549. for(std::map<std::string, IArrayOf<CSecurityDescriptor>*>::iterator cur = sdmap.begin(); cur != sdmap.end(); cur++)
  4550. {
  4551. getSecurityDescriptors(*((*cur).second), (*cur).first.c_str());
  4552. delete (*cur).second;
  4553. }
  4554. }
  4555. virtual void getSecurityDescriptors(IArrayOf<CSecurityDescriptor>& sdlist, const char* basedn)
  4556. {
  4557. char *attribute;
  4558. CLDAPGetValuesLenWrapper valsLen;
  4559. LDAPMessage *message;
  4560. int i;
  4561. const char *id_fieldname;
  4562. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  4563. {
  4564. id_fieldname = "name";
  4565. }
  4566. else
  4567. {
  4568. id_fieldname = "ou";
  4569. }
  4570. const char *des_fieldname = m_ldapconfig->getSdFieldName();
  4571. int len = sdlist.length();
  4572. if(len == 0)
  4573. {
  4574. DBGLOG("CLdapClient::getSecurityDescriptors2 sdlist cannot be empty");
  4575. return;
  4576. }
  4577. StringBuffer filter;
  4578. filter.append("(|");
  4579. for(i = 0; i < len; i++)
  4580. {
  4581. CSecurityDescriptor& sd = sdlist.item(i);
  4582. StringBuffer namebuf;
  4583. namebuf.append(sd.getName());
  4584. namebuf.trim();
  4585. if(namebuf.length() > 0)
  4586. {
  4587. filter.append("(").append(id_fieldname).append("=").append(namebuf.str()).append(")");;
  4588. }
  4589. }
  4590. filter.append(")");
  4591. SDServerCtlWrapper ctlwrapper(m_ldapconfig->isAzureAD());
  4592. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  4593. char* attrs[] = {(char*)id_fieldname, (char*)des_fieldname, NULL};
  4594. Owned<ILdapConnection> lconn = m_connections->getConnection();
  4595. LDAP* ld = lconn.get()->getLd();
  4596. CLDAPMessage searchResult;
  4597. 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 */
  4598. if ( rc != LDAP_SUCCESS )
  4599. {
  4600. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), basedn);
  4601. return;
  4602. }
  4603. // Go through the search results by checking message types
  4604. for(message = LdapFirstEntry(ld, searchResult); message != NULL; message = ldap_next_entry(ld, message))
  4605. {
  4606. StringBuffer resourcename;
  4607. CLDAPGetAttributesWrapper atts(ld, searchResult);
  4608. for ( attribute = atts.getFirst();
  4609. attribute != NULL;
  4610. attribute = atts.getNext())
  4611. {
  4612. if(stricmp(attribute, id_fieldname) == 0)
  4613. {
  4614. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  4615. if (vals.hasValues())
  4616. resourcename.append(vals.queryCharValue(0));
  4617. }
  4618. else if(stricmp(attribute, des_fieldname) == 0)
  4619. {
  4620. valsLen.retrieveBValues(ld, message, attribute);
  4621. }
  4622. }
  4623. for(i = 0; i < len; i++)
  4624. {
  4625. CSecurityDescriptor& sd = sdlist.item(i);
  4626. if(resourcename.length() > 0 && stricmp(resourcename.str(), sd.getName()) == 0)
  4627. {
  4628. if (valsLen.hasValues())
  4629. {
  4630. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  4631. {
  4632. struct berval* val = valsLen.queryBValues()[0];
  4633. if(val != NULL)
  4634. {
  4635. CSecurityDescriptor& sd = sdlist.item(i);
  4636. sd.setDescriptor(val->bv_len, val->bv_val);
  4637. }
  4638. }
  4639. else
  4640. {
  4641. MemoryBuffer allvals;
  4642. int valseq = 0;
  4643. struct berval* val = valsLen.queryBValues()[valseq++];
  4644. while(val != NULL)
  4645. {
  4646. if(val->bv_len > 0)
  4647. {
  4648. allvals.append(val->bv_len, val->bv_val);
  4649. allvals.append('\0'); // my separator between ACIs
  4650. }
  4651. val = valsLen.queryBValues()[valseq++];
  4652. }
  4653. if(allvals.length() > 0)
  4654. {
  4655. CSecurityDescriptor& sd = sdlist.item(i);
  4656. sd.setDescriptor(allvals.length(), (void*)allvals.toByteArray());
  4657. }
  4658. }
  4659. }
  4660. break;
  4661. }
  4662. }
  4663. }
  4664. }
  4665. virtual void getSecurityDescriptorsScope(IArrayOf<CSecurityDescriptor>& sdlist, const char* basedn)
  4666. {
  4667. char *attribute;
  4668. CLDAPGetValuesLenWrapper valsLen;
  4669. LDAPMessage *message;
  4670. int i;
  4671. int len = sdlist.length();
  4672. if(len == 0)
  4673. {
  4674. DBGLOG("CLdapClient::getSecurityDescriptorsScope sdlist cannot be empty");
  4675. return;
  4676. }
  4677. LdapServerType servertype = m_ldapconfig->getServerType();
  4678. char *sd_fieldname = (char*)m_ldapconfig->getSdFieldName();
  4679. StringBuffer filter;
  4680. filter.append("(|");
  4681. for(i = 0; i < len; i++)
  4682. {
  4683. CSecurityDescriptor& sd = sdlist.item(i);
  4684. StringBuffer namebuf;
  4685. namebuf.append(sd.getName());
  4686. namebuf.trim();
  4687. if(namebuf.length() > 0)
  4688. {
  4689. const char* resourcename = namebuf.str();
  4690. int len = namebuf.length();
  4691. const char* curptr = resourcename + len - 1;
  4692. StringBuffer dn, cn;
  4693. bool isleaf = true;
  4694. while(curptr > resourcename)
  4695. {
  4696. const char* lastptr = curptr;
  4697. while(curptr > resourcename && *curptr != ':')
  4698. curptr--;
  4699. int curlen;
  4700. const char* curscope;
  4701. if(*curptr == ':')
  4702. {
  4703. curlen = lastptr - curptr;
  4704. curscope = curptr + 1;
  4705. }
  4706. else
  4707. {
  4708. curlen = lastptr - curptr + 1;
  4709. curscope = curptr;
  4710. }
  4711. if(isleaf && (sd.getObjectClass() != NULL) && (stricmp(sd.getObjectClass(), "Volume") == 0))
  4712. {
  4713. cn.append(curlen, curscope);
  4714. dn.append("cn=").append(curlen, curscope).append(",");
  4715. }
  4716. else
  4717. {
  4718. cn.append(curlen, curscope);
  4719. dn.append("ou=").append(curlen, curscope).append(",");
  4720. }
  4721. isleaf = false;
  4722. if (curptr == resourcename) //handle a single char as the top scope, such as x::abc
  4723. break;
  4724. while(curptr >resourcename && *curptr == ':')
  4725. curptr--;
  4726. if (curptr == resourcename && *curptr != ':') //handle a single char as the top scope, such as x::abc
  4727. {
  4728. dn.append("ou=").append(1, curptr).append(",");
  4729. }
  4730. }
  4731. dn.append(basedn);
  4732. if(servertype == ACTIVE_DIRECTORY)
  4733. {
  4734. filter.append("(distinguishedName=").append(dn.str()).append(")");
  4735. }
  4736. else if(servertype == IPLANET)
  4737. {
  4738. filter.append("(entrydn=").append(dn.str()).append(")");
  4739. }
  4740. else if(servertype == OPEN_LDAP)
  4741. {
  4742. filter.append("(ou=").append(cn.str()).append(")");
  4743. }
  4744. sd.setDn(dn.str());
  4745. }
  4746. }
  4747. filter.append(")");
  4748. SDServerCtlWrapper ctlwrapper(m_ldapconfig->isAzureAD());
  4749. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  4750. char* attrs[] = {sd_fieldname, NULL};
  4751. Owned<ILdapConnection> lconn = m_connections->getConnection();
  4752. LDAP* ld = lconn.get()->getLd();
  4753. CLDAPMessage searchResult;
  4754. 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 */
  4755. if ( rc != LDAP_SUCCESS )
  4756. {
  4757. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), basedn);
  4758. return;
  4759. }
  4760. // Go through the search results by checking message types
  4761. for(message = LdapFirstEntry(ld, searchResult); message != NULL; message = ldap_next_entry(ld, message))
  4762. {
  4763. StringBuffer dn;
  4764. char *p = ldap_get_dn(ld, message);
  4765. dn.append(p);
  4766. ldap_memfree(p);
  4767. CLDAPGetAttributesWrapper atts(ld, searchResult);
  4768. for ( attribute = atts.getFirst();
  4769. attribute != NULL;
  4770. attribute = atts.getNext())
  4771. {
  4772. if(stricmp(attribute, sd_fieldname) == 0)
  4773. {
  4774. valsLen.retrieveBValues(ld, message, attribute);
  4775. }
  4776. }
  4777. for(i = 0; i < len; i++)
  4778. {
  4779. CSecurityDescriptor& sd = sdlist.item(i);
  4780. if(dn.length() > 0 && stricmp(dn.str(), sd.getDn()) == 0)
  4781. {
  4782. if (valsLen.hasValues())
  4783. {
  4784. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  4785. {
  4786. struct berval* val = valsLen.queryBValues()[0];
  4787. if(val != NULL)
  4788. {
  4789. CSecurityDescriptor& sd = sdlist.item(i);
  4790. sd.setDescriptor(val->bv_len, val->bv_val);
  4791. }
  4792. }
  4793. else
  4794. {
  4795. MemoryBuffer allvals;
  4796. int valseq = 0;
  4797. struct berval* val = valsLen.queryBValues()[valseq++];
  4798. while(val != NULL)
  4799. {
  4800. if(val->bv_len > 0)
  4801. {
  4802. allvals.append(val->bv_len, val->bv_val);
  4803. allvals.append('\0'); // my separator between ACIs
  4804. }
  4805. val = valsLen.queryBValues()[valseq++];
  4806. }
  4807. if(allvals.length() > 0)
  4808. {
  4809. CSecurityDescriptor& sd = sdlist.item(i);
  4810. sd.setDescriptor(allvals.length(), (void*)allvals.toByteArray());
  4811. }
  4812. }
  4813. }
  4814. break;
  4815. }
  4816. }
  4817. }
  4818. }
  4819. virtual const bool organizationalUnitExists(const char * ou) const
  4820. {
  4821. Owned<ILdapConnection> lconn = m_connections->getConnection();
  4822. LDAP* sys_ld = lconn.get()->getLd();
  4823. char* attrs[] = {"ou", NULL};
  4824. CLDAPMessage searchResult;
  4825. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  4826. 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);
  4827. return rc == LDAP_SUCCESS;
  4828. }
  4829. virtual void createLdapBasedn(ISecUser* user, const char* basedn, SecPermissionType ptype)
  4830. {
  4831. if(basedn == NULL || basedn[0] == '\0')
  4832. {
  4833. DBGLOG("CLdapClient::createLdapBasedn basedn must be provided");
  4834. return;
  4835. }
  4836. const char* ptr = strstr(basedn, "ou=");
  4837. if(ptr == NULL)
  4838. {
  4839. DBGLOG("CLdapClient::createLdapBasedn OU= missing from basedn");
  4840. return;
  4841. }
  4842. ptr += 3;
  4843. StringBuffer oubuf;
  4844. const char* comma = strchr(ptr, ',');
  4845. if(comma == NULL)
  4846. {
  4847. oubuf.append(ptr);
  4848. ptr = NULL;
  4849. }
  4850. else
  4851. {
  4852. oubuf.append(comma - ptr, ptr);
  4853. ptr = comma + 1;
  4854. }
  4855. if (ptr && strstr(ptr,"ou=") && !organizationalUnitExists(ptr))
  4856. createLdapBasedn(user, ptr, ptype);
  4857. addOrganizationalUnit(user, oubuf.str(), ptr, ptype);
  4858. }
  4859. virtual bool addOrganizationalUnit(ISecUser* user, const char* name, const char* basedn, SecPermissionType ptype)
  4860. {
  4861. if(name == NULL || basedn == NULL)
  4862. {
  4863. DBGLOG("CLdapClient::addOrganizationalUnit OU name must be provided");
  4864. return false;
  4865. }
  4866. if(strchr(name, '/') != NULL || strchr(name, '=') != NULL)
  4867. {
  4868. DBGLOG("CLdapClient::addOrganizationalUnit Invalid characters in OU");
  4869. return false;
  4870. }
  4871. StringBuffer dn;
  4872. dn.append("ou=").append(name).append(",").append(basedn);
  4873. if (organizationalUnitExists(dn.str()))
  4874. return true;
  4875. char *ou_values[] = {(char*)name, NULL };
  4876. LDAPMod ou_attr =
  4877. {
  4878. LDAP_MOD_ADD,
  4879. "ou",
  4880. ou_values
  4881. };
  4882. char *name_values[] = {(char*)name, NULL };
  4883. LDAPMod name_attr =
  4884. {
  4885. LDAP_MOD_ADD,
  4886. "name",
  4887. name_values
  4888. };
  4889. char *oc_values[] = {"OrganizationalUnit", NULL };
  4890. LDAPMod oc_attr =
  4891. {
  4892. LDAP_MOD_ADD,
  4893. "objectClass",
  4894. oc_values
  4895. };
  4896. MemoryBuffer sdbuf;
  4897. Owned<CSecurityDescriptor> default_sd = NULL;
  4898. if(m_pp != NULL)
  4899. default_sd.setown(m_pp->createDefaultSD(user, name, ptype));
  4900. if(default_sd != NULL)
  4901. sdbuf.append(default_sd->getDescriptor());
  4902. LDAPMod *attrs[6];
  4903. int ind = 0;
  4904. attrs[ind++] = &ou_attr;
  4905. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  4906. {
  4907. attrs[ind++] = &name_attr;
  4908. }
  4909. attrs[ind++] = &oc_attr;
  4910. LDAPMod sd_attr;
  4911. struct berval sd_val;
  4912. sd_val.bv_len = sdbuf.length();
  4913. sd_val.bv_val = (char*)sdbuf.toByteArray();
  4914. struct berval* sd_values[] = {&sd_val, NULL};
  4915. sd_attr.mod_op = LDAP_MOD_ADD | LDAP_MOD_BVALUES;
  4916. sd_attr.mod_type = (char*)m_ldapconfig->getSdFieldName();
  4917. sd_attr.mod_vals.modv_bvals = sd_values;
  4918. if(sdbuf.length() > 0)
  4919. attrs[ind++] = &sd_attr;
  4920. attrs[ind] = NULL;
  4921. Owned<ILdapConnection> lconn = m_connections->getConnection();
  4922. LDAP* ld = lconn.get()->getLd();
  4923. int rc = ldap_add_ext_s(ld, (char*)dn.str(), attrs, NULL, NULL);
  4924. if ( rc != LDAP_SUCCESS )
  4925. {
  4926. if(rc == LDAP_ALREADY_EXISTS)
  4927. {
  4928. WARNLOG("CLdapClient::addOrganizationalUnit LDAP object 'ou=%s,%s' already exists", name, basedn);
  4929. return false;
  4930. }
  4931. else
  4932. {
  4933. throw MakeStringException(-1, "ldap_add_ext_s error for ou=%s,%s: %d %s", name, basedn, rc, ldap_err2string( rc ));
  4934. }
  4935. }
  4936. return true;
  4937. }
  4938. virtual void name2dn(SecResourceType rtype, const char* resourcename, const char* basedn, StringBuffer& ldapname)
  4939. {
  4940. StringBuffer namebuf;
  4941. const char* bptr = resourcename;
  4942. const char* sep = strstr(resourcename, "::");
  4943. while(sep != NULL)
  4944. {
  4945. if(sep > bptr)
  4946. {
  4947. StringBuffer onebuf;
  4948. onebuf.append("ou=").append(sep-bptr, bptr).append(",");
  4949. namebuf.insert(0, onebuf.str());
  4950. }
  4951. bptr = sep + 2;
  4952. sep = strstr(bptr, "::");
  4953. }
  4954. if(*bptr != '\0')
  4955. {
  4956. StringBuffer onebuf;
  4957. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY && (rtype == RT_DEFAULT || rtype == RT_MODULE || rtype == RT_SERVICE))
  4958. onebuf.append("cn");
  4959. else
  4960. onebuf.append("ou");
  4961. onebuf.append("=").append(bptr).append(",");
  4962. namebuf.insert(0, onebuf.str());
  4963. }
  4964. namebuf.append(basedn);
  4965. LdapUtils::normalizeDn(namebuf.str(), m_ldapconfig->getBasedn(), ldapname);
  4966. }
  4967. virtual void name2rdn(SecResourceType rtype, const char* resourcename, StringBuffer& ldapname)
  4968. {
  4969. if(resourcename == NULL || *resourcename == '\0')
  4970. {
  4971. DBGLOG("CLdapClient::name2rdn resourcename must be provided");
  4972. return;
  4973. }
  4974. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY && (rtype == RT_DEFAULT || rtype == RT_MODULE || rtype == RT_SERVICE))
  4975. ldapname.append("cn=");
  4976. else
  4977. ldapname.append("ou=");
  4978. const char* prevptr = resourcename;
  4979. const char* nextptr = strstr(resourcename, "::");
  4980. while(nextptr != NULL)
  4981. {
  4982. prevptr = nextptr + 2;
  4983. nextptr = strstr(prevptr, "::");
  4984. }
  4985. if(*prevptr != '\0')
  4986. ldapname.append(prevptr);
  4987. }
  4988. virtual bool addResource(SecResourceType rtype, ISecUser& user, ISecResource* resource, SecPermissionType ptype, const char* basedn)
  4989. {
  4990. Owned<CSecurityDescriptor> template_sd = NULL;
  4991. const char* templatename = m_ldapconfig->getTemplateName();
  4992. if(templatename != NULL && *templatename != '\0')
  4993. {
  4994. IArrayOf<CSecurityDescriptor> sdlist;
  4995. template_sd.setown(new CSecurityDescriptor(templatename));
  4996. sdlist.append(*LINK(template_sd));
  4997. if(basedn && *basedn)
  4998. getSecurityDescriptors(sdlist, basedn);
  4999. else
  5000. getSecurityDescriptors(rtype, sdlist);
  5001. }
  5002. Owned<CSecurityDescriptor> default_sd = NULL;
  5003. if(template_sd != NULL && template_sd->getDescriptor().length() > 0)
  5004. {
  5005. MemoryBuffer template_sd_buf;
  5006. template_sd_buf.append(template_sd->getDescriptor());
  5007. if(m_pp != NULL)
  5008. default_sd.setown(m_pp->createDefaultSD(&user, resource, template_sd_buf));
  5009. }
  5010. else
  5011. {
  5012. if(m_pp != NULL)
  5013. default_sd.setown(m_pp->createDefaultSD(&user, resource, ptype));
  5014. }
  5015. return addResource(rtype, user, resource, ptype, basedn, default_sd.get());
  5016. }
  5017. virtual bool addResource(SecResourceType rtype, ISecUser& user, ISecResource* resource, SecPermissionType ptype, const char* basedn, CSecurityDescriptor* default_sd, bool lessException=true)
  5018. {
  5019. if(resource == NULL)
  5020. {
  5021. DBGLOG("CLdapClient::addResource can't add resource, ISecResource must be specified");
  5022. return true;
  5023. }
  5024. char* resourcename = (char*)resource->getName();
  5025. if(resourcename == NULL)
  5026. {
  5027. DBGLOG("CLdapClient::addResource can't add resource, empty resource name");
  5028. return false;
  5029. }
  5030. const char* rbasedn;
  5031. StringBuffer rbasednbuf;
  5032. if(basedn == NULL)
  5033. rbasedn = m_ldapconfig->getResourceBasedn(rtype);
  5034. else
  5035. {
  5036. LdapUtils::normalizeDn(basedn, m_ldapconfig->getBasedn(), rbasednbuf);
  5037. rbasedn = rbasednbuf.str();
  5038. }
  5039. if(rbasedn == NULL || *rbasedn == '\0')
  5040. {
  5041. DBGLOG("CLdapClient::addResource Can't add resource '%s', corresponding resource basedn is not defined",resourcename);
  5042. return false;
  5043. }
  5044. if(strchr(resourcename, '/') != NULL || strchr(resourcename, '=') != NULL)
  5045. {
  5046. DBGLOG("CLdapClient::addResource Can't add resource '%s', invalid characters specified",resourcename);
  5047. return false;
  5048. }
  5049. if(rtype == RT_FILE_SCOPE || rtype == RT_WORKUNIT_SCOPE)
  5050. {
  5051. StringBuffer extbuf;
  5052. name2dn(rtype, resourcename, rbasedn, extbuf);
  5053. createLdapBasedn(&user, extbuf.str(), ptype);
  5054. return true;
  5055. }
  5056. LdapServerType servertype = m_ldapconfig->getServerType();
  5057. char* description = (char*)((CLdapSecResource*)resource)->getDescription();
  5058. StringBuffer dn;
  5059. char *fieldname, *oc_name;
  5060. if(servertype == ACTIVE_DIRECTORY)
  5061. {
  5062. fieldname = "cn";
  5063. oc_name = "Volume";
  5064. }
  5065. else
  5066. {
  5067. fieldname = "ou";
  5068. oc_name = "OrganizationalUnit";
  5069. }
  5070. dn.append(fieldname).append("=").append(resourcename).append(",");
  5071. dn.append(rbasedn);
  5072. char *cn_values[] = {resourcename, NULL };
  5073. LDAPMod cn_attr =
  5074. {
  5075. LDAP_MOD_ADD,
  5076. fieldname,
  5077. cn_values
  5078. };
  5079. char *oc_values[] = {oc_name, NULL };
  5080. LDAPMod oc_attr =
  5081. {
  5082. LDAP_MOD_ADD,
  5083. "objectClass",
  5084. oc_values
  5085. };
  5086. char* uncname_values[] = {resourcename, NULL};
  5087. LDAPMod uncname_attr =
  5088. {
  5089. LDAP_MOD_ADD,
  5090. "uNCName",
  5091. uncname_values
  5092. };
  5093. StringBuffer descriptionbuf;
  5094. if(description && *description)
  5095. descriptionbuf.append(description);
  5096. else
  5097. descriptionbuf.appendf("Access to %s", resourcename);
  5098. char* description_values[] = {(char*)descriptionbuf.str(), NULL};
  5099. LDAPMod description_attr =
  5100. {
  5101. LDAP_MOD_ADD,
  5102. "description",
  5103. description_values
  5104. };
  5105. Owned<CSecurityDescriptor> template_sd = NULL;
  5106. const char* templatename = m_ldapconfig->getTemplateName();
  5107. if(templatename != NULL && *templatename != '\0')
  5108. {
  5109. IArrayOf<CSecurityDescriptor> sdlist;
  5110. template_sd.setown(new CSecurityDescriptor(templatename));
  5111. sdlist.append(*LINK(template_sd));
  5112. getSecurityDescriptors(rtype, sdlist);
  5113. }
  5114. int numberOfSegs = 0;
  5115. if(default_sd != NULL)
  5116. {
  5117. numberOfSegs = m_pp->sdSegments(default_sd);
  5118. }
  5119. LDAPMod **attrs = (LDAPMod**)(alloca((5+numberOfSegs)*sizeof(LDAPMod*)));
  5120. int ind = 0;
  5121. attrs[ind++] = &cn_attr;
  5122. attrs[ind++] = &oc_attr;
  5123. attrs[ind++] = &description_attr;
  5124. if(servertype == ACTIVE_DIRECTORY)
  5125. {
  5126. attrs[ind++] = &uncname_attr;
  5127. }
  5128. LDAPMod sd_attr;
  5129. if(default_sd != NULL)
  5130. {
  5131. struct berval** sd_values = (struct berval**)alloca(sizeof(struct berval*)*(numberOfSegs+1));
  5132. MemoryBuffer& sdbuf = default_sd->getDescriptor();
  5133. // Active Directory acutally has only one segment.
  5134. if(servertype == ACTIVE_DIRECTORY)
  5135. {
  5136. struct berval* sd_val = (struct berval*)alloca(sizeof(struct berval));
  5137. sd_val->bv_len = sdbuf.length();
  5138. sd_val->bv_val = (char*)sdbuf.toByteArray();
  5139. sd_values[0] = sd_val;
  5140. sd_values[1] = NULL;
  5141. sd_attr.mod_type = "ntSecurityDescriptor";
  5142. }
  5143. else
  5144. {
  5145. const char* bbptr = sdbuf.toByteArray();
  5146. const char* bptr = sdbuf.toByteArray();
  5147. int sdbuflen = sdbuf.length();
  5148. int segind;
  5149. for(segind = 0; segind < numberOfSegs; segind++)
  5150. {
  5151. if(bptr - bbptr >= sdbuflen)
  5152. break;
  5153. while(*bptr == '\0' && (bptr - bbptr) < sdbuflen)
  5154. bptr++;
  5155. const char* eptr = bptr;
  5156. while(*eptr != '\0' && (eptr - bbptr) < sdbuflen)
  5157. eptr++;
  5158. struct berval* sd_val = (struct berval*)alloca(sizeof(struct berval));
  5159. sd_val->bv_len = eptr - bptr;
  5160. sd_val->bv_val = (char*)bptr;
  5161. sd_values[segind] = sd_val;
  5162. bptr = eptr + 1;
  5163. }
  5164. sd_values[segind] = NULL;
  5165. sd_attr.mod_type = (char*)m_ldapconfig->getSdFieldName();
  5166. }
  5167. sd_attr.mod_op = LDAP_MOD_ADD | LDAP_MOD_BVALUES;
  5168. sd_attr.mod_vals.modv_bvals = sd_values;
  5169. attrs[ind++] = &sd_attr;
  5170. }
  5171. attrs[ind] = NULL;
  5172. Owned<ILdapConnection> lconn = m_connections->getConnection();
  5173. LDAP* ld = lconn.get()->getLd();
  5174. int rc = ldap_add_ext_s(ld, (char*)dn.str(), attrs, NULL, NULL);
  5175. if ( rc != LDAP_SUCCESS )
  5176. {
  5177. if(rc == LDAP_ALREADY_EXISTS)
  5178. {
  5179. //WARNLOG("Can't insert %s to Ldap Server, an LDAP object with this name already exists", resourcename);
  5180. if(lessException)
  5181. {
  5182. DBGLOG("CLdapClient::addResource Can't add resource '%s', an LDAP object with this name already exists", resourcename);
  5183. return false;
  5184. }
  5185. else
  5186. throw MakeStringException(-1, "Can't insert %s, an LDAP object with this name already exists", resourcename);
  5187. }
  5188. else
  5189. {
  5190. throw MakeStringException(-1, "ldap_add_ext_s error for %s: %d %s", resourcename, rc, ldap_err2string( rc ));
  5191. }
  5192. }
  5193. return true;
  5194. }
  5195. virtual void enableUser(ISecUser* user, const char* dn, LDAP* ld)
  5196. {
  5197. const char* username = user->getName();
  5198. StringBuffer filter;
  5199. filter.append("sAMAccountName=").append(username);
  5200. char *attribute;
  5201. LDAPMessage *message;
  5202. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  5203. char *attrs[] = {"userAccountControl", NULL};
  5204. CLDAPMessage searchResult;
  5205. 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 );
  5206. if ( rc != LDAP_SUCCESS )
  5207. {
  5208. DBGLOG("ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), m_ldapconfig->getUserBasedn());
  5209. throw MakeStringException(-1, "ldap_search_ext_s error: %s, when searching %s under %s", ldap_err2string( rc ), filter.str(), m_ldapconfig->getUserBasedn());
  5210. }
  5211. StringBuffer act_ctrl;
  5212. message = LdapFirstEntry( ld, searchResult);
  5213. if(message != NULL)
  5214. {
  5215. CLDAPGetAttributesWrapper atts(ld, searchResult);
  5216. for ( attribute = atts.getFirst();
  5217. attribute != NULL;
  5218. attribute = atts.getNext())
  5219. {
  5220. if(0 == stricmp(attribute, "userAccountControl"))
  5221. {
  5222. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  5223. if (vals.hasValues())
  5224. {
  5225. act_ctrl.append(vals.queryCharValue(0));
  5226. break;
  5227. }
  5228. }
  5229. }
  5230. }
  5231. if(act_ctrl.length() == 0)
  5232. {
  5233. DBGLOG("enableUser: userAccountControl doesn't exist for user %s",username);
  5234. throw MakeStringException(-1, "enableUser: userAccountControl doesn't exist for user %s",username);
  5235. }
  5236. unsigned act_ctrl_val = atoi(act_ctrl.str());
  5237. // UF_ACCOUNTDISABLE 0x0002
  5238. act_ctrl_val &= 0xFFFFFFFD;
  5239. #ifdef _DONT_EXPIRE_PASSWORD
  5240. // UF_DONT_EXPIRE_PASSWD 0x10000
  5241. if (m_domainPwdsNeverExpire)
  5242. act_ctrl_val |= 0x10000;
  5243. #endif
  5244. StringBuffer new_act_ctrl;
  5245. new_act_ctrl.append(act_ctrl_val);
  5246. char *ctrl_values[] = {(char*)new_act_ctrl.str(), NULL};
  5247. LDAPMod ctrl_attr = {
  5248. LDAP_MOD_REPLACE,
  5249. "userAccountControl",
  5250. ctrl_values
  5251. };
  5252. LDAPMod *cattrs[2];
  5253. cattrs[0] = &ctrl_attr;
  5254. cattrs[1] = NULL;
  5255. rc = ldap_modify_ext_s(ld, (char*)dn, cattrs, NULL, NULL);
  5256. if ( rc != LDAP_SUCCESS )
  5257. {
  5258. throw MakeStringException(-1, "error enableUser %s, ldap_modify_ext_s error: %s", username, ldap_err2string( rc ));
  5259. }
  5260. // set the password.
  5261. Owned<ISecUser> tmpuser = new CLdapSecUser(user->getName(), "");
  5262. const char* passwd = user->credentials().getPassword();
  5263. if(passwd == NULL || *passwd == '\0')
  5264. passwd = "password";
  5265. if (!updateUserPassword(*tmpuser, passwd, NULL))
  5266. {
  5267. DBGLOG("Error updating password for %s",username);
  5268. throw MakeStringException(-1, "Error updating password for %s",username);
  5269. }
  5270. }
  5271. virtual bool addUser(ISecUser& user)
  5272. {
  5273. const char* username = user.getName();
  5274. if(username == NULL || *username == '\0')
  5275. {
  5276. DBGLOG("Can't add user, username not set");
  5277. throw MakeStringException(-1, "Can't add user, username not set");
  5278. }
  5279. const char* fname = user.getFirstName();
  5280. const char* lname = user.getLastName();
  5281. if((lname == NULL || *lname == '\0') && (fname == NULL || *fname == '\0' || m_ldapconfig->getServerType() == IPLANET))
  5282. lname = username;
  5283. const char* fullname = user.getFullName();
  5284. StringBuffer fullname_buf;
  5285. if(fullname == NULL || *fullname == '\0')
  5286. {
  5287. if(fname != NULL && *fname != '\0')
  5288. {
  5289. fullname_buf.append(fname);
  5290. if(lname != NULL && *lname != '\0')
  5291. fullname_buf.append(" ");
  5292. }
  5293. if(lname != NULL && *lname != '\0')
  5294. fullname_buf.append(lname);
  5295. if(fullname_buf.length() == 0)
  5296. {
  5297. fullname_buf.append(username);
  5298. }
  5299. fullname = fullname_buf.str();
  5300. }
  5301. const char* employeeID = user.getEmployeeID();
  5302. const char* employeeNumber = user.getEmployeeNumber();
  5303. StringBuffer dn;
  5304. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  5305. {
  5306. dn.append("cn=").append(fullname).append(",");
  5307. }
  5308. else
  5309. {
  5310. dn.append("uid=").append(user.getName()).append(",");
  5311. }
  5312. dn.append(m_ldapconfig->getUserBasedn());
  5313. char* oc_name;
  5314. char* act_fieldname;
  5315. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  5316. {
  5317. oc_name = "User";
  5318. act_fieldname = "sAMAccountName";
  5319. }
  5320. else
  5321. {
  5322. oc_name = "inetorgperson";
  5323. act_fieldname = "uid";
  5324. }
  5325. char *cn_values[] = {(char*)fullname, NULL };
  5326. LDAPMod cn_attr =
  5327. {
  5328. LDAP_MOD_ADD,
  5329. "cn",
  5330. cn_values
  5331. };
  5332. char *oc_values[] = {oc_name, NULL};
  5333. LDAPMod oc_attr =
  5334. {
  5335. LDAP_MOD_ADD,
  5336. "objectClass",
  5337. oc_values
  5338. };
  5339. char *gn_values[] = { (char*)fname, NULL };
  5340. LDAPMod gn_attr = {
  5341. LDAP_MOD_ADD,
  5342. "givenName",
  5343. gn_values
  5344. };
  5345. char *sn_values[] = { (char*)lname, NULL };
  5346. LDAPMod sn_attr = {
  5347. LDAP_MOD_ADD,
  5348. "sn",
  5349. sn_values
  5350. };
  5351. char* actname_values[] = {(char*)username, NULL};
  5352. LDAPMod actname_attr =
  5353. {
  5354. LDAP_MOD_ADD,
  5355. act_fieldname,
  5356. actname_values
  5357. };
  5358. const char* passwd = user.credentials().getPassword();
  5359. if(passwd == NULL || *passwd == '\0')
  5360. passwd = "password";
  5361. char* passwd_values[] = {(char*)passwd, NULL};
  5362. LDAPMod passwd_attr =
  5363. {
  5364. LDAP_MOD_ADD,
  5365. "userpassword",
  5366. passwd_values
  5367. };
  5368. char *dispname_values[] = {(char*)fullname, NULL };
  5369. LDAPMod dispname_attr =
  5370. {
  5371. LDAP_MOD_ADD,
  5372. "displayName",
  5373. dispname_values
  5374. };
  5375. char* username_values[] = {(char*)username, NULL};
  5376. LDAPMod username_attr =
  5377. {
  5378. LDAP_MOD_ADD,
  5379. "userPrincipalName",
  5380. username_values
  5381. };
  5382. char* employeeID_values[] = {(char*)employeeID, NULL};
  5383. LDAPMod employeeID_attr =
  5384. {
  5385. LDAP_MOD_ADD,
  5386. "employeeId",
  5387. employeeID_values
  5388. };
  5389. char* employeeNumber_values[] = {(char*)employeeNumber, NULL};
  5390. LDAPMod employeeNumber_attr =
  5391. {
  5392. LDAP_MOD_ADD,
  5393. "employeeNumber",
  5394. employeeNumber_values
  5395. };
  5396. LDAPMod *attrs[10];
  5397. int ind = 0;
  5398. attrs[ind++] = &cn_attr;
  5399. attrs[ind++] = &oc_attr;
  5400. if(fname != NULL && *fname != '\0')
  5401. attrs[ind++] = &gn_attr;
  5402. if(lname != NULL && *lname != '\0')
  5403. attrs[ind++] = &sn_attr;
  5404. attrs[ind++] = &actname_attr;
  5405. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  5406. {
  5407. attrs[ind++] = &username_attr;
  5408. attrs[ind++] = &dispname_attr;
  5409. if (employeeID && *employeeID)
  5410. attrs[ind++] = &employeeID_attr;
  5411. if (employeeNumber && *employeeNumber)
  5412. attrs[ind++] = &employeeNumber_attr;
  5413. }
  5414. else
  5415. {
  5416. attrs[ind++] = &passwd_attr;
  5417. }
  5418. attrs[ind] = NULL;
  5419. Owned<ILdapConnection> lconn = m_connections->getConnection();
  5420. LDAP* ld = lconn.get()->getLd();
  5421. int rc = ldap_add_ext_s(ld, (char*)dn.str(), attrs, NULL, NULL);
  5422. if ( rc != LDAP_SUCCESS )
  5423. {
  5424. if(rc == LDAP_ALREADY_EXISTS)
  5425. {
  5426. DBGLOG("Can't add user %s, an LDAP object with this name already exists", username);
  5427. throw MakeStringException(-1, "Can't add user %s, an LDAP object with this name already exists", username);
  5428. }
  5429. else
  5430. {
  5431. DBGLOG("Error addUser %s, ldap_add_ext_s error: %s", username, ldap_err2string( rc ));
  5432. throw MakeStringException(-1, "Error addUser %s, ldap_add_ext_s error: %s", username, ldap_err2string( rc ));
  5433. }
  5434. }
  5435. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  5436. {
  5437. try
  5438. {
  5439. enableUser(&user, dn.str(), ld);
  5440. }
  5441. catch(...)
  5442. {
  5443. deleteUser(&user);
  5444. throw;
  5445. }
  5446. }
  5447. //Add tempfile scope for this user (spill, paused and checkpoint
  5448. //will be created under this user specific scope)
  5449. StringBuffer resName(queryDfsXmlBranchName(DXB_Internal));
  5450. resName.append("::").append(username);
  5451. Owned<ISecResource> resource = new CLdapSecResource(resName.str());
  5452. if (!addResource(RT_FILE_SCOPE, user, resource, PT_ADMINISTRATORS_AND_USER, m_ldapconfig->getResourceBasedn(RT_FILE_SCOPE)))
  5453. {
  5454. throw MakeStringException(-1, "Error adding temp file scope %s",resName.str());
  5455. }
  5456. return true;
  5457. }
  5458. bool createUserScope(ISecUser& user)
  5459. {
  5460. //Add tempfile scope for given user (spill, paused and checkpoint
  5461. //files will be created under this user specific scope)
  5462. StringBuffer resName(queryDfsXmlBranchName(DXB_Internal));
  5463. resName.append("::").append(user.getName());
  5464. Owned<ISecResource> resource = new CLdapSecResource(resName.str());
  5465. return addResource(RT_FILE_SCOPE, user, resource, PT_ADMINISTRATORS_AND_USER, m_ldapconfig->getResourceBasedn(RT_FILE_SCOPE));
  5466. }
  5467. virtual aindex_t getManagedScopeTree(LDAP* ld, SecResourceType rtype, const char * basedn, IArrayOf<ISecResource>& scopes)
  5468. {
  5469. Owned<ILdapConnection> lconn;
  5470. if (nullptr == ld)
  5471. {
  5472. lconn.setown(m_connections->getConnection());
  5473. ld = lconn.get()->getLd();
  5474. }
  5475. //Get array of all file scopes listed in files baseDN
  5476. StringBuffer basednbuf;
  5477. LdapUtils::normalizeDn(basedn ? basedn : m_ldapconfig->getResourceBasedn(rtype), m_ldapconfig->getBasedn(), basednbuf);
  5478. basednbuf.toLowerCase();//Will look something like "ou=files,ou=dataland_ecl,dc=internal,dc=sds". Lowercase ensures proper strstr with StringArray elements below
  5479. //Extract OU path from basedn ("ou=files,ou=dataland_ecl")
  5480. StringBuffer baseOU(basednbuf);
  5481. {
  5482. const char * pDC = strstr(baseOU.str(), ",dc=");
  5483. if (pDC)
  5484. baseOU.setLength(pDC - baseOU.str());//strip out trailing "dc=" portion
  5485. }
  5486. char *attrs[2];
  5487. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  5488. attrs[0] = "canonicalName";
  5489. else
  5490. attrs[0] = "entrydn";//389DirectoryServer
  5491. attrs[1] = nullptr;
  5492. //Call LDAP to get the complete OU tree underneath basdnbuf
  5493. CPagedLDAPSearch pagedSrch(ld, m_ldapconfig->getLdapTimeout(), (char*)basednbuf.str(), LDAP_SCOPE_SUBTREE, "objectClass=*", attrs);
  5494. StringArray arrScopes;
  5495. for (LDAPMessage *message = pagedSrch.getFirstEntry(); message; message = pagedSrch.getNextEntry())
  5496. {
  5497. CLDAPGetAttributesWrapper atts(ld, message);
  5498. for ( char *attribute = atts.getFirst();
  5499. attribute != NULL;
  5500. attribute = atts.getNext())
  5501. {
  5502. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  5503. if (vals.hasValues())
  5504. {
  5505. const char* val = vals.queryCharValue(0);
  5506. if(val)//this check probably isn't necessary since hasValues(), but could prevent a core
  5507. {
  5508. StringArray OUarray;//array to contain OU elements, most nested first (ie roxieuser, hpccinternal)
  5509. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  5510. {
  5511. //Build filescope from everything below the basedn
  5512. OUarray.appendList(val,"/",true);//create StringArray of OU elements. LDAP returns them in the form "internal.sds/files/dataland_ecl/hpccinternal/roxieuser
  5513. //Remove all domain and basedn elements
  5514. OUarray.remove(0, false);//remove domain element
  5515. while (OUarray.ordinality())
  5516. {
  5517. VStringBuffer theOU("ou=%s,", OUarray.item(0));
  5518. theOU.toLowerCase();//Lowercase to ensure proper strstr within basednbuf
  5519. if (nullptr != strstr(basednbuf.str(), theOU.str()))//search baseDN for OU substring
  5520. OUarray.remove(0, false);//remove baseDn element
  5521. else
  5522. break;
  5523. }
  5524. }
  5525. else
  5526. {
  5527. //389DirectoryServer, attribute returned in the form "ou=roxieuser,ou=hpccinternal,ou=files,ou=dataland_ecl,dc=risk,dc=regn,dc=net"
  5528. StringBuffer ouStr(val);
  5529. ouStr.toLowerCase();
  5530. //strip out trailing "dc=" portion
  5531. const char * pDC = strstr(ouStr.str(), ",dc=");
  5532. if (pDC)
  5533. ouStr.setLength(pDC - ouStr.str());
  5534. ouStr.replaceString(baseOU, nullptr);//strip out baseDN (ou=files,ou=dataland_ecl)
  5535. StringArray tmpOUarray;
  5536. if (!ouStr.isEmpty())
  5537. {
  5538. ouStr.replaceString("ou=", nullptr);//strip out all "ou=" strings
  5539. tmpOUarray.appendList(ouStr, ",");//create array of OU entries
  5540. //Populate OUarray in opposite order
  5541. for (int curr = tmpOUarray.ordinality() - 1; curr >= 0; curr--)
  5542. OUarray.append(tmpOUarray.item(curr));
  5543. }
  5544. }
  5545. //build OU string with remaining elements in the form "hpccinternal::roxieuser"
  5546. StringBuffer sb;
  5547. for (int curr = 0; curr < OUarray.ordinality(); curr++)
  5548. {
  5549. sb.appendf("%s%s", sb.isEmpty() ? "" : "::", OUarray.item(curr));
  5550. }
  5551. if (!sb.isEmpty())
  5552. {
  5553. arrScopes.append(sb);
  5554. }
  5555. }
  5556. }
  5557. }
  5558. }
  5559. //Build sorted IArrayOf<ISecResource> from arrScopes
  5560. if (arrScopes.length())
  5561. {
  5562. arrScopes.sortAscii(false);
  5563. ForEachItemIn(i, arrScopes)
  5564. {
  5565. const char * scope= arrScopes.item(i);
  5566. CLdapSecResource* resource = new CLdapSecResource(scope);
  5567. scopes.append(*resource);
  5568. }
  5569. }
  5570. DBGLOG("getManagedScopeTree() found %d scopes under '%s'", scopes.length(), basednbuf.str());
  5571. return scopes.length();
  5572. }
  5573. virtual SecAccessFlags queryDefaultPermission(ISecUser& user)
  5574. {
  5575. const char* basedn = m_ldapconfig->getResourceBasedn(RT_FILE_SCOPE);
  5576. if(basedn == NULL || *basedn == '\0')
  5577. {
  5578. DBGLOG("corresponding basedn is not defined");
  5579. return SecAccess_Unavailable;
  5580. }
  5581. const char* basebasedn = strchr(basedn, ',') + 1;
  5582. StringBuffer baseresource;
  5583. baseresource.append(basebasedn-basedn-4, basedn+3);
  5584. IArrayOf<ISecResource> base_resources;
  5585. base_resources.append(*new CLdapSecResource(baseresource.str()));
  5586. bool baseok = authorizeScope(user, base_resources, basebasedn);
  5587. if(baseok)
  5588. return base_resources.item(0).getAccessFlags();
  5589. else
  5590. return UNK_PERM_VALUE;
  5591. }
  5592. bool isReservedGroupName(const char * groupName)
  5593. {
  5594. if (stricmp(groupName, "Administrators") == 0 ||
  5595. stricmp(groupName, "Authenticated Users") == 0 ||
  5596. stricmp(groupName, "Directory Administrators") == 0)
  5597. {
  5598. return true;
  5599. }
  5600. return false;
  5601. }
  5602. //Data View related interfaces
  5603. void createView(const char * viewName, const char * viewDescription)
  5604. {
  5605. if(viewName == nullptr || *viewName == '\0')
  5606. throw MakeStringException(-1, "Can't add view, viewname is empty");
  5607. if (isReservedGroupName(viewName))
  5608. {
  5609. throw MakeStringException(-1, "Can't add view, '%s' is a reserved name", viewName);
  5610. }
  5611. addGroup(viewName, nullptr, nullptr, m_ldapconfig->getViewBasedn());//TODO Save description
  5612. }
  5613. void deleteView(const char * viewName)
  5614. {
  5615. if(viewName == nullptr || *viewName == '\0')
  5616. throw MakeStringException(-1, "Can't delete view, viewname is empty");
  5617. deleteGroup(viewName, (const char *)m_ldapconfig->getViewBasedn());
  5618. }
  5619. void queryAllViews(StringArray & viewNames, StringArray & viewDescriptions, StringArray & viewManagedBy)
  5620. {
  5621. StringArray names;
  5622. StringArray managedBy;
  5623. StringArray desc;
  5624. getAllGroups(names, managedBy, desc, (const char *)m_ldapconfig->getViewBasedn());
  5625. unsigned len = names.ordinality();
  5626. for(unsigned idx = 0; idx < len; idx++)
  5627. {
  5628. const char * pName = names.item(idx);
  5629. if (!isReservedGroupName(pName))
  5630. {
  5631. viewNames.append(pName);
  5632. viewDescriptions.append(desc.item(idx));
  5633. viewManagedBy.append(managedBy.item(idx));
  5634. }
  5635. }
  5636. }
  5637. bool userInView(const char * user, const char* viewName)
  5638. {
  5639. if(user == nullptr || *user == '\0')
  5640. throw MakeStringException(-1, "Can't check user in view, user name is empty");
  5641. if(viewName == nullptr || *viewName == '\0')
  5642. throw MakeStringException(-1, "Can't check user in view, viewName is empty");
  5643. try
  5644. {
  5645. StringBuffer userDN;
  5646. getUserDN(user, userDN);
  5647. VStringBuffer viewDN("CN=%s,%s",viewName, m_ldapconfig->getViewBasedn());
  5648. return userInGroup(userDN.str(), viewDN.str());
  5649. }
  5650. catch (IException* e)
  5651. {
  5652. #ifdef _DEBUG
  5653. StringBuffer emsg;
  5654. e->errorMessage(emsg);
  5655. DBGLOG("userInView(%s,%s) - %s", user, viewName, emsg.str());
  5656. #endif
  5657. e->Release();
  5658. return false;
  5659. }
  5660. }
  5661. void updateViewContents(const char * viewName, const char * content)
  5662. {
  5663. if(viewName == nullptr || *viewName == '\0')
  5664. throw MakeStringException(-1, "Can't updateViewContents, viewName is empty");
  5665. //Update LDAP description
  5666. char *desc_values[] = { (content && *content != '\0') ? (char*)content : (char*)"|", NULL };
  5667. LDAPMod desc_attr = {
  5668. LDAP_MOD_REPLACE,
  5669. "description",
  5670. desc_values
  5671. };
  5672. LDAPMod *attrs[2];
  5673. attrs[0] = &desc_attr;
  5674. attrs[1] = nullptr;
  5675. TIMEVAL timeOut = { m_ldapconfig->getLdapTimeout(), 0 };
  5676. Owned<ILdapConnection> lconn = m_connections->getConnection();
  5677. LDAP* ld = lconn.get()->getLd();
  5678. StringBuffer dn;
  5679. dn.appendf("CN=%s,%s", viewName, (char*) m_ldapconfig->getViewBasedn());
  5680. unsigned rc = ldap_modify_ext_s(ld, (char*)dn.str(), attrs, nullptr, nullptr);
  5681. if (rc != LDAP_SUCCESS )
  5682. throw MakeStringException(-1, "Error updating view %s - %s", viewName, ldap_err2string( rc ));
  5683. }
  5684. void addViewColumns(const char * viewName, StringArray & files, StringArray & columns)
  5685. {
  5686. if(viewName == nullptr || *viewName == '\0')
  5687. throw MakeStringException(-1, "Can't addViewColumns, viewName is empty");
  5688. StringArray currFiles;
  5689. StringArray currCols;
  5690. queryViewColumns(viewName, currFiles, currCols);
  5691. unsigned vCount = currFiles.ordinality();
  5692. assertex(vCount == currCols.ordinality());
  5693. unsigned len = files.ordinality();
  5694. assertex(len == columns.ordinality());
  5695. bool changed = false;
  5696. for(unsigned idx = 0; idx < len; idx++)
  5697. {
  5698. bool isDup = false;
  5699. for (unsigned vIdx = 0; vIdx < vCount; vIdx++)//look for dups
  5700. {
  5701. if (0 == stricmp(files.item(idx), currFiles.item(vIdx)) &&
  5702. 0 == stricmp(columns.item(idx), currCols.item(vIdx)))
  5703. {
  5704. isDup = true;//skip duplicate entry
  5705. break;
  5706. }
  5707. }
  5708. if (!isDup)
  5709. {
  5710. currFiles.append(files.item(idx));
  5711. currCols.append(columns.item(idx));
  5712. changed = true;
  5713. }
  5714. }
  5715. if (!changed)
  5716. {
  5717. throw MakeStringException(-1, "Specified columns already exist in view");
  5718. }
  5719. ///build description buffer containing one or more ||lfn|col
  5720. StringBuffer description;
  5721. len = currFiles.ordinality();
  5722. for(unsigned idx = 0; idx < len; idx++)
  5723. {
  5724. description.appendf("||%s|%s",currFiles.item(idx), currCols.item(idx));//use illegal LFN character as separators
  5725. }
  5726. updateViewContents(viewName, description.str());
  5727. }
  5728. void removeViewColumns(const char * viewName, StringArray & files, StringArray & columns)
  5729. {
  5730. if(viewName == nullptr || *viewName == '\0')
  5731. throw MakeStringException(-1, "Can't removeViewColumns, viewName is empty");
  5732. StringArray currFiles;
  5733. StringArray currCols;
  5734. queryViewColumns(viewName, currFiles, currCols);
  5735. assertex(currFiles.ordinality() == currCols.ordinality());
  5736. unsigned len = files.ordinality();
  5737. assertex(len == columns.ordinality());
  5738. bool changed = false;
  5739. for(unsigned idx = 0; idx < len; idx++)//for all pairs to be removed
  5740. {
  5741. unsigned len2 = currFiles.ordinality();
  5742. for(unsigned idx2 = 0; idx2 < len2; idx2++)
  5743. {
  5744. if (0 == stricmp(files.item(idx), currFiles.item(idx2)) &&
  5745. 0 == stricmp(columns.item(idx), currCols.item(idx2)))
  5746. {
  5747. currFiles.remove(idx2);
  5748. currCols.remove(idx2);
  5749. changed = true;
  5750. break;
  5751. }
  5752. }
  5753. }
  5754. if (!changed)
  5755. {
  5756. throw MakeStringException(-1, "Specified columns do not exist in view");
  5757. }
  5758. ///build description buffer containing one or more ||lfn|col
  5759. StringBuffer description;
  5760. len = currFiles.ordinality();
  5761. for(unsigned idx = 0; idx < len; idx++)
  5762. {
  5763. description.appendf("||%s|%s",currFiles.item(idx), currCols.item(idx));//use illegal LFN character as separators
  5764. }
  5765. updateViewContents(viewName, description.str());
  5766. }
  5767. void queryViewColumns(const char * viewName, StringArray & files, StringArray & columns)
  5768. {
  5769. if(viewName == nullptr || *viewName == '\0')
  5770. throw MakeStringException(-1, "Can't queryViewColumns, viewName is empty");
  5771. StringBuffer filter;
  5772. if(m_ldapconfig->getServerType() == ACTIVE_DIRECTORY)
  5773. filter.append("objectClass=group");
  5774. else
  5775. filter.append("objectClass=groupofuniquenames");
  5776. TIMEVAL timeOut = {m_ldapconfig->getLdapTimeout(),0};
  5777. Owned<ILdapConnection> lconn = m_connections->getConnection();
  5778. LDAP* ld = lconn.get()->getLd();
  5779. char *attrs[] = {"description", NULL};
  5780. StringBuffer dn;
  5781. dn.appendf("CN=%s,%s", viewName, (char*)m_ldapconfig->getViewBasedn() );
  5782. CPagedLDAPSearch pagedSrch(ld, m_ldapconfig->getLdapTimeout(), (char*)dn.str(), LDAP_SCOPE_SUBTREE, (char*)filter.str(), attrs);
  5783. int idx = 0;
  5784. LDAPMessage *message = pagedSrch.getFirstEntry();
  5785. if (message)
  5786. {
  5787. CLDAPGetAttributesWrapper atts(ld, message);
  5788. char * attribute = atts.getFirst();
  5789. if (attribute)
  5790. {
  5791. CLDAPGetValuesLenWrapper vals(ld, message, attribute);
  5792. if(vals.hasValues() && stricmp(attribute, "description") == 0)
  5793. {
  5794. StringBuffer sb(vals.queryCharValue(0));
  5795. if (!sb.isEmpty())
  5796. {
  5797. StringBuffer sbFile;
  5798. StringBuffer sbCol;
  5799. unsigned finger = 0;
  5800. unsigned len = sb.length();
  5801. while (finger < len)
  5802. {
  5803. while (finger < len && sb.charAt(finger) == '|')
  5804. finger++;//skip to lfn
  5805. sbFile.clear();
  5806. while (finger < len && sb.charAt(finger) != '|')
  5807. sbFile.append(sb.charAt(finger++));
  5808. while (finger < len && sb.charAt(finger) == '|')
  5809. finger++;//skip to column name
  5810. sbCol.clear();
  5811. while (finger < len && sb.charAt(finger) != '|')
  5812. sbCol.append(sb.charAt(finger++));
  5813. if (!sbFile.isEmpty() && !sbCol.isEmpty())
  5814. {
  5815. files.append(sbFile.str());
  5816. columns.append(sbCol.str());
  5817. }
  5818. }
  5819. }
  5820. }
  5821. }
  5822. }
  5823. }
  5824. void addViewMembers(const char * viewName, StringArray & viewUsers, StringArray & viewGroups)
  5825. {
  5826. if(viewName == nullptr || *viewName == '\0')
  5827. throw MakeStringException(-1, "Can't addViewMembers, viewName is empty");
  5828. unsigned len = viewUsers.ordinality();
  5829. for (unsigned idx = 0; idx < len; idx++)
  5830. {
  5831. changeUserGroup("add", viewUsers.item(idx), viewName, m_ldapconfig->getViewBasedn());
  5832. }
  5833. //TODO handle viewGroups
  5834. }
  5835. void removeViewMembers(const char * viewName, StringArray & viewUsers, StringArray & viewGroups)
  5836. {
  5837. if(viewName == nullptr || *viewName == '\0')
  5838. throw MakeStringException(-1, "Can't removeViewMembers, viewName is empty");
  5839. unsigned len = viewUsers.ordinality();
  5840. for (unsigned idx = 0; idx < len; idx++)
  5841. {
  5842. changeUserGroup("delete", viewUsers.item(idx), viewName, m_ldapconfig->getViewBasedn());
  5843. }
  5844. //TODO handle viewGroups
  5845. }
  5846. void queryViewMembers(const char * viewName, StringArray & viewUsers, StringArray & viewGroups)
  5847. {
  5848. if(viewName == nullptr || *viewName == '\0')
  5849. throw MakeStringException(-1, "Can't queryViewMembers, viewName is empty");
  5850. getGroupMembers(viewName, viewUsers, m_ldapconfig->getViewBasedn());
  5851. //TODO get viewGroups
  5852. }
  5853. };
  5854. #ifdef _WIN32
  5855. bool verifyServerCert(LDAP* ld, PCCERT_CONTEXT pServerCert)
  5856. {
  5857. return true;
  5858. }
  5859. #endif
  5860. ILdapClient* createLdapClient(IPropertyTree* cfg)
  5861. {
  5862. return new CLdapClient(cfg);
  5863. }