ldapconnection.cpp 205 KB

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