ldapconnection.cpp 187 KB

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