ldapconnection.cpp 220 KB

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