ldapconnection.cpp 219 KB

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