ldapconnection.cpp 238 KB

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