ldapconnection.cpp 203 KB

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