ldapconnection.cpp 202 KB

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