ldaputil.c 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456
  1. /** BEGIN COPYRIGHT BLOCK
  2. * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission.
  3. * Copyright (C) 2005 Red Hat, Inc.
  4. * All rights reserved.
  5. *
  6. * mozldap_ldap_explode, mozldap_ldap_explode_dn, mozldap_ldap_explode_rdn
  7. * are from the file ldap/libraries/libldap/getdn.c in the Mozilla LDAP C SDK
  8. *
  9. * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  10. *
  11. * The contents of this file are subject to the Mozilla Public License Version
  12. * 1.1 (the "License"); you may not use this file except in compliance with
  13. * the License. You may obtain a copy of the License at
  14. * http://www.mozilla.org/MPL/
  15. *
  16. * Software distributed under the License is distributed on an "AS IS" basis,
  17. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  18. * for the specific language governing rights and limitations under the
  19. * License.
  20. *
  21. * The Original Code is Mozilla Communicator client code, released
  22. * March 31, 1998.
  23. *
  24. * The Initial Developer of the Original Code is
  25. * Netscape Communications Corporation.
  26. * Portions created by the Initial Developer are Copyright (C) 1998-1999
  27. * the Initial Developer. All Rights Reserved.
  28. *
  29. * Contributor(s):
  30. *
  31. * Alternatively, the contents of this file may be used under the terms of
  32. * either of the GNU General Public License Version 2 or later (the "GPL"),
  33. * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  34. * in which case the provisions of the GPL or the LGPL are applicable instead
  35. * of those above. If you wish to allow use of your version of this file only
  36. * under the terms of either the GPL or the LGPL, and not to allow others to
  37. * use your version of this file under the terms of the MPL, indicate your
  38. * decision by deleting the provisions above and replace them with the notice
  39. * and other provisions required by the GPL or the LGPL. If you do not delete
  40. * the provisions above, a recipient may use your version of this file under
  41. * the terms of any one of the MPL, the GPL or the LGPL.
  42. *
  43. * Copyright (c) 1994 Regents of the University of Michigan.
  44. * All rights reserved.
  45. *
  46. * License: GPL (version 3 or any later version).
  47. * See LICENSE for details.
  48. * END COPYRIGHT BLOCK **/
  49. #ifdef HAVE_CONFIG_H
  50. # include <config.h>
  51. #endif
  52. /* ldaputil.c -- LDAP utility functions and wrappers */
  53. #include <sys/socket.h>
  54. #include <sys/param.h>
  55. #include <unistd.h>
  56. #include <pwd.h>
  57. #include <libgen.h>
  58. #include <pk11func.h>
  59. #include "slap.h"
  60. #include "prtime.h"
  61. #include "prinrval.h"
  62. #include "snmp_collator.h"
  63. #if !defined(USE_OPENLDAP)
  64. #include <ldap_ssl.h>
  65. #include <ldappr.h>
  66. #else
  67. /* need mutex around ldap_initialize - see https://fedorahosted.org/389/ticket/348 */
  68. static PRCallOnceType ol_init_callOnce = {0,0};
  69. static PRLock *ol_init_lock = NULL;
  70. #if defined(USE_OPENLDAP)
  71. extern void getSSLVersionRangeOL(int *min, int *max);
  72. extern int getSSLVersionRange(char **min, char **max);
  73. #endif
  74. static PRStatus
  75. internal_ol_init_init(void)
  76. {
  77. PR_ASSERT(NULL == ol_init_lock);
  78. if ((ol_init_lock = PR_NewLock()) == NULL) {
  79. PRErrorCode errorCode = PR_GetError();
  80. slapi_log_error(SLAPI_LOG_FATAL, "internal_ol_init_init", "PR_NewLock failed %d:%s\n",
  81. errorCode, slapd_pr_strerror(errorCode));
  82. return PR_FAILURE;
  83. }
  84. return PR_SUCCESS;
  85. }
  86. #endif
  87. /* the server depends on the old, deprecated ldap_explode behavior which openldap
  88. does not support - the use of the mozldap code should be discouraged as
  89. there are issues that mozldap does not handle correctly. */
  90. static char **mozldap_ldap_explode( const char *dn, const int notypes, const int nametype );
  91. static char **mozldap_ldap_explode_dn( const char *dn, const int notypes );
  92. static char **mozldap_ldap_explode_rdn( const char *rdn, const int notypes );
  93. #ifdef HAVE_KRB5
  94. static void clear_krb5_ccache();
  95. #endif
  96. #ifdef MEMPOOL_EXPERIMENTAL
  97. void _free_wrapper(void *ptr)
  98. {
  99. slapi_ch_free(&ptr);
  100. }
  101. #endif
  102. /*
  103. * Function: slapi_ldap_unbind()
  104. * Purpose: release an LDAP session obtained from a call to slapi_ldap_init().
  105. */
  106. void
  107. slapi_ldap_unbind( LDAP *ld )
  108. {
  109. if ( ld != NULL ) {
  110. ldap_unbind_ext( ld, NULL, NULL );
  111. }
  112. }
  113. #if defined(USE_OPENLDAP)
  114. /* mozldap ldap_init and ldap_url_parse accept a hostname in the form
  115. host1[:port1]SPACEhost2[:port2]SPACEhostN[:portN]
  116. where SPACE is a single space (0x20) character
  117. for openldap, we have to convert this to a string like this:
  118. PROTO://host1[:port1]/SPACEPROTO://host2[:port2]/SPACEPROTO://hostN[:portN]/
  119. where PROTO is ldap or ldaps or ldapi
  120. if proto is NULL, assume hostname_or_uri is really a valid ldap uri
  121. */
  122. static char *
  123. convert_to_openldap_uri(const char *hostname_or_uri, int port, const char *proto)
  124. {
  125. char *retstr = NULL;
  126. char *my_copy = NULL;
  127. char *start = NULL;
  128. char *iter = NULL;
  129. char *ptr = NULL;
  130. char *s = NULL;
  131. const char *brkstr = " ";
  132. int done = 0;
  133. if (!hostname_or_uri) {
  134. return NULL;
  135. }
  136. if(slapi_is_ipv6_addr(hostname_or_uri)){
  137. /* We need to encapsulate the ipv6 addr with brackets */
  138. my_copy = slapi_ch_smprintf("[%s]",hostname_or_uri);
  139. } else {
  140. my_copy = slapi_ch_strdup(hostname_or_uri);
  141. }
  142. /* see if hostname_or_uri is an ldap uri */
  143. if (!proto && !PL_strncasecmp(my_copy, "ldap", 4)) {
  144. start = my_copy + 4;
  145. if ((*start == 's') || (*start == 'i')) {
  146. start++;
  147. }
  148. if (!PL_strncmp(start, "://", 3)) {
  149. *start = '\0';
  150. proto = my_copy;
  151. start += 3;
  152. } else {
  153. slapi_log_error(SLAPI_LOG_FATAL, "convert_to_openldap_uri",
  154. "The given LDAP URI [%s] is not valid\n", hostname_or_uri);
  155. goto end;
  156. }
  157. } else if (!proto) {
  158. slapi_log_error(SLAPI_LOG_FATAL, "convert_to_openldap_uri",
  159. "The given LDAP URI [%s] is not valid\n", hostname_or_uri);
  160. goto end;
  161. } else {
  162. start = my_copy; /* just assume it's not a uri */
  163. }
  164. for (s = ldap_utf8strtok_r(my_copy, brkstr, &iter); s != NULL; s = ldap_utf8strtok_r(NULL, brkstr, &iter)) {
  165. /* strtok will grab the '/' at the end of the uri, if any, so terminate parsing there */
  166. if ((ptr = strchr(s, '/'))) {
  167. *ptr = '\0';
  168. done = 1;
  169. }
  170. if (retstr) {
  171. retstr = PR_sprintf_append(retstr, "/ %s://%s", proto, s);
  172. } else {
  173. retstr = PR_smprintf("%s://%s", proto, s);
  174. }
  175. if (done) {
  176. break;
  177. }
  178. }
  179. /* add the port on the last one */
  180. retstr = PR_sprintf_append(retstr, ":%d/", port);
  181. end:
  182. slapi_ch_free_string(&my_copy);
  183. return retstr;
  184. }
  185. #endif /* USE_OPENLDAP */
  186. const char *
  187. slapi_urlparse_err2string( int err )
  188. {
  189. const char *s="internal error";
  190. switch( err ) {
  191. case 0:
  192. s = "no error";
  193. break;
  194. case LDAP_URL_ERR_BADSCOPE:
  195. s = "invalid search scope";
  196. break;
  197. case LDAP_URL_ERR_MEM:
  198. s = "unable to allocate memory";
  199. break;
  200. case LDAP_URL_ERR_PARAM:
  201. s = "bad parameter to an LDAP URL function";
  202. break;
  203. #if defined(USE_OPENLDAP)
  204. case LDAP_URL_ERR_BADSCHEME:
  205. s = "does not begin with ldap://, ldaps://, or ldapi://";
  206. break;
  207. case LDAP_URL_ERR_BADENCLOSURE:
  208. s = "missing trailing '>' in enclosure";
  209. break;
  210. case LDAP_URL_ERR_BADURL:
  211. s = "not a valid LDAP URL";
  212. break;
  213. case LDAP_URL_ERR_BADHOST:
  214. s = "hostname part of url is not valid or not given";
  215. break;
  216. case LDAP_URL_ERR_BADATTRS:
  217. s = "attribute list not formatted correctly or missing";
  218. break;
  219. case LDAP_URL_ERR_BADFILTER:
  220. s = "search filter not correct";
  221. break;
  222. case LDAP_URL_ERR_BADEXTS:
  223. s = "extensions not specified correctly";
  224. break;
  225. #else /* !USE_OPENLDAP */
  226. case LDAP_URL_ERR_NOTLDAP:
  227. s = "missing ldap:// or ldaps:// or ldapi://";
  228. break;
  229. case LDAP_URL_ERR_NODN:
  230. s = "missing suffix";
  231. break;
  232. #endif
  233. }
  234. return( s );
  235. }
  236. /* there are various differences among url parsers - directory server
  237. needs the ability to parse partial URLs - those with no dn - and
  238. needs to be able to tell if it is a secure url (ldaps) or not */
  239. int
  240. slapi_ldap_url_parse(const char *url, LDAPURLDesc **ludpp, int require_dn, int *secure)
  241. {
  242. PR_ASSERT(url);
  243. PR_ASSERT(ludpp);
  244. int rc;
  245. /* This blocks NULL getting to strlen via url_to_use later in the function. */
  246. if (url == NULL) {
  247. return LDAP_PARAM_ERROR;
  248. }
  249. const char *url_to_use = url;
  250. #if defined(USE_OPENLDAP)
  251. char *urlescaped = NULL;
  252. #endif
  253. if (secure) {
  254. *secure = 0;
  255. }
  256. #if defined(USE_OPENLDAP)
  257. /* openldap does not support the non-standard multi host:port URLs supported
  258. by mozldap - so we have to fake out openldap - replace all spaces with %20 -
  259. replace all but the last colon with %3A
  260. Go to the 3rd '/' or to the end of the string (convert only the host:port part) */
  261. if (url) {
  262. char *p = strstr(url, "://");
  263. if (p) {
  264. int foundspace = 0;
  265. int coloncount = 0;
  266. char *lastcolon = NULL;
  267. p += 3;
  268. for (; *p && (*p != '/'); p++) {
  269. if (*p == ' ') {
  270. foundspace = 1;
  271. }
  272. if (*p == ':') {
  273. coloncount++;
  274. lastcolon = p;
  275. }
  276. }
  277. if (foundspace) {
  278. char *src = NULL, *dest = NULL;
  279. /* have to convert url, len * 3 is way too much, but acceptable */
  280. urlescaped = slapi_ch_calloc(strlen(url) * 3, sizeof(char));
  281. dest = urlescaped;
  282. /* copy the scheme */
  283. src = strstr(url, "://");
  284. src += 3;
  285. memcpy(dest, url, src-url);
  286. dest += (src-url);
  287. /*
  288. * we have to convert all spaces to %20 - we have to convert
  289. * all colons except the last one to %3A
  290. */
  291. for (; *src; ++src) {
  292. if (src < p) {
  293. if (*src == ' ') {
  294. memcpy(dest, "%20", 3);
  295. dest += 3;
  296. } else if ((coloncount > 1) && (*src == ':') && (src != lastcolon)) {
  297. memcpy(dest, "%3A", 3);
  298. dest += 3;
  299. } else {
  300. *dest++ = *src;
  301. }
  302. } else {
  303. *dest++ = *src;
  304. }
  305. }
  306. *dest = '\0';
  307. url_to_use = urlescaped;
  308. }
  309. }
  310. }
  311. #endif
  312. #if defined(HAVE_LDAP_URL_PARSE_NO_DEFAULTS)
  313. rc = ldap_url_parse_no_defaults(url_to_use, ludpp, require_dn);
  314. if (!rc && *ludpp && secure) {
  315. *secure = (*ludpp)->lud_options & LDAP_URL_OPT_SECURE;
  316. }
  317. #else /* openldap */
  318. #if defined(HAVE_LDAP_URL_PARSE_EXT) && defined(LDAP_PVT_URL_PARSE_NONE) && defined(LDAP_PVT_URL_PARSE_NOEMPTY_DN)
  319. rc = ldap_url_parse_ext(url_to_use, ludpp, require_dn ? LDAP_PVT_URL_PARSE_NONE : LDAP_PVT_URL_PARSE_NOEMPTY_DN);
  320. #else
  321. rc = ldap_url_parse(url_to_use, ludpp);
  322. if ((rc || !*ludpp) && !require_dn) { /* failed - see if failure was due to missing dn */
  323. size_t len = strlen(url_to_use);
  324. /* assume the url is just scheme://host:port[/] - add the empty string
  325. as the DN (adding a trailing / first if needed) and try to parse
  326. again
  327. */
  328. char *urlcopy;
  329. if (len > 0) {
  330. urlcopy = slapi_ch_smprintf("%s%s%s", url_to_use, (url_to_use[len-1] == '/' ? "" : "/"), "");
  331. } else {
  332. /* When len == 0, this is effectively what we create ... */
  333. urlcopy = slapi_ch_smprintf("/");
  334. }
  335. if (*ludpp) {
  336. ldap_free_urldesc(*ludpp); /* free the old one, if any */
  337. }
  338. rc = ldap_url_parse(urlcopy, ludpp);
  339. slapi_ch_free_string(&urlcopy);
  340. if (0 == rc) { /* only problem was the DN - free it */
  341. slapi_ch_free_string(&((*ludpp)->lud_dn));
  342. }
  343. }
  344. #endif
  345. if (!rc && *ludpp && secure) {
  346. *secure = (*ludpp)->lud_scheme && !strcmp((*ludpp)->lud_scheme, "ldaps");
  347. }
  348. #endif /* openldap */
  349. #if defined(USE_OPENLDAP)
  350. if (urlescaped && (*ludpp) && (*ludpp)->lud_host) {
  351. /* have to unescape lud_host - can unescape in place */
  352. char *p = strstr((*ludpp)->lud_host, "://");
  353. if (p) {
  354. char *dest = NULL;
  355. p += 3;
  356. dest = p;
  357. /* up to the first '/', unescape the host */
  358. for (; *p && (*p != '/'); p++) {
  359. if (!strncmp(p, "%20", 3)) {
  360. *dest++ = ' ';
  361. p += 2;
  362. } else if (!strncmp(p, "%3A", 3)) {
  363. *dest++ = ':';
  364. p += 2;
  365. } else {
  366. *dest++ = *p;
  367. }
  368. }
  369. /* just copy the remainder of the host, if any */
  370. while (*p) {
  371. *dest++ = *p++;
  372. }
  373. *dest = '\0';
  374. }
  375. }
  376. slapi_ch_free_string(&urlescaped);
  377. #endif
  378. return rc;
  379. }
  380. #include <sasl.h>
  381. int
  382. slapi_ldap_get_lderrno(LDAP *ld, char **m, char **s)
  383. {
  384. int rc = LDAP_SUCCESS;
  385. #if defined(USE_OPENLDAP)
  386. ldap_get_option(ld, LDAP_OPT_RESULT_CODE, &rc);
  387. if (m) {
  388. ldap_get_option(ld, LDAP_OPT_MATCHED_DN, m);
  389. }
  390. if (s) {
  391. #ifdef LDAP_OPT_DIAGNOSTIC_MESSAGE
  392. ldap_get_option(ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, s);
  393. #else
  394. ldap_get_option(ld, LDAP_OPT_ERROR_STRING, s);
  395. #endif
  396. }
  397. #else /* !USE_OPENLDAP */
  398. rc = ldap_get_lderrno( ld, m, s );
  399. #endif
  400. return rc;
  401. }
  402. void
  403. slapi_ldif_put_type_and_value_with_options( char **out, const char *t, const char *val, int vlen, unsigned long options )
  404. {
  405. #if defined(USE_OPENLDAP)
  406. /* openldap always wraps and always does conservative base64 encoding
  407. we unwrap here, but clients will have to do their own base64 decode */
  408. int type = LDIF_PUT_VALUE;
  409. char *save = *out;
  410. if (options & LDIF_OPT_VALUE_IS_URL) {
  411. type = LDIF_PUT_URL;
  412. }
  413. ldif_sput( out, type, t, val, vlen );
  414. if (options & LDIF_OPT_NOWRAP) {
  415. /* modify out in place, stripping out continuation lines */
  416. char *src = save;
  417. char *dest = save;
  418. for (; src < *out; ++src) {
  419. if ((src < (*out - 2)) && !strncmp(src, "\n ", 2)) {
  420. src += 2; /* skip continuation */
  421. }
  422. *dest++ = *src;
  423. }
  424. *out = dest; /* move 'out' back if we removed some continuation lines */
  425. }
  426. #else
  427. ldif_put_type_and_value_with_options( out, (char *)t, (char *)val, vlen, options );
  428. #endif
  429. }
  430. void
  431. slapi_ldap_value_free( char **vals )
  432. {
  433. #if defined(USE_OPENLDAP)
  434. slapi_ch_array_free(vals);
  435. #else
  436. ldap_value_free(vals);
  437. #endif
  438. }
  439. int
  440. slapi_ldap_count_values( char **vals )
  441. {
  442. #if defined(USE_OPENLDAP)
  443. return ldap_count_values_len((struct berval **)vals);
  444. #else
  445. return ldap_count_values(vals);
  446. #endif
  447. }
  448. int
  449. slapi_ldap_create_proxyauth_control (
  450. LDAP *ld, /* only used to get current ber options */
  451. const char *dn, /* proxy dn */
  452. const char ctl_iscritical,
  453. int usev2, /* use the v2 (.18) control instead */
  454. LDAPControl **ctrlp /* value to return */
  455. )
  456. {
  457. int rc = 0;
  458. #if defined(USE_OPENLDAP)
  459. BerElement *ber = NULL;
  460. int beropts = 0;
  461. char *berfmtstr = NULL;
  462. char *ctrloid = NULL;
  463. struct berval *bv = NULL;
  464. /* note - there is currently no way to get the beroptions from the ld*,
  465. so we just hard code it here */
  466. beropts = LBER_USE_DER; /* openldap seems to use DER by default */
  467. if (ctrlp == NULL) {
  468. return LDAP_PARAM_ERROR;
  469. }
  470. if (NULL == dn) {
  471. dn = "";
  472. }
  473. if (NULL == (ber = ber_alloc_t(beropts))) {
  474. return LDAP_NO_MEMORY;
  475. }
  476. if (usev2) {
  477. berfmtstr = "s";
  478. ctrloid = LDAP_CONTROL_PROXIEDAUTH;
  479. } else {
  480. berfmtstr = "{s}";
  481. ctrloid = LDAP_CONTROL_PROXYAUTH;
  482. }
  483. if (LBER_ERROR == ber_printf(ber, berfmtstr, dn)) {
  484. ber_free(ber, 1);
  485. return LDAP_ENCODING_ERROR;
  486. }
  487. if (LBER_ERROR == ber_flatten(ber, &bv)) {
  488. ber_bvfree(bv);
  489. ber_free(ber, 1);
  490. return LDAP_ENCODING_ERROR;
  491. }
  492. if (NULL == bv) {
  493. ber_free(ber, 1);
  494. return LDAP_NO_MEMORY;
  495. }
  496. rc = ldap_control_create(ctrloid, ctl_iscritical, bv, 1, ctrlp);
  497. ber_bvfree(bv);
  498. ber_free(ber, 1);
  499. #else
  500. if (usev2) {
  501. rc = ldap_create_proxiedauth_control(ld, dn, ctrlp);
  502. } else {
  503. rc = ldap_create_proxyauth_control(ld, dn, ctl_iscritical, ctrlp);
  504. }
  505. #endif
  506. return rc;
  507. }
  508. int
  509. slapi_ldif_parse_line(
  510. char *line,
  511. struct berval *type,
  512. struct berval *value,
  513. int *freeval
  514. )
  515. {
  516. int rc;
  517. #if defined(USE_OPENLDAP)
  518. rc = ldif_parse_line2(line, type, value, freeval);
  519. /* check that type and value are null terminated */
  520. #else
  521. int vlen;
  522. rc = ldif_parse_line(line, &type->bv_val, &value->bv_val, &vlen);
  523. type->bv_len = type->bv_val ? strlen(type->bv_val) : 0;
  524. value->bv_len = vlen;
  525. *freeval = 0; /* always returns in place */
  526. #endif
  527. return rc;
  528. }
  529. #if defined(USE_OPENLDAP)
  530. static int
  531. setup_ol_tls_conn(LDAP *ld, int clientauth)
  532. {
  533. char *certdir = config_get_certdir();
  534. int optval = 0;
  535. int ssl_strength = 0;
  536. int rc = 0;
  537. const char *cacert = NULL;
  538. if (config_get_ssl_check_hostname()) {
  539. ssl_strength = LDAP_OPT_X_TLS_HARD;
  540. } else {
  541. /* verify certificate only */
  542. ssl_strength = LDAP_OPT_X_TLS_NEVER;
  543. }
  544. if ((rc = ldap_set_option(ld, LDAP_OPT_X_TLS_REQUIRE_CERT, &ssl_strength))) {
  545. slapi_log_error(SLAPI_LOG_FATAL, "setup_ol_tls_conn",
  546. "failed: unable to set REQUIRE_CERT option to %d\n", ssl_strength);
  547. }
  548. if (slapi_client_uses_non_nss(ld)) {
  549. cacert = slapi_get_cacertfile();
  550. if (cacert) {
  551. /* CA Cert PEM file exists. Set the path to openldap option. */
  552. rc = ldap_set_option(ld, LDAP_OPT_X_TLS_CACERTFILE, cacert);
  553. if (rc) {
  554. slapi_log_error(SLAPI_LOG_FATAL, "setup_ol_tls_conn",
  555. "Could not set CA cert path [%s]: %d:%s\n",
  556. cacert, rc, ldap_err2string(rc));
  557. }
  558. }
  559. if (slapi_client_uses_openssl(ld)) {
  560. const int crlcheck = LDAP_OPT_X_TLS_CRL_ALL;
  561. /* Sets the CRL evaluation strategy. */
  562. rc = ldap_set_option(ld, LDAP_OPT_X_TLS_CRLCHECK, &crlcheck);
  563. if (rc) {
  564. slapi_log_error(SLAPI_LOG_FATAL, "setup_ol_tls_conn",
  565. "Could not set CRLCHECK [%d]: %d:%s\n",
  566. crlcheck, rc, ldap_err2string(rc));
  567. }
  568. }
  569. }
  570. /* tell it where our cert db/file is */
  571. if ((rc = ldap_set_option(ld, LDAP_OPT_X_TLS_CACERTDIR, certdir))) {
  572. slapi_log_error(SLAPI_LOG_FATAL, "setup_ol_tls_conn",
  573. "failed: unable to set CACERTDIR option to %s\n", certdir);
  574. }
  575. slapi_ch_free_string(&certdir);
  576. #if defined(LDAP_OPT_X_TLS_PROTOCOL_MIN)
  577. getSSLVersionRangeOL(&optval, NULL);
  578. if ((rc = ldap_set_option(ld, LDAP_OPT_X_TLS_PROTOCOL_MIN, &optval))) {
  579. char *minstr = NULL;
  580. (void)getSSLVersionRange(&minstr, NULL);
  581. slapi_log_error(SLAPI_LOG_FATAL, "setup_ol_tls_conn",
  582. "failed: unable to set minimum TLS protocol level to %s\n", minstr);
  583. slapi_ch_free_string(&minstr);
  584. }
  585. #endif /* LDAP_OPT_X_TLS_PROTOCOL_MIN */
  586. if (clientauth) {
  587. rc = slapd_SSL_client_auth(ld);
  588. if (rc) {
  589. slapi_log_error(SLAPI_LOG_FATAL, "setup_ol_tls_conn",
  590. "failed: unable to setup connection for TLS/SSL EXTERNAL client cert authentication - %d\n", rc);
  591. }
  592. }
  593. /* have to do this last - this creates the new TLS handle and sets/copies
  594. all of the parameters set above into that TLS handle context - note
  595. that optval is zero, meaning create a context for a client */
  596. optval = 0;
  597. if ((rc = ldap_set_option(ld, LDAP_OPT_X_TLS_NEWCTX, &optval))) {
  598. slapi_log_error(SLAPI_LOG_FATAL, "setup_ol_tls_conn",
  599. "failed: unable to create new TLS context - %d\n", rc);
  600. }
  601. return rc;
  602. }
  603. #endif /* defined(USE_OPENLDAP) */
  604. /*
  605. Perform LDAP init and return an LDAP* handle. If ldapurl is given,
  606. that is used as the basis for the protocol, host, port, and whether
  607. to use starttls (given on the end as ldap://..../?????starttlsOID
  608. If hostname is given, LDAP or LDAPS is assumed, and this will override
  609. the hostname from the ldapurl, if any. If port is > 0, this is the
  610. port number to use. It will override the port in the ldapurl, if any.
  611. If no port is given in port or ldapurl, the default will be used based
  612. on the secure setting (389 for ldap, 636 for ldaps, 389 for starttls)
  613. secure takes 1 of 3 values - 0 means regular ldap, 1 means ldaps, 2
  614. means regular ldap with starttls.
  615. ldapi_socket is the ldapi file name
  616. if this is given, and no other options are given, ldapi is assumed.
  617. */
  618. /* util_sasl_path: the string argument for putenv.
  619. It must be a global or a static */
  620. char util_sasl_path[MAXPATHLEN];
  621. LDAP *
  622. slapi_ldap_init_ext(
  623. const char *ldapurl, /* full ldap url */
  624. const char *hostname, /* can also use this to override
  625. host in url */
  626. int port, /* can also use this to override port in url */
  627. int secure, /* 0 for ldap, 1 for ldaps, 2 for starttls -
  628. override proto in url */
  629. int shared, /* if true, LDAP* will be shared among multiple threads */
  630. const char *ldapi_socket /* for ldapi */
  631. )
  632. {
  633. LDAPURLDesc *ludp = NULL;
  634. LDAP *ld = NULL;
  635. int rc = 0;
  636. int secureurl = 0;
  637. int ldap_version3 = LDAP_VERSION3;
  638. /* We need to provide a sasl path used for client connections, especially
  639. if the server is not set up to be a sasl server - since mozldap provides
  640. no way to override the default path programatically, we set the sasl
  641. path to the environment variable SASL_PATH. */
  642. char *configpluginpath = config_get_saslpath();
  643. char *pluginpath = configpluginpath;
  644. char *pp = NULL;
  645. if (NULL == pluginpath || (*pluginpath == '\0')) {
  646. slapi_log_error(SLAPI_LOG_SHELL, "slapi_ldap_init_ext",
  647. "config_get_saslpath returns NULL\n");
  648. pluginpath = ldaputil_get_saslpath();
  649. }
  650. if ('\0' == util_sasl_path[0] || /* first time */
  651. NULL == (pp = strchr(util_sasl_path, '=')) || /* invalid arg for putenv */
  652. (0 != strcmp(++pp, pluginpath)) /* sasl_path has been updated */ )
  653. {
  654. PR_snprintf(util_sasl_path, sizeof(util_sasl_path), "SASL_PATH=%s", pluginpath);
  655. slapi_log_error(SLAPI_LOG_SHELL, "slapi_ldap_init_ext", "putenv(%s)\n", util_sasl_path);
  656. putenv(util_sasl_path);
  657. }
  658. slapi_ch_free_string(&configpluginpath);
  659. /* if ldapurl is given, parse it */
  660. if (ldapurl && ((rc = slapi_ldap_url_parse(ldapurl, &ludp, 0, &secureurl)) || !ludp)) {
  661. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_init_ext",
  662. "Could not parse given LDAP URL [%s] : error [%s]\n",
  663. ldapurl, /* ldapurl cannot be NULL here */
  664. slapi_urlparse_err2string(rc));
  665. goto done;
  666. }
  667. /* use url host if no host given */
  668. if (!hostname && ludp && ludp->lud_host) {
  669. hostname = ludp->lud_host;
  670. }
  671. /* use url port if no port given */
  672. if (!port && ludp && ludp->lud_port) {
  673. port = ludp->lud_port;
  674. }
  675. /* use secure setting from url if none given */
  676. if (!secure && ludp) {
  677. if (secureurl) {
  678. secure = SLAPI_LDAP_INIT_FLAG_SSL;
  679. } else if (0/* starttls option - not supported yet in LDAP URLs */) {
  680. secure = SLAPI_LDAP_INIT_FLAG_startTLS;
  681. }
  682. }
  683. /* ldap_url_parse doesn't yet handle ldapi */
  684. /*
  685. if (!ldapi_socket && ludp && ludp->lud_file) {
  686. ldapi_socket = ludp->lud_file;
  687. }
  688. */
  689. #ifdef MEMPOOL_EXPERIMENTAL
  690. {
  691. /*
  692. * slapi_ch_malloc functions need to be set to LDAP C SDK
  693. */
  694. struct ldap_memalloc_fns memalloc_fns;
  695. memalloc_fns.ldapmem_malloc = (LDAP_MALLOC_CALLBACK *)slapi_ch_malloc;
  696. memalloc_fns.ldapmem_calloc = (LDAP_CALLOC_CALLBACK *)slapi_ch_calloc;
  697. memalloc_fns.ldapmem_realloc = (LDAP_REALLOC_CALLBACK *)slapi_ch_realloc;
  698. memalloc_fns.ldapmem_free = (LDAP_FREE_CALLBACK *)_free_wrapper;
  699. }
  700. /*
  701. * MEMPOOL_EXPERIMENTAL:
  702. * These LDAP C SDK init function needs to be revisited.
  703. * In ldap_init called via ldapssl_init and prldap_init initializes
  704. * options and set default values including memalloc_fns, then it
  705. * initializes as sasl client by calling sasl_client_init. In
  706. * sasl_client_init, it creates mechlist using the malloc function
  707. * available at the moment which could mismatch the malloc/free functions
  708. * set later.
  709. */
  710. #endif
  711. #if defined(USE_OPENLDAP)
  712. if (ldapurl) {
  713. if (PR_SUCCESS != PR_CallOnce(&ol_init_callOnce, internal_ol_init_init)) {
  714. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_init_ext",
  715. "Could not perform internal ol_init init\n");
  716. rc = -1;
  717. goto done;
  718. }
  719. PR_Lock(ol_init_lock);
  720. rc = ldap_initialize(&ld, ldapurl);
  721. PR_Unlock(ol_init_lock);
  722. if (rc) {
  723. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_init_ext",
  724. "Could not initialize LDAP connection to [%s]: %d:%s\n",
  725. ldapurl, rc, ldap_err2string(rc));
  726. goto done;
  727. }
  728. } else {
  729. char *makeurl = NULL;
  730. if (ldapi_socket) {
  731. makeurl = slapi_ch_smprintf("ldapi://%s/", ldapi_socket);
  732. } else { /* host port */
  733. makeurl = convert_to_openldap_uri(hostname, port,
  734. (secure == SLAPI_LDAP_INIT_FLAG_SSL ? "ldaps" : "ldap"));
  735. }
  736. if (PR_SUCCESS != PR_CallOnce(&ol_init_callOnce, internal_ol_init_init)) {
  737. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_init_ext",
  738. "Could not perform internal ol_init init\n");
  739. rc = -1;
  740. goto done;
  741. }
  742. PR_Lock(ol_init_lock);
  743. rc = ldap_initialize(&ld, makeurl);
  744. PR_Unlock(ol_init_lock);
  745. if (rc) {
  746. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_init_ext",
  747. "Could not initialize LDAP connection to [%s]: %d:%s\n",
  748. makeurl, rc, ldap_err2string(rc));
  749. slapi_ch_free_string(&makeurl);
  750. goto done;
  751. }
  752. slapi_ch_free_string(&makeurl);
  753. }
  754. if(config_get_connection_nocanon()){
  755. /*
  756. * The NONCANON flag tells openldap to use the hostname specified in
  757. * the ldap_initialize command, rather than looking up the
  758. * hostname using gethostname or similar - this allows running
  759. * sasl/gssapi tests on machines that don't have a canonical
  760. * hostname (such as localhost.localdomain).
  761. */
  762. if((rc = ldap_set_option(ld, LDAP_OPT_X_SASL_NOCANON, LDAP_OPT_ON))){
  763. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_init_ext",
  764. "Could not set ldap option LDAP_OPT_X_SASL_NOCANON for (%s), error %d (%s)\n",
  765. ldapurl, rc, ldap_err2string(rc) );
  766. }
  767. }
  768. #else /* !USE_OPENLDAP */
  769. if (ldapi_socket) {
  770. /* ldapi in mozldap client is not yet supported */
  771. } else if (secure == SLAPI_LDAP_INIT_FLAG_SSL) {
  772. ld = ldapssl_init(hostname, port, secure);
  773. } else { /* regular ldap and/or starttls */
  774. /*
  775. * Leverage the libprldap layer to take care of all the NSPR
  776. * integration.
  777. * Note that ldapssl_init() uses libprldap implicitly.
  778. */
  779. ld = prldap_init(hostname, port, shared);
  780. }
  781. #endif /* !USE_OPENLDAP */
  782. /* must explicitly set version to 3 */
  783. ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &ldap_version3);
  784. /* Update snmp interaction table */
  785. if (hostname) {
  786. if (ld == NULL) {
  787. set_snmp_interaction_row((char *)hostname, port, -1);
  788. } else {
  789. set_snmp_interaction_row((char *)hostname, port, 0);
  790. }
  791. }
  792. if (ld && !ldapi_socket) {
  793. /*
  794. * Set the outbound LDAP I/O timeout based on the server config.
  795. */
  796. int io_timeout_ms = config_get_outbound_ldap_io_timeout();
  797. if (io_timeout_ms > 0) {
  798. #if defined(USE_OPENLDAP)
  799. struct timeval tv;
  800. tv.tv_sec = io_timeout_ms / 1000;
  801. tv.tv_usec = (io_timeout_ms % 1000) * 1000;
  802. if (LDAP_OPT_SUCCESS != ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &tv)) {
  803. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_init_ext",
  804. "failed: unable to set outbound I/O timeout to %dms\n", io_timeout_ms);
  805. slapi_ldap_unbind(ld);
  806. ld = NULL;
  807. goto done;
  808. }
  809. #else /* !USE_OPENLDAP */
  810. if (prldap_set_session_option(ld, NULL, PRLDAP_OPT_IO_MAX_TIMEOUT, io_timeout_ms) != LDAP_SUCCESS) {
  811. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_init_ext",
  812. "failed: unable to set outbound I/O timeout to %dms\n", io_timeout_ms);
  813. slapi_ldap_unbind(ld);
  814. ld = NULL;
  815. goto done;
  816. }
  817. #endif /* !USE_OPENLDAP */
  818. }
  819. /*
  820. * Set SSL strength (server certificate validity checking).
  821. */
  822. if (secure > 0) {
  823. #if defined(USE_OPENLDAP)
  824. if (setup_ol_tls_conn(ld, 0)) {
  825. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_init_ext",
  826. "failed: unable to set SSL/TLS options\n");
  827. }
  828. #else
  829. int ssl_strength = 0;
  830. LDAP *myld = NULL;
  831. /*
  832. * We can only use the set functions below with a real
  833. * LDAP* if it has already gone through ldapssl_init -
  834. * so, use NULL if using starttls
  835. */
  836. if (secure == SLAPI_LDAP_INIT_FLAG_SSL) {
  837. myld = ld;
  838. }
  839. if (config_get_ssl_check_hostname()) {
  840. /* check hostname against name in certificate */
  841. ssl_strength = LDAPSSL_AUTH_CNCHECK;
  842. } else {
  843. /* verify certificate only */
  844. ssl_strength = LDAPSSL_AUTH_CERT;
  845. }
  846. if ((rc = ldapssl_set_strength(myld, ssl_strength)) ||
  847. (rc = ldapssl_set_option(myld, SSL_ENABLE_SSL2, PR_FALSE)) ||
  848. (rc = ldapssl_set_option(myld, SSL_ENABLE_SSL3, PR_TRUE)) ||
  849. (rc = ldapssl_set_option(myld, SSL_ENABLE_TLS, PR_TRUE)))
  850. {
  851. int prerr = PR_GetError();
  852. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_init_ext",
  853. "failed: unable to set SSL options ("
  854. SLAPI_COMPONENT_NAME_NSPR " error %d - %s)\n",
  855. prerr, slapd_pr_strerror(prerr));
  856. }
  857. if (secure == SLAPI_LDAP_INIT_FLAG_SSL) {
  858. /* tell bind code we are using SSL */
  859. ldap_set_option(ld, LDAP_OPT_SSL, LDAP_OPT_ON);
  860. }
  861. #endif /* !USE_OPENLDAP */
  862. }
  863. }
  864. if (ld && (secure == SLAPI_LDAP_INIT_FLAG_startTLS)) {
  865. /*
  866. * We don't have a way to stash context data with the LDAP*, so we
  867. * stash the information in the client controls (currently unused).
  868. * We don't want to open the connection in ldap_init, since that's
  869. * not the semantic - the connection is not usually opened until
  870. * the first operation is sent, which is usually the bind - or
  871. * in this case, the start_tls - so we stash the start_tls so
  872. * we can do it in slapi_ldap_bind - note that this will get
  873. * cleaned up when the LDAP* is disposed of
  874. */
  875. LDAPControl start_tls_dummy_ctrl;
  876. LDAPControl **clientctrls = NULL;
  877. /* returns copy of controls */
  878. ldap_get_option(ld, LDAP_OPT_CLIENT_CONTROLS, &clientctrls);
  879. start_tls_dummy_ctrl.ldctl_oid = START_TLS_OID;
  880. start_tls_dummy_ctrl.ldctl_value.bv_val = NULL;
  881. start_tls_dummy_ctrl.ldctl_value.bv_len = 0;
  882. start_tls_dummy_ctrl.ldctl_iscritical = 0;
  883. slapi_add_control_ext(&clientctrls, &start_tls_dummy_ctrl, 1);
  884. /* set option frees old list and copies the new list */
  885. ldap_set_option(ld, LDAP_OPT_CLIENT_CONTROLS, clientctrls);
  886. ldap_controls_free(clientctrls); /* free the copy */
  887. }
  888. slapi_log_error(SLAPI_LOG_SHELL, "slapi_ldap_init_ext",
  889. "Success: set up conn to [%s:%d]%s\n",
  890. hostname, port,
  891. (secure == SLAPI_LDAP_INIT_FLAG_startTLS) ? " using startTLS" :
  892. ((secure == SLAPI_LDAP_INIT_FLAG_SSL) ? " using SSL" : ""));
  893. done:
  894. ldap_free_urldesc(ludp);
  895. return( ld );
  896. }
  897. char *
  898. ldaputil_get_saslpath()
  899. {
  900. char *saslpath = getenv("SASL_PATH");
  901. if (NULL == saslpath) {
  902. #if defined(LINUX) && defined(__LP64__)
  903. saslpath = "/usr/lib64/sasl2";
  904. if (PR_SUCCESS != PR_Access(saslpath, PR_ACCESS_EXISTS)) {
  905. #ifdef CPU_arm
  906. /* the 64-bit ARMv8 architecture. */
  907. saslpath = "/usr/lib/aarch64-linux-gnu";
  908. #else
  909. /* Try x86_64 gnu triplet */
  910. saslpath = "/usr/lib/x86_64-linux-gnu";
  911. #endif
  912. }
  913. #else
  914. saslpath = "/usr/lib/sasl2";
  915. if (PR_SUCCESS != PR_Access(saslpath, PR_ACCESS_EXISTS)) {
  916. #ifdef CPU_arm
  917. /* the latest 32 bit ARM architecture using the hard-float version of EABI. */
  918. saslpath = "/usr/lib/arm-linux-gnueabihf";
  919. if (PR_SUCCESS != PR_Access(saslpath, PR_ACCESS_EXISTS)) {
  920. /* the 32 bit ARM architecture of EABI. */
  921. saslpath = "/usr/lib/arm-linux-gnueabi";
  922. }
  923. #else
  924. /* Try i386 gnu triplet */
  925. saslpath = "/usr/lib/i386-linux-gnu";
  926. #endif
  927. }
  928. #endif
  929. }
  930. return saslpath;
  931. }
  932. /*
  933. * Function: slapi_ldap_init()
  934. * Description: just like ldap_ssl_init() but also arranges for the LDAP
  935. * session handle returned to be safely shareable by multiple threads
  936. * if "shared" is non-zero.
  937. * Returns:
  938. * an LDAP session handle (NULL if some local error occurs).
  939. */
  940. LDAP *
  941. slapi_ldap_init( char *ldaphost, int ldapport, int secure, int shared )
  942. {
  943. return slapi_ldap_init_ext(NULL, ldaphost, ldapport, secure, shared, NULL/*, NULL*/);
  944. }
  945. /*
  946. * Does the correct bind operation simple/sasl/cert depending
  947. * on the arguments passed in. If the user specified to use
  948. * starttls in init, this will do the starttls first. If using
  949. * ssl or client cert auth, this will initialize the client side
  950. * of that.
  951. */
  952. int
  953. slapi_ldap_bind(
  954. LDAP *ld, /* ldap connection */
  955. const char *bindid, /* usually a bind DN for simple bind */
  956. const char *creds, /* usually a password for simple bind */
  957. const char *mech, /* name of mechanism */
  958. LDAPControl **serverctrls, /* additional controls to send */
  959. LDAPControl ***returnedctrls, /* returned controls */
  960. struct timeval *timeout, /* timeout */
  961. int *msgidp /* pass in non-NULL for async handling */
  962. )
  963. {
  964. int rc = LDAP_SUCCESS;
  965. int err;
  966. LDAPControl **clientctrls = NULL;
  967. int secure = 0;
  968. struct berval bvcreds = {0, NULL};
  969. LDAPMessage *result = NULL;
  970. struct berval *servercredp = NULL;
  971. /* do starttls if requested
  972. NOTE - starttls is an extop, not a control, but we don't have
  973. a place we can stash this information in the LDAP*, other
  974. than the currently unused clientctrls */
  975. ldap_get_option(ld, LDAP_OPT_CLIENT_CONTROLS, &clientctrls);
  976. if (clientctrls && clientctrls[0] &&
  977. slapi_control_present(clientctrls, START_TLS_OID, NULL, NULL)) {
  978. secure = SLAPI_LDAP_INIT_FLAG_startTLS;
  979. } else {
  980. #if defined(USE_OPENLDAP)
  981. /* openldap doesn't have a SSL/TLS yes/no flag - so grab the
  982. ldapurl, parse it, and see if it is a secure one */
  983. char *ldapurl = NULL;
  984. ldap_get_option(ld, LDAP_OPT_URI, &ldapurl);
  985. if (ldapurl && !PL_strncasecmp(ldapurl, "ldaps", 5)) {
  986. secure = SLAPI_LDAP_INIT_FLAG_SSL;
  987. }
  988. slapi_ch_free_string(&ldapurl);
  989. #else /* !USE_OPENLDAP */
  990. ldap_get_option(ld, LDAP_OPT_SSL, &secure);
  991. #endif
  992. }
  993. ldap_controls_free(clientctrls);
  994. ldap_set_option(ld, LDAP_OPT_CLIENT_CONTROLS, NULL);
  995. if ((secure > 0) && mech && !strcmp(mech, LDAP_SASL_EXTERNAL)) {
  996. #if defined(USE_OPENLDAP)
  997. /* we already set up a tls context in slapi_ldap_init_ext() - this will
  998. free those old settings and context and create a new one */
  999. rc = setup_ol_tls_conn(ld, 1);
  1000. #else
  1001. /* SSL connections will use the server's security context
  1002. and cert for client auth */
  1003. rc = slapd_SSL_client_auth(ld);
  1004. #endif
  1005. if (rc != 0) {
  1006. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  1007. "Error: could not configure the server for cert "
  1008. "auth - error %d - make sure the server is "
  1009. "correctly configured for SSL/TLS\n", rc);
  1010. goto done;
  1011. } else {
  1012. slapi_log_error(SLAPI_LOG_SHELL, "slapi_ldap_bind",
  1013. "Set up conn to use client auth\n");
  1014. }
  1015. bvcreds.bv_val = NULL; /* ignore username and passed in creds */
  1016. bvcreds.bv_len = 0; /* for external auth */
  1017. bindid = NULL;
  1018. } else { /* other type of auth */
  1019. bvcreds.bv_val = (char *)creds;
  1020. bvcreds.bv_len = creds ? strlen(creds) : 0;
  1021. }
  1022. if (secure == SLAPI_LDAP_INIT_FLAG_startTLS) { /* send start tls */
  1023. rc = ldap_start_tls_s(ld, NULL /* serverctrls?? */, NULL);
  1024. if (LDAP_SUCCESS != rc) {
  1025. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  1026. "Error: could not send startTLS request: "
  1027. "error %d (%s) errno %d (%s)\n",
  1028. rc, ldap_err2string(rc), errno, slapd_system_strerror(errno));
  1029. goto done;
  1030. }
  1031. slapi_log_error(SLAPI_LOG_SHELL, "slapi_ldap_bind",
  1032. "startTLS started on connection\n");
  1033. }
  1034. /* The connection has been set up - now do the actual bind, depending on
  1035. the mechanism and arguments */
  1036. if (!mech || (mech == LDAP_SASL_SIMPLE) ||
  1037. !strcmp(mech, LDAP_SASL_EXTERNAL)) {
  1038. int mymsgid = 0;
  1039. slapi_log_error(SLAPI_LOG_SHELL, "slapi_ldap_bind",
  1040. "attempting %s bind with id [%s] creds [%s]\n",
  1041. mech ? mech : "SIMPLE",
  1042. bindid, creds);
  1043. if ((rc = ldap_sasl_bind(ld, bindid, mech, &bvcreds, serverctrls,
  1044. NULL /* clientctrls */, &mymsgid))) {
  1045. char *hostname = NULL;
  1046. char *host_port = NULL;
  1047. char *ptr = NULL;
  1048. int myerrno = errno;
  1049. int gaierr = 0;
  1050. ldap_get_option(ld, LDAP_OPT_HOST_NAME, &host_port);
  1051. if (host_port) {
  1052. ptr = strchr(host_port, ':');
  1053. if (ptr) {
  1054. hostname = slapi_ch_strdup(host_port);
  1055. *(hostname + (ptr - host_port)) = '\0';
  1056. }
  1057. }
  1058. if (0 == myerrno) {
  1059. struct addrinfo *result = NULL;
  1060. gaierr = getaddrinfo(hostname, NULL, NULL, &result);
  1061. myerrno = errno;
  1062. if (result) {
  1063. freeaddrinfo(result);
  1064. }
  1065. }
  1066. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  1067. "Error: could not send bind request for id "
  1068. "[%s] authentication mechanism [%s]: error %d (%s), system error %d (%s), "
  1069. "network error %d (%s, host \"%s\")\n",
  1070. bindid ? bindid : "(anon)",
  1071. mech ? mech : "SIMPLE",
  1072. rc, ldap_err2string(rc),
  1073. PR_GetError(), slapd_pr_strerror(PR_GetError()),
  1074. myerrno ? myerrno : gaierr,
  1075. myerrno ? slapd_system_strerror(myerrno) : gai_strerror(gaierr),
  1076. host_port ? host_port : "unknown host");
  1077. slapi_ch_free_string(&hostname);
  1078. slapi_ch_free_string(&host_port);
  1079. goto done;
  1080. }
  1081. if (msgidp) { /* let caller process result */
  1082. *msgidp = mymsgid;
  1083. } else { /* process results */
  1084. struct timeval default_timeout, *bind_timeout;
  1085. if ((timeout == NULL) || ((timeout->tv_sec == 0) && (timeout->tv_usec == 0))) {
  1086. /* Let's wait 1 min max to bind */
  1087. default_timeout.tv_sec = 60;
  1088. default_timeout.tv_usec = 0;
  1089. bind_timeout = &default_timeout;
  1090. } else {
  1091. /* take the one provided by the caller. It should be the one defined in the protocol */
  1092. bind_timeout = timeout;
  1093. }
  1094. rc = ldap_result(ld, mymsgid, LDAP_MSG_ALL, bind_timeout, &result);
  1095. if (-1 == rc) { /* error */
  1096. rc = slapi_ldap_get_lderrno(ld, NULL, NULL);
  1097. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  1098. "Error reading bind response for id "
  1099. "[%s] authentication mechanism [%s]: error %d (%s) errno %d (%s)\n",
  1100. bindid ? bindid : "(anon)",
  1101. mech ? mech : "SIMPLE",
  1102. rc, ldap_err2string(rc), errno, slapd_system_strerror(errno));
  1103. goto done;
  1104. } else if (rc == 0) { /* timeout */
  1105. rc = LDAP_TIMEOUT;
  1106. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  1107. "Error: timeout after [%ld.%ld] seconds reading "
  1108. "bind response for [%s] authentication mechanism [%s]\n",
  1109. bind_timeout->tv_sec, bind_timeout->tv_usec,
  1110. bindid ? bindid : "(anon)",
  1111. mech ? mech : "SIMPLE");
  1112. goto done;
  1113. }
  1114. /* if we got here, we were able to read success result */
  1115. /* Get the controls sent by the server if requested */
  1116. if ((rc = ldap_parse_result(ld, result, &err, NULL, NULL,
  1117. NULL, returnedctrls, 0)) != LDAP_SUCCESS) {
  1118. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  1119. "Error: could not parse bind result: error %d (%s) errno %d (%s)\n",
  1120. rc, ldap_err2string(rc), errno, slapd_system_strerror(errno));
  1121. goto done;
  1122. }
  1123. /* check the result code from the bind operation */
  1124. if(err){
  1125. rc = err;
  1126. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  1127. "Error: could not bind id "
  1128. "[%s] authentication mechanism [%s]: error %d (%s) errno %d (%s)\n",
  1129. bindid ? bindid : "(anon)",
  1130. mech ? mech : "SIMPLE",
  1131. rc, ldap_err2string(rc), errno, slapd_system_strerror(errno));
  1132. goto done;
  1133. }
  1134. /* parse the bind result and get the ldap error code */
  1135. if ((rc = ldap_parse_sasl_bind_result(ld, result, &servercredp,
  1136. 0))) {
  1137. rc = slapi_ldap_get_lderrno(ld, NULL, NULL);
  1138. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  1139. "Error: could not read bind results for id "
  1140. "[%s] authentication mechanism [%s]: error %d (%s) errno %d (%s)\n",
  1141. bindid ? bindid : "(anon)",
  1142. mech ? mech : "SIMPLE",
  1143. rc, ldap_err2string(rc), errno, slapd_system_strerror(errno));
  1144. goto done;
  1145. }
  1146. }
  1147. } else {
  1148. /* a SASL mech - set the sasl ssf to 0 if using TLS/SSL */
  1149. /* openldap supports tls + sasl security */
  1150. #if !defined(USE_OPENLDAP)
  1151. if (secure) {
  1152. sasl_ssf_t max_ssf = 0;
  1153. ldap_set_option(ld, LDAP_OPT_X_SASL_SSF_MAX, &max_ssf);
  1154. }
  1155. #endif
  1156. rc = slapd_ldap_sasl_interactive_bind(ld, bindid, creds, mech,
  1157. serverctrls, returnedctrls,
  1158. msgidp);
  1159. if (LDAP_SUCCESS != rc) {
  1160. slapi_log_error(SLAPI_LOG_CONNS, "slapi_ldap_bind",
  1161. "Error: could not perform interactive bind for id "
  1162. "[%s] authentication mechanism [%s]: error %d (%s)\n",
  1163. bindid ? bindid : "(anon)",
  1164. mech, /* mech cannot be SIMPLE here */
  1165. rc, ldap_err2string(rc));
  1166. #ifdef HAVE_KRB5
  1167. if(mech && !strcmp(mech, "GSSAPI") && rc == 49){
  1168. /* only on err 49 should we clear out the credential cache */
  1169. clear_krb5_ccache();
  1170. }
  1171. #endif
  1172. }
  1173. }
  1174. done:
  1175. slapi_ch_bvfree(&servercredp);
  1176. ldap_msgfree(result);
  1177. return rc;
  1178. }
  1179. char **
  1180. slapi_ldap_explode_rdn(const char *rdn, int notypes)
  1181. {
  1182. return mozldap_ldap_explode_rdn(rdn, notypes);
  1183. }
  1184. char **
  1185. slapi_ldap_explode_dn(const char *dn, int notypes)
  1186. {
  1187. return mozldap_ldap_explode_dn(dn, notypes);
  1188. }
  1189. void
  1190. slapi_add_auth_response_control( Slapi_PBlock *pb, const char *binddn )
  1191. {
  1192. LDAPControl arctrl;
  1193. char dnbuf_fixedsize[ 512 ], *dnbuf, *dnbuf_dynamic = NULL;
  1194. size_t dnlen;
  1195. if ( NULL == binddn ) {
  1196. binddn = "";
  1197. }
  1198. dnlen = strlen( binddn );
  1199. /*
  1200. * According to draft-weltman-ldapv3-auth-response-03.txt section
  1201. * 4 (Authentication Response Control):
  1202. *
  1203. * The controlType is "2.16.840.1.113730.3.4.15". If the bind request
  1204. * succeeded and resulted in an identity (not anonymous), the
  1205. * controlValue contains the authorization identity [AUTH] granted to
  1206. * the requestor. If the bind request resulted in anonymous
  1207. * authentication, the controlValue field is a string of zero length.
  1208. *
  1209. * [AUTH] is a reference to RFC 2829, which in section 9 defines
  1210. * authorization identity as:
  1211. *
  1212. *
  1213. * The authorization identity is a string in the UTF-8 character set,
  1214. * corresponding to the following ABNF [7]:
  1215. *
  1216. * ; Specific predefined authorization (authz) id schemes are
  1217. * ; defined below -- new schemes may be defined in the future.
  1218. *
  1219. * authzId = dnAuthzId / uAuthzId
  1220. *
  1221. * ; distinguished-name-based authz id.
  1222. * dnAuthzId = "dn:" dn
  1223. * dn = utf8string ; with syntax defined in RFC 2253
  1224. *
  1225. * ; unspecified userid, UTF-8 encoded.
  1226. * uAuthzId = "u:" userid
  1227. * userid = utf8string ; syntax unspecified
  1228. *
  1229. * A utf8string is defined to be the UTF-8 encoding of one or more ISO
  1230. * 10646 characters.
  1231. *
  1232. * We always map identities to DNs, so we always use the dnAuthzId form.
  1233. */
  1234. arctrl.ldctl_oid = LDAP_CONTROL_AUTH_RESPONSE;
  1235. arctrl.ldctl_iscritical = 0;
  1236. if ( dnlen == 0 ) { /* anonymous -- return zero length value */
  1237. arctrl.ldctl_value.bv_val = "";
  1238. arctrl.ldctl_value.bv_len = 0;
  1239. } else { /* mapped to a DN -- return "dn:<DN>" */
  1240. if ( 3 + dnlen < sizeof( dnbuf_fixedsize )) {
  1241. dnbuf = dnbuf_fixedsize;
  1242. } else {
  1243. dnbuf = dnbuf_dynamic = slapi_ch_malloc( 4 + dnlen );
  1244. }
  1245. strcpy( dnbuf, "dn:" );
  1246. strcpy( dnbuf + 3, binddn );
  1247. arctrl.ldctl_value.bv_val = dnbuf;
  1248. arctrl.ldctl_value.bv_len = 3 + dnlen;
  1249. }
  1250. if ( slapi_pblock_set( pb, SLAPI_ADD_RESCONTROL, &arctrl ) != 0 ) {
  1251. slapi_log_error( SLAPI_LOG_FATAL, "bind",
  1252. "unable to add authentication response control" );
  1253. }
  1254. if ( NULL != dnbuf_dynamic ) {
  1255. slapi_ch_free_string( &dnbuf_dynamic );
  1256. }
  1257. }
  1258. /* the following implements the client side of sasl bind, for LDAP server
  1259. -> LDAP server SASL */
  1260. typedef struct {
  1261. char *mech;
  1262. char *authid;
  1263. char *username;
  1264. char *passwd;
  1265. char *realm;
  1266. } ldapSaslInteractVals;
  1267. #ifdef HAVE_KRB5
  1268. static void set_krb5_creds(
  1269. const char *authid,
  1270. const char *username,
  1271. const char *passwd,
  1272. const char *realm,
  1273. ldapSaslInteractVals *vals
  1274. );
  1275. #endif
  1276. static void *
  1277. ldap_sasl_set_interact_vals(LDAP *ld, const char *mech, const char *authid,
  1278. const char *username, const char *passwd,
  1279. const char *realm)
  1280. {
  1281. ldapSaslInteractVals *vals = NULL;
  1282. char *idprefix = "";
  1283. vals = (ldapSaslInteractVals *)
  1284. slapi_ch_calloc(1, sizeof(ldapSaslInteractVals));
  1285. if (!vals) {
  1286. return NULL;
  1287. }
  1288. if (mech) {
  1289. vals->mech = slapi_ch_strdup(mech);
  1290. } else {
  1291. ldap_get_option(ld, LDAP_OPT_X_SASL_MECH, &vals->mech);
  1292. }
  1293. if (vals->mech && !strcasecmp(vals->mech, "DIGEST-MD5")) {
  1294. idprefix = "dn:"; /* prefix name and id with this string */
  1295. }
  1296. if (authid) { /* use explicit passed in value */
  1297. vals->authid = slapi_ch_smprintf("%s%s", idprefix, authid);
  1298. } else { /* use option value if any */
  1299. ldap_get_option(ld, LDAP_OPT_X_SASL_AUTHCID, &vals->authid);
  1300. if (!vals->authid) {
  1301. /* get server user id? */
  1302. vals->authid = slapi_ch_strdup("");
  1303. }
  1304. }
  1305. if (username) { /* use explicit passed in value */
  1306. vals->username = slapi_ch_smprintf("%s%s", idprefix, username);
  1307. } else { /* use option value if any */
  1308. ldap_get_option(ld, LDAP_OPT_X_SASL_AUTHZID, &vals->username);
  1309. if (!vals->username) { /* use default sasl value */
  1310. vals->username = slapi_ch_strdup("");
  1311. }
  1312. }
  1313. if (passwd) {
  1314. vals->passwd = slapi_ch_strdup(passwd);
  1315. } else {
  1316. vals->passwd = slapi_ch_strdup("");
  1317. }
  1318. if (realm) {
  1319. vals->realm = slapi_ch_strdup(realm);
  1320. } else {
  1321. ldap_get_option(ld, LDAP_OPT_X_SASL_REALM, &vals->realm);
  1322. if (!vals->realm) { /* use default sasl value */
  1323. vals->realm = slapi_ch_strdup("");
  1324. }
  1325. }
  1326. #ifdef HAVE_KRB5
  1327. if (mech && !strcmp(mech, "GSSAPI")) {
  1328. set_krb5_creds(authid, username, passwd, realm, vals);
  1329. }
  1330. #endif /* HAVE_KRB5 */
  1331. return vals;
  1332. }
  1333. static void
  1334. ldap_sasl_free_interact_vals(void *defaults)
  1335. {
  1336. ldapSaslInteractVals *vals = defaults;
  1337. if (vals) {
  1338. slapi_ch_free_string(&vals->mech);
  1339. slapi_ch_free_string(&vals->authid);
  1340. slapi_ch_free_string(&vals->username);
  1341. slapi_ch_free_string(&vals->passwd);
  1342. slapi_ch_free_string(&vals->realm);
  1343. slapi_ch_free(&defaults);
  1344. }
  1345. }
  1346. static int
  1347. ldap_sasl_get_val(ldapSaslInteractVals *vals, sasl_interact_t *interact, unsigned flags)
  1348. {
  1349. const char *defvalue = interact->defresult;
  1350. int authtracelevel = SLAPI_LOG_SHELL; /* special auth tracing */
  1351. if (vals != NULL) {
  1352. switch(interact->id) {
  1353. case SASL_CB_AUTHNAME:
  1354. defvalue = vals->authid;
  1355. slapi_log_error(authtracelevel, "ldap_sasl_get_val",
  1356. "Using value [%s] for SASL_CB_AUTHNAME\n",
  1357. defvalue ? defvalue : "(null)");
  1358. break;
  1359. case SASL_CB_USER:
  1360. defvalue = vals->username;
  1361. slapi_log_error(authtracelevel, "ldap_sasl_get_val",
  1362. "Using value [%s] for SASL_CB_USER\n",
  1363. defvalue ? defvalue : "(null)");
  1364. break;
  1365. case SASL_CB_PASS:
  1366. defvalue = vals->passwd;
  1367. slapi_log_error(authtracelevel, "ldap_sasl_get_val",
  1368. "Using value [%s] for SASL_CB_PASS\n",
  1369. defvalue ? defvalue : "(null)");
  1370. break;
  1371. case SASL_CB_GETREALM:
  1372. defvalue = vals->realm;
  1373. slapi_log_error(authtracelevel, "ldap_sasl_get_val",
  1374. "Using value [%s] for SASL_CB_GETREALM\n",
  1375. defvalue ? defvalue : "(null)");
  1376. break;
  1377. }
  1378. }
  1379. if (defvalue != NULL) {
  1380. interact->result = defvalue;
  1381. if ((char *)interact->result == NULL)
  1382. return (LDAP_NO_MEMORY);
  1383. interact->len = strlen((char *)(interact->result));
  1384. }
  1385. return (LDAP_SUCCESS);
  1386. }
  1387. static int
  1388. ldap_sasl_interact_cb(LDAP *ld, unsigned flags, void *defaults, void *prompts)
  1389. {
  1390. sasl_interact_t *interact = NULL;
  1391. ldapSaslInteractVals *sasldefaults = defaults;
  1392. int rc;
  1393. if (prompts == NULL) {
  1394. return (LDAP_PARAM_ERROR);
  1395. }
  1396. for (interact = prompts; interact->id != SASL_CB_LIST_END; interact++) {
  1397. /* Obtain the default value */
  1398. if ((rc = ldap_sasl_get_val(sasldefaults, interact, flags)) != LDAP_SUCCESS) {
  1399. return (rc);
  1400. }
  1401. }
  1402. return (LDAP_SUCCESS);
  1403. }
  1404. /* figure out from the context and this error if we should
  1405. attempt to retry the bind */
  1406. static int
  1407. can_retry_bind(LDAP *ld, const char *mech, const char *bindid,
  1408. const char *creds, int rc, const char *errmsg)
  1409. {
  1410. int localrc = 0;
  1411. if (errmsg && strstr(errmsg, "Ticket expired")) {
  1412. localrc = 1;
  1413. }
  1414. return localrc;
  1415. }
  1416. int
  1417. slapd_ldap_sasl_interactive_bind(
  1418. LDAP *ld, /* ldap connection */
  1419. const char *bindid, /* usually a bind DN for simple bind */
  1420. const char *creds, /* usually a password for simple bind */
  1421. const char *mech, /* name of mechanism */
  1422. LDAPControl **serverctrls, /* additional controls to send */
  1423. LDAPControl ***returnedctrls, /* returned controls */
  1424. int *msgidp /* pass in non-NULL for async handling */
  1425. )
  1426. {
  1427. int rc = LDAP_SUCCESS;
  1428. int tries = 0;
  1429. while (tries < 2) {
  1430. void *defaults = ldap_sasl_set_interact_vals(ld, mech, bindid, bindid,
  1431. creds, NULL);
  1432. /* have to first set the defaults used by the callback function */
  1433. /* call the bind function */
  1434. /* openldap does not have the ext version - not sure how to get the
  1435. returned controls */
  1436. #if defined(USE_OPENLDAP)
  1437. rc = ldap_sasl_interactive_bind_s(ld, bindid, mech, serverctrls,
  1438. NULL, LDAP_SASL_QUIET,
  1439. ldap_sasl_interact_cb, defaults);
  1440. #else
  1441. rc = ldap_sasl_interactive_bind_ext_s(ld, bindid, mech, serverctrls,
  1442. NULL, LDAP_SASL_QUIET,
  1443. ldap_sasl_interact_cb, defaults,
  1444. returnedctrls);
  1445. #endif
  1446. ldap_sasl_free_interact_vals(defaults);
  1447. if (LDAP_SUCCESS != rc) {
  1448. char *errmsg = NULL;
  1449. rc = slapi_ldap_get_lderrno(ld, NULL, &errmsg);
  1450. slapi_log_error(SLAPI_LOG_CONNS, "slapd_ldap_sasl_interactive_bind",
  1451. "Error: could not perform interactive bind for id "
  1452. "[%s] mech [%s]: LDAP error %d (%s) (%s) "
  1453. "errno %d (%s)\n",
  1454. bindid ? bindid : "(anon)",
  1455. mech ? mech : "SIMPLE",
  1456. rc, ldap_err2string(rc), errmsg,
  1457. errno, slapd_system_strerror(errno));
  1458. if (can_retry_bind(ld, mech, bindid, creds, rc, errmsg)) {
  1459. ; /* pass through to retry one time */
  1460. } else {
  1461. break; /* done - fail - cannot retry */
  1462. }
  1463. } else {
  1464. break; /* done - success */
  1465. }
  1466. tries++;
  1467. }
  1468. return rc;
  1469. }
  1470. #ifdef HAVE_KRB5
  1471. #include <krb5.h>
  1472. /* for some reason this is not in the public API?
  1473. but it is documented e.g. man kinit */
  1474. #ifndef KRB5_ENV_CCNAME
  1475. #define KRB5_ENV_CCNAME "KRB5CCNAME"
  1476. #endif
  1477. static void
  1478. show_one_credential(int authtracelevel,
  1479. krb5_context ctx, krb5_creds *cred)
  1480. {
  1481. char *logname = "show_one_credential";
  1482. krb5_error_code rc;
  1483. char *name = NULL, *sname = NULL;
  1484. char startts[BUFSIZ], endts[BUFSIZ], renewts[BUFSIZ];
  1485. if ((rc = krb5_unparse_name(ctx, cred->client, &name))) {
  1486. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1487. "Could not get client name from credential: %d (%s)\n",
  1488. rc, error_message(rc));
  1489. goto cleanup;
  1490. }
  1491. if ((rc = krb5_unparse_name(ctx, cred->server, &sname))) {
  1492. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1493. "Could not get server name from credential: %d (%s)\n",
  1494. rc, error_message(rc));
  1495. goto cleanup;
  1496. }
  1497. if (!cred->times.starttime) {
  1498. cred->times.starttime = cred->times.authtime;
  1499. }
  1500. krb5_timestamp_to_sfstring((krb5_timestamp)cred->times.starttime,
  1501. startts, sizeof(startts), NULL);
  1502. krb5_timestamp_to_sfstring((krb5_timestamp)cred->times.endtime,
  1503. endts, sizeof(endts), NULL);
  1504. krb5_timestamp_to_sfstring((krb5_timestamp)cred->times.renew_till,
  1505. renewts, sizeof(renewts), NULL);
  1506. slapi_log_error(authtracelevel, logname,
  1507. "\tKerberos credential: client [%s] server [%s] "
  1508. "start time [%s] end time [%s] renew time [%s] "
  1509. "flags [0x%x]\n", name, sname, startts, endts,
  1510. renewts, (uint32_t)cred->ticket_flags);
  1511. cleanup:
  1512. krb5_free_unparsed_name(ctx, name);
  1513. krb5_free_unparsed_name(ctx, sname);
  1514. return;
  1515. }
  1516. /*
  1517. * Call this after storing the credentials in the cache
  1518. */
  1519. static void
  1520. show_cached_credentials(int authtracelevel,
  1521. krb5_context ctx, krb5_ccache cc,
  1522. krb5_principal princ)
  1523. {
  1524. char *logname = "show_cached_credentials";
  1525. krb5_error_code rc = 0;
  1526. krb5_creds creds;
  1527. krb5_cc_cursor cur;
  1528. char *princ_name = NULL;
  1529. if ((rc = krb5_unparse_name(ctx, princ, &princ_name))) {
  1530. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1531. "Could not get principal name from principal: %d (%s)\n",
  1532. rc, error_message(rc));
  1533. goto cleanup;
  1534. }
  1535. slapi_log_error(authtracelevel, logname,
  1536. "Ticket cache: %s:%s\nDefault principal: %s\n\n",
  1537. krb5_cc_get_type(ctx, cc),
  1538. krb5_cc_get_name(ctx, cc), princ_name);
  1539. if ((rc = krb5_cc_start_seq_get(ctx, cc, &cur))) {
  1540. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1541. "Could not get cursor to iterate cached credentials: "
  1542. "%d (%s)\n", rc, error_message(rc));
  1543. goto cleanup;
  1544. }
  1545. while (!(rc = krb5_cc_next_cred(ctx, cc, &cur, &creds))) {
  1546. show_one_credential(authtracelevel, ctx, &creds);
  1547. krb5_free_cred_contents(ctx, &creds);
  1548. }
  1549. if (rc == KRB5_CC_END) {
  1550. if ((rc = krb5_cc_end_seq_get(ctx, cc, &cur))) {
  1551. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1552. "Could not close cached credentials cursor: "
  1553. "%d (%s)\n", rc, error_message(rc));
  1554. goto cleanup;
  1555. }
  1556. }
  1557. cleanup:
  1558. krb5_free_unparsed_name(ctx, princ_name);
  1559. return;
  1560. }
  1561. static int
  1562. looks_like_a_princ_name(const char *name)
  1563. {
  1564. /* a valid principal name will be a non-empty string
  1565. that doesn't have a = in it (which will likely be
  1566. a bind DN) */
  1567. return (name && *name && !strchr(name, '='));
  1568. }
  1569. static int
  1570. credentials_are_valid(
  1571. krb5_context ctx,
  1572. krb5_ccache cc,
  1573. krb5_principal princ,
  1574. const char *princ_name,
  1575. int *rc
  1576. )
  1577. {
  1578. char *logname = "credentials_are_valid";
  1579. int myrc = 0;
  1580. krb5_creds mcreds; /* match these values */
  1581. krb5_creds creds; /* returned creds */
  1582. char *tgs_princ_name = NULL;
  1583. krb5_timestamp currenttime;
  1584. int authtracelevel = SLAPI_LOG_SHELL; /* special auth tracing */
  1585. int realm_len;
  1586. char *realm_str;
  1587. int time_buffer = 30; /* seconds - go ahead and renew if creds are
  1588. about to expire */
  1589. memset(&mcreds, 0, sizeof(mcreds));
  1590. memset(&creds, 0, sizeof(creds));
  1591. *rc = 0;
  1592. if (!cc) {
  1593. /* ok - no error */
  1594. goto cleanup;
  1595. }
  1596. /* have to construct the tgs server principal in
  1597. order to set mcreds.server required in order
  1598. to use krb5_cc_retrieve_creds() */
  1599. /* get default realm first */
  1600. realm_len = krb5_princ_realm(ctx, princ)->length;
  1601. realm_str = krb5_princ_realm(ctx, princ)->data;
  1602. tgs_princ_name = slapi_ch_smprintf("%s/%*s@%*s", KRB5_TGS_NAME,
  1603. realm_len, realm_str,
  1604. realm_len, realm_str);
  1605. if ((*rc = krb5_parse_name(ctx, tgs_princ_name, &mcreds.server))) {
  1606. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1607. "Could parse principal [%s]: %d (%s)\n",
  1608. tgs_princ_name, *rc, error_message(*rc));
  1609. goto cleanup;
  1610. }
  1611. mcreds.client = princ;
  1612. if ((*rc = krb5_cc_retrieve_cred(ctx, cc, 0, &mcreds, &creds))) {
  1613. if (*rc == KRB5_CC_NOTFOUND) {
  1614. /* ok - no creds for this princ in the cache */
  1615. *rc = 0;
  1616. }
  1617. goto cleanup;
  1618. }
  1619. /* have the creds - now look at the timestamp */
  1620. if ((*rc = krb5_timeofday(ctx, &currenttime))) {
  1621. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1622. "Could not get current time: %d (%s)\n",
  1623. *rc, error_message(*rc));
  1624. goto cleanup;
  1625. }
  1626. if (currenttime > (creds.times.endtime + time_buffer)) {
  1627. slapi_log_error(authtracelevel, logname,
  1628. "Credentials for [%s] have expired or will soon "
  1629. "expire - now [%d] endtime [%d]\n", princ_name,
  1630. currenttime, creds.times.endtime);
  1631. goto cleanup;
  1632. }
  1633. myrc = 1; /* credentials are valid */
  1634. cleanup:
  1635. krb5_free_cred_contents(ctx, &creds);
  1636. slapi_ch_free_string(&tgs_princ_name);
  1637. if (mcreds.server) {
  1638. krb5_free_principal(ctx, mcreds.server);
  1639. }
  1640. return myrc;
  1641. }
  1642. static PRCallOnceType krb5_callOnce = {0,0};
  1643. static PRLock *krb5_lock = NULL;
  1644. static PRStatus
  1645. internal_krb5_init(void)
  1646. {
  1647. PR_ASSERT(NULL == krb5_lock);
  1648. if ((krb5_lock = PR_NewLock()) == NULL) {
  1649. PRErrorCode errorCode = PR_GetError();
  1650. slapi_log_error(SLAPI_LOG_FATAL, NULL, "internal_krb5_init PR_NewLock failed %d:%s\n",
  1651. errorCode, slapd_pr_strerror(errorCode));
  1652. return PR_FAILURE;
  1653. }
  1654. return PR_SUCCESS;
  1655. }
  1656. /*
  1657. * This implementation assumes that we want to use the
  1658. * keytab from the default keytab env. var KRB5_KTNAME
  1659. * as. This code is very similar to kinit -k -t. We
  1660. * get a krb context, get the default keytab, get
  1661. * the credentials from the keytab, authenticate with
  1662. * those credentials, create a ccache, store the
  1663. * credentials in the ccache, and set the ccache
  1664. * env var to point to those credentials.
  1665. */
  1666. static void
  1667. set_krb5_creds(
  1668. const char *authid,
  1669. const char *username,
  1670. const char *passwd,
  1671. const char *realm,
  1672. ldapSaslInteractVals *vals
  1673. )
  1674. {
  1675. char *logname = "set_krb5_creds";
  1676. const char *cc_type = "MEMORY"; /* keep cred cache in memory */
  1677. krb5_context ctx = NULL;
  1678. krb5_ccache cc = NULL;
  1679. krb5_principal princ = NULL;
  1680. char *princ_name = NULL;
  1681. krb5_error_code rc = 0;
  1682. krb5_creds creds;
  1683. krb5_keytab kt = NULL;
  1684. char *cc_name = NULL;
  1685. char ktname[MAX_KEYTAB_NAME_LEN];
  1686. static char cc_env_name[1024+32]; /* size from ccdefname.c */
  1687. int new_ccache = 0;
  1688. int authtracelevel = SLAPI_LOG_SHELL; /* special auth tracing
  1689. not sure what shell was
  1690. used for, does not
  1691. appear to be used
  1692. currently */
  1693. /* wipe this out so we can safely free it later if we
  1694. short circuit */
  1695. memset(&creds, 0, sizeof(creds));
  1696. /*
  1697. * we are using static variables and sharing an in-memory credentials cache
  1698. * so we put a lock around all kerberos interactions
  1699. */
  1700. if (PR_SUCCESS != PR_CallOnce(&krb5_callOnce, internal_krb5_init)) {
  1701. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1702. "Could not perform internal krb5 init\n");
  1703. rc = -1;
  1704. goto cleanup;
  1705. }
  1706. PR_Lock(krb5_lock);
  1707. /* initialize the kerberos context */
  1708. if ((rc = krb5_init_context(&ctx))) {
  1709. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1710. "Could not init Kerberos context: %d (%s)\n",
  1711. rc, error_message(rc));
  1712. goto cleanup;
  1713. }
  1714. /* see if there is already a ccache, and see if there are
  1715. creds in the ccache */
  1716. /* grab the default ccache - note: this does not open the cache */
  1717. if ((rc = krb5_cc_default(ctx, &cc))) {
  1718. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1719. "Could not get default Kerberos ccache: %d (%s)\n",
  1720. rc, error_message(rc));
  1721. goto cleanup;
  1722. }
  1723. /* use this cache - construct the full cache name */
  1724. cc_name = slapi_ch_smprintf("%s:%s", krb5_cc_get_type(ctx, cc),
  1725. krb5_cc_get_name(ctx, cc));
  1726. /* grab the principal from the ccache - will fail if there
  1727. is no ccache */
  1728. if ((rc = krb5_cc_get_principal(ctx, cc, &princ))) {
  1729. if (KRB5_FCC_NOFILE == rc) { /* no cache - ok */
  1730. slapi_log_error(authtracelevel, logname,
  1731. "The default credentials cache [%s] not found: "
  1732. "will create a new one.\n", cc_name);
  1733. /* close the cache - we will create a new one below */
  1734. krb5_cc_close(ctx, cc);
  1735. cc = NULL;
  1736. slapi_ch_free_string(&cc_name);
  1737. /* fall through to the keytab auth code below */
  1738. } else { /* fatal */
  1739. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1740. "Could not open default Kerberos ccache [%s]: "
  1741. "%d (%s)\n", cc_name, rc, error_message(rc));
  1742. goto cleanup;
  1743. }
  1744. } else { /* have a valid ccache && found principal */
  1745. if ((rc = krb5_unparse_name(ctx, princ, &princ_name))) {
  1746. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1747. "Unable to get name of principal from ccache [%s]: "
  1748. "%d (%s)\n", cc_name, rc, error_message(rc));
  1749. goto cleanup;
  1750. }
  1751. slapi_log_error(authtracelevel, logname,
  1752. "Using principal [%s] from ccache [%s]\n",
  1753. princ_name, cc_name);
  1754. }
  1755. /* if this is not our type of ccache, there is nothing more we can
  1756. do - just punt and let sasl/gssapi take it's course - this
  1757. usually means there has been an external kinit e.g. in the
  1758. start up script, and it is the responsibility of the script to
  1759. renew those credentials or face lots of sasl/gssapi failures
  1760. This means, however, that the caller MUST MAKE SURE THERE IS NO
  1761. DEFAULT CCACHE FILE or the server will attempt to use it (and
  1762. likely fail) - THERE MUST BE NO DEFAULT CCACHE FILE IF YOU WANT
  1763. THE SERVER TO AUTHENTICATE WITH THE KEYTAB
  1764. NOTE: cc types are case sensitive and always upper case */
  1765. if (cc && strcmp(cc_type, krb5_cc_get_type(ctx, cc))) {
  1766. static int errmsgcounter = 0;
  1767. int loglevel = SLAPI_LOG_FATAL;
  1768. if (errmsgcounter) {
  1769. loglevel = authtracelevel;
  1770. }
  1771. /* make sure we log this message once, in case the user has
  1772. done something unintended, we want to make sure they know
  1773. about it. However, if the user knows what he/she is doing,
  1774. by using an external ccache file, they probably don't want
  1775. to be notified with an error every time. */
  1776. slapi_log_error(loglevel, logname,
  1777. "The server will use the external SASL/GSSAPI "
  1778. "credentials cache [%s:%s]. If you want the "
  1779. "server to automatically authenticate with its "
  1780. "keytab, you must remove this cache. If you "
  1781. "did not intend to use this cache, you will likely "
  1782. "see many SASL/GSSAPI authentication failures.\n",
  1783. krb5_cc_get_type(ctx, cc), krb5_cc_get_name(ctx, cc));
  1784. errmsgcounter++;
  1785. goto cleanup;
  1786. }
  1787. /* need to figure out which principal to use
  1788. 1) use the one from the ccache
  1789. 2) use username
  1790. 3) construct one in the form ldap/fqdn@REALM
  1791. */
  1792. if (!princ && looks_like_a_princ_name(username) &&
  1793. (rc = krb5_parse_name(ctx, username, &princ))) {
  1794. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1795. "Error: could not convert [%s] into a kerberos "
  1796. "principal: %d (%s)\n", username,
  1797. rc, error_message(rc));
  1798. goto cleanup;
  1799. }
  1800. if (getenv("HACK_PRINCIPAL_NAME") &&
  1801. (rc = krb5_parse_name(ctx, getenv("HACK_PRINCIPAL_NAME"), &princ))) {
  1802. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1803. "Error: could not convert [%s] into a kerberos "
  1804. "principal: %d (%s)\n", getenv("HACK_PRINCIPAL_NAME"),
  1805. rc, error_message(rc));
  1806. goto cleanup;
  1807. }
  1808. /* if still no principal, construct one */
  1809. if (!princ) {
  1810. char *hostname = config_get_localhost();
  1811. if ((rc = krb5_sname_to_principal(ctx, hostname, "ldap",
  1812. KRB5_NT_SRV_HST, &princ))) {
  1813. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1814. "Error: could not construct ldap service "
  1815. "principal from hostname [%s]: %d (%s)\n",
  1816. hostname ? hostname : "NULL", rc, error_message(rc));
  1817. }
  1818. slapi_ch_free_string(&hostname);
  1819. if (rc) {
  1820. goto cleanup;
  1821. }
  1822. }
  1823. slapi_ch_free_string(&princ_name);
  1824. if ((rc = krb5_unparse_name(ctx, princ, &princ_name))) {
  1825. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1826. "Unable to get name of principal: "
  1827. "%d (%s)\n", rc, error_message(rc));
  1828. goto cleanup;
  1829. }
  1830. slapi_log_error(authtracelevel, logname,
  1831. "Using principal named [%s]\n", princ_name);
  1832. /* grab the credentials from the ccache, if any -
  1833. if the credentials are still valid, we do not have
  1834. to authenticate again */
  1835. if (credentials_are_valid(ctx, cc, princ, princ_name, &rc)) {
  1836. slapi_log_error(authtracelevel, logname,
  1837. "Credentials for principal [%s] are still "
  1838. "valid - no auth is necessary.\n",
  1839. princ_name);
  1840. goto cleanup;
  1841. } else if (rc) { /* some error other than "there are no credentials" */
  1842. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1843. "Unable to verify cached credentials for "
  1844. "principal [%s]: %d (%s)\n", princ_name,
  1845. rc, error_message(rc));
  1846. goto cleanup;
  1847. }
  1848. /* find our default keytab */
  1849. if ((rc = krb5_kt_default(ctx, &kt))) {
  1850. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1851. "Unable to get default keytab: %d (%s)\n",
  1852. rc, error_message(rc));
  1853. goto cleanup;
  1854. }
  1855. /* get name of keytab for debugging purposes */
  1856. if ((rc = krb5_kt_get_name(ctx, kt, ktname, sizeof(ktname)))) {
  1857. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1858. "Unable to get name of default keytab: %d (%s)\n",
  1859. rc, error_message(rc));
  1860. goto cleanup;
  1861. }
  1862. slapi_log_error(authtracelevel, logname,
  1863. "Using keytab named [%s]\n", ktname);
  1864. /* now do the actual kerberos authentication using
  1865. the keytab, and get the creds */
  1866. rc = krb5_get_init_creds_keytab(ctx, &creds, princ, kt,
  1867. 0, NULL, NULL);
  1868. if (rc) {
  1869. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1870. "Could not get initial credentials for principal [%s] "
  1871. "in keytab [%s]: %d (%s)\n",
  1872. princ_name, ktname, rc, error_message(rc));
  1873. goto cleanup;
  1874. }
  1875. /* completely done with the keytab now, close it */
  1876. krb5_kt_close(ctx, kt);
  1877. kt = NULL; /* no double free */
  1878. /* we now have the creds and the principal to which the
  1879. creds belong - use or allocate a new memory based
  1880. cache to hold the creds */
  1881. if (!cc_name) {
  1882. #if HAVE_KRB5_CC_NEW_UNIQUE
  1883. /* krb5_cc_new_unique is a new convenience function which
  1884. generates a new unique name and returns a memory
  1885. cache with that name */
  1886. if ((rc = krb5_cc_new_unique(ctx, cc_type, NULL, &cc))) {
  1887. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1888. "Could not create new unique memory ccache: "
  1889. "%d (%s)\n",
  1890. rc, error_message(rc));
  1891. goto cleanup;
  1892. }
  1893. cc_name = slapi_ch_smprintf("%s:%s", cc_type,
  1894. krb5_cc_get_name(ctx, cc));
  1895. #else
  1896. /* store the cache in memory - krb5_init_context uses malloc
  1897. to create the ctx, so the address should be unique enough
  1898. for our purposes */
  1899. if (!(cc_name = slapi_ch_smprintf("%s:%p", cc_type, ctx))) {
  1900. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1901. "Could create Kerberos memory ccache: "
  1902. "out of memory\n");
  1903. rc = 1;
  1904. goto cleanup;
  1905. }
  1906. #endif
  1907. slapi_log_error(authtracelevel, logname,
  1908. "Generated new memory ccache [%s]\n", cc_name);
  1909. new_ccache = 1; /* need to set this in env. */
  1910. } else {
  1911. slapi_log_error(authtracelevel, logname,
  1912. "Using existing ccache [%s]\n", cc_name);
  1913. }
  1914. /* krb5_cc_resolve is basically like an init -
  1915. this creates the cache structure, and creates a slot
  1916. for the cache in the static linked list in memory, if
  1917. there is not already a slot -
  1918. see cc_memory.c for details
  1919. cc could already have been created by new_unique above
  1920. */
  1921. if (!cc && (rc = krb5_cc_resolve(ctx, cc_name, &cc))) {
  1922. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1923. "Could not create ccache [%s]: %d (%s)\n",
  1924. cc_name, rc, error_message(rc));
  1925. goto cleanup;
  1926. }
  1927. /* wipe out previous contents of cache for this principal, if any */
  1928. if ((rc = krb5_cc_initialize(ctx, cc, princ))) {
  1929. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1930. "Could not initialize ccache [%s] for the new "
  1931. "credentials for principal [%s]: %d (%s)\n",
  1932. cc_name, princ_name, rc, error_message(rc));
  1933. goto cleanup;
  1934. }
  1935. /* store the credentials in the cache */
  1936. if ((rc = krb5_cc_store_cred(ctx, cc, &creds))) {
  1937. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1938. "Could not store the credentials in the "
  1939. "ccache [%s] for principal [%s]: %d (%s)\n",
  1940. cc_name, princ_name, rc, error_message(rc));
  1941. goto cleanup;
  1942. }
  1943. /* now, do a "klist" to show the credential information, and log it */
  1944. show_cached_credentials(authtracelevel, ctx, cc, princ);
  1945. /* set the CC env var to the value of the cc cache name */
  1946. /* since we can't pass krb5 context up and out of here
  1947. and down through the ldap sasl layer, we set this
  1948. env var so that calls to krb5_cc_default_name will
  1949. use this */
  1950. if (new_ccache) {
  1951. PR_snprintf(cc_env_name, sizeof(cc_env_name),
  1952. "%s=%s", KRB5_ENV_CCNAME, cc_name);
  1953. PR_SetEnv(cc_env_name);
  1954. slapi_log_error(authtracelevel, logname,
  1955. "Set new env for ccache: [%s]\n",
  1956. cc_env_name);
  1957. }
  1958. cleanup:
  1959. /* use NULL as username and authid */
  1960. slapi_ch_free_string(&vals->username);
  1961. slapi_ch_free_string(&vals->authid);
  1962. krb5_free_unparsed_name(ctx, princ_name);
  1963. if (kt) { /* NULL not allowed */
  1964. krb5_kt_close(ctx, kt);
  1965. }
  1966. if (creds.client == princ) {
  1967. creds.client = NULL;
  1968. }
  1969. krb5_free_cred_contents(ctx, &creds);
  1970. slapi_ch_free_string(&cc_name);
  1971. krb5_free_principal(ctx, princ);
  1972. if (cc) {
  1973. krb5_cc_close(ctx, cc);
  1974. }
  1975. if (ctx) { /* cannot pass NULL to free context */
  1976. krb5_free_context(ctx);
  1977. }
  1978. PR_Unlock(krb5_lock);
  1979. return;
  1980. }
  1981. static void
  1982. clear_krb5_ccache()
  1983. {
  1984. krb5_context ctx = NULL;
  1985. krb5_ccache cc = NULL;
  1986. int rc = 0;
  1987. PR_Lock(krb5_lock);
  1988. /* initialize the kerberos context */
  1989. if ((rc = krb5_init_context(&ctx))) {
  1990. slapi_log_error(SLAPI_LOG_FATAL, "clear_krb5_ccache", "Could not initialize kerberos context: %d (%s)\n",
  1991. rc, error_message(rc));
  1992. goto done;
  1993. }
  1994. /* get the default ccache */
  1995. if ((rc = krb5_cc_default(ctx, &cc))) {
  1996. slapi_log_error(SLAPI_LOG_FATAL, "clear_krb5_ccache", "Could not get default kerberos ccache: %d (%s)\n",
  1997. rc, error_message(rc));
  1998. goto done;
  1999. }
  2000. /* destroy the ccache */
  2001. if((rc = krb5_cc_destroy(ctx, cc))){
  2002. slapi_log_error(SLAPI_LOG_FATAL, "clear_krb5_ccache", "Could not destroy kerberos ccache: %d (%s)\n",
  2003. rc, error_message(rc));
  2004. } else {
  2005. slapi_log_error(SLAPI_LOG_TRACE,"clear_krb5_ccache", "Successfully cleared kerberos ccache\n");
  2006. }
  2007. done:
  2008. if(ctx){
  2009. krb5_free_context(ctx);
  2010. }
  2011. PR_Unlock(krb5_lock);
  2012. }
  2013. #endif /* HAVE_KRB5 */
  2014. #define LDAP_DN 1
  2015. #define LDAP_RDN 2
  2016. #define INQUOTE 1
  2017. #define OUTQUOTE 2
  2018. /* We use the following two functions when built against OpenLDAP
  2019. * or the MozLDAP libs since the MozLDAP ldap_explode_dn() function
  2020. * does not handle trailing whitespace characters properly. */
  2021. static char **
  2022. mozldap_ldap_explode( const char *dn, const int notypes, const int nametype )
  2023. {
  2024. char *p, *q, *rdnstart, **rdns = NULL;
  2025. size_t plen = 0;
  2026. int state = 0;
  2027. int count = 0;
  2028. int startquote = 0;
  2029. int endquote = 0;
  2030. int len = 0;
  2031. int goteq = 0;
  2032. if ( dn == NULL ) {
  2033. dn = "";
  2034. }
  2035. while ( ldap_utf8isspace( (char *)dn )) { /* ignore leading spaces */
  2036. ++dn;
  2037. }
  2038. p = rdnstart = (char *) dn;
  2039. state = OUTQUOTE;
  2040. do {
  2041. p += plen;
  2042. plen = 1;
  2043. switch ( *p ) {
  2044. case '\\':
  2045. if ( *++p == '\0' )
  2046. p--;
  2047. else
  2048. plen = LDAP_UTF8LEN(p);
  2049. break;
  2050. case '"':
  2051. if ( state == INQUOTE )
  2052. state = OUTQUOTE;
  2053. else
  2054. state = INQUOTE;
  2055. break;
  2056. case '+': if ( nametype != LDAP_RDN ) break;
  2057. case ';':
  2058. case ',':
  2059. case '\0':
  2060. if ( state == OUTQUOTE ) {
  2061. /*
  2062. * semicolon and comma are not valid RDN
  2063. * separators.
  2064. */
  2065. if ( nametype == LDAP_RDN &&
  2066. ( *p == ';' || *p == ',' || !goteq)) {
  2067. charray_free( rdns );
  2068. return NULL;
  2069. }
  2070. if ( (*p == ',' || *p == ';') && !goteq ) {
  2071. /* If we get here, we have a case similar
  2072. * to <attr>=<value>,<string>,<attr>=<value>
  2073. * This is not a valid dn */
  2074. charray_free( rdns );
  2075. return NULL;
  2076. }
  2077. goteq = 0;
  2078. ++count;
  2079. if ( rdns == NULL ) {
  2080. if (( rdns = (char **)slapi_ch_malloc( 8
  2081. * sizeof( char *))) == NULL )
  2082. return( NULL );
  2083. } else if ( count >= 8 ) {
  2084. if (( rdns = (char **)slapi_ch_realloc(
  2085. (char *)rdns, (count+1) *
  2086. sizeof( char *))) == NULL )
  2087. return( NULL );
  2088. }
  2089. rdns[ count ] = NULL;
  2090. endquote = 0;
  2091. if ( notypes ) {
  2092. for ( q = rdnstart;
  2093. q < p && *q != '='; ++q ) {
  2094. ;
  2095. }
  2096. if ( q < p ) { /* *q == '=' */
  2097. rdnstart = ++q;
  2098. }
  2099. if ( *rdnstart == '"' ) {
  2100. startquote = 1;
  2101. ++rdnstart;
  2102. }
  2103. if ( (*(p-1) == '"') && startquote ) {
  2104. endquote = 1;
  2105. --p;
  2106. }
  2107. }
  2108. len = p - rdnstart;
  2109. if (( rdns[ count-1 ] = (char *)slapi_ch_calloc(
  2110. 1, len + 1 )) != NULL ) {
  2111. memcpy( rdns[ count-1 ], rdnstart,
  2112. len );
  2113. if ( !endquote ) {
  2114. /* trim trailing spaces */
  2115. while ( len > 0 &&
  2116. (rdns[count-1][len-1] == ' ')) {
  2117. --len;
  2118. }
  2119. }
  2120. rdns[ count-1 ][ len ] = '\0';
  2121. }
  2122. /*
  2123. * Don't forget to increment 'p' back to where
  2124. * it should be. If we don't, then we will
  2125. * never get past an "end quote."
  2126. */
  2127. if ( endquote == 1 )
  2128. p++;
  2129. rdnstart = *p ? p + 1 : p;
  2130. while ( ldap_utf8isspace( rdnstart ))
  2131. ++rdnstart;
  2132. }
  2133. break;
  2134. case '=':
  2135. if ( state == OUTQUOTE ) {
  2136. goteq = 1;
  2137. }
  2138. /* FALL */
  2139. default:
  2140. plen = LDAP_UTF8LEN(p);
  2141. break;
  2142. }
  2143. } while ( *p );
  2144. return( rdns );
  2145. }
  2146. static char **
  2147. mozldap_ldap_explode_dn( const char *dn, const int notypes )
  2148. {
  2149. return( mozldap_ldap_explode( dn, notypes, LDAP_DN ) );
  2150. }
  2151. static char **
  2152. mozldap_ldap_explode_rdn( const char *rdn, const int notypes )
  2153. {
  2154. return( mozldap_ldap_explode( rdn, notypes, LDAP_RDN ) );
  2155. }
  2156. int
  2157. slapi_is_ipv6_addr( const char *hostname ){
  2158. PRNetAddr addr;
  2159. if(PR_StringToNetAddr(hostname, &addr) == PR_SUCCESS &&
  2160. !PR_IsNetAddrType(&addr, PR_IpAddrV4Mapped) &&
  2161. addr.raw.family == PR_AF_INET6)
  2162. {
  2163. return 1;
  2164. }
  2165. return 0;
  2166. }
  2167. /*
  2168. * Get the length of the ber-encoded ldap message. Note, only the length of
  2169. * the LDAP operation is returned, not the length of the entire berval.
  2170. * Add 2 to the length for the entire PDU size. If "strict" is set then
  2171. * the entire LDAP PDU must be in the berval.
  2172. */
  2173. ber_len_t
  2174. slapi_berval_get_msg_len(struct berval *bv, int strict)
  2175. {
  2176. ber_len_t len, rest;
  2177. unsigned char *ptr;
  2178. int i;
  2179. /* Get the ldap operation length */
  2180. rest = bv->bv_len - 1;
  2181. ptr = (unsigned char *)bv->bv_val ;
  2182. ptr++; /* skip the tag and get right to the length */
  2183. len = *ptr++;
  2184. rest--;
  2185. if ( len & 0x80U ) {
  2186. len &= 0x7fU;
  2187. if ( len - 1U > sizeof(ber_len_t) - 1U || rest < len ) {
  2188. /* Indefinite-length/too long length/not enough data */
  2189. return -1;
  2190. }
  2191. rest -= len;
  2192. i = len;
  2193. for( len = *ptr++ & 0xffU; --i; len |= *ptr++ & 0xffU ) {
  2194. len <<= 8;
  2195. }
  2196. }
  2197. if( strict && len > rest ) {
  2198. return -1;
  2199. }
  2200. return len;
  2201. }
  2202. int
  2203. slapi_client_uses_non_nss(LDAP *ld)
  2204. {
  2205. static int not_nss = 0;
  2206. #if defined(USE_OPENLDAP)
  2207. static int initialized = 0;
  2208. char *package_name = NULL;
  2209. int rc;
  2210. if (initialized) {
  2211. return not_nss;
  2212. }
  2213. rc = ldap_get_option(ld, LDAP_OPT_X_TLS_PACKAGE, &package_name);
  2214. if (!rc && PL_strcasecmp(package_name, "MozNSS")) {
  2215. not_nss = 1;
  2216. slapi_ch_free_string(&package_name);
  2217. }
  2218. initialized = 1;
  2219. #endif
  2220. return not_nss;
  2221. }
  2222. int
  2223. slapi_client_uses_openssl(LDAP *ld)
  2224. {
  2225. static int is_openssl = 0;
  2226. #if defined(USE_OPENLDAP)
  2227. static int initialized = 0;
  2228. char *package_name = NULL;
  2229. int rc;
  2230. if (initialized) {
  2231. return is_openssl;
  2232. }
  2233. rc = ldap_get_option(ld, LDAP_OPT_X_TLS_PACKAGE, &package_name);
  2234. if (!rc && !PL_strcasecmp(package_name, "OpenSSL")) {
  2235. is_openssl = 1;
  2236. slapi_ch_free_string(&package_name);
  2237. }
  2238. initialized = 1;
  2239. #endif
  2240. return is_openssl;
  2241. }