ldaputil.c 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873
  1. /** BEGIN COPYRIGHT BLOCK
  2. * This Program is free software; you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation; version 2 of the License.
  5. *
  6. * This Program is distributed in the hope that it will be useful, but WITHOUT
  7. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  8. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  9. *
  10. * You should have received a copy of the GNU General Public License along with
  11. * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple
  12. * Place, Suite 330, Boston, MA 02111-1307 USA.
  13. *
  14. * In addition, as a special exception, Red Hat, Inc. gives You the additional
  15. * right to link the code of this Program with code not covered under the GNU
  16. * General Public License ("Non-GPL Code") and to distribute linked combinations
  17. * including the two, subject to the limitations in this paragraph. Non-GPL Code
  18. * permitted under this exception must only link to the code of this Program
  19. * through those well defined interfaces identified in the file named EXCEPTION
  20. * found in the source code files (the "Approved Interfaces"). The files of
  21. * Non-GPL Code may instantiate templates or use macros or inline functions from
  22. * the Approved Interfaces without causing the resulting work to be covered by
  23. * the GNU General Public License. Only Red Hat, Inc. may make changes or
  24. * additions to the list of Approved Interfaces. You must obey the GNU General
  25. * Public License in all respects for all of the Program code and other code used
  26. * in conjunction with the Program except the Non-GPL Code covered by this
  27. * exception. If you modify this file, you may extend this exception to your
  28. * version of the file, but you are not obligated to do so. If you do not wish to
  29. * provide this exception without modification, you must delete this exception
  30. * statement from your version and license this file solely under the GPL without
  31. * exception.
  32. *
  33. *
  34. * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission.
  35. * Copyright (C) 2005 Red Hat, Inc.
  36. * All rights reserved.
  37. * END COPYRIGHT BLOCK **/
  38. #ifdef HAVE_CONFIG_H
  39. # include <config.h>
  40. #endif
  41. /* ldaputil.c -- LDAP utility functions and wrappers */
  42. #ifdef _WIN32
  43. #include <direct.h> /* for getcwd */
  44. #else
  45. #include <sys/socket.h>
  46. #include <sys/param.h>
  47. #include <unistd.h>
  48. #include <pwd.h>
  49. #endif
  50. #include <libgen.h>
  51. #include <pk11func.h>
  52. #include "slap.h"
  53. #include "prtime.h"
  54. #include "prinrval.h"
  55. #include "snmp_collator.h"
  56. #if !defined(USE_OPENLDAP)
  57. #include <ldap_ssl.h>
  58. #include <ldappr.h>
  59. #endif
  60. #ifdef MEMPOOL_EXPERIMENTAL
  61. void _free_wrapper(void *ptr)
  62. {
  63. slapi_ch_free(&ptr);
  64. }
  65. #endif
  66. /*
  67. * Function: slapi_ldap_unbind()
  68. * Purpose: release an LDAP session obtained from a call to slapi_ldap_init().
  69. */
  70. void
  71. slapi_ldap_unbind( LDAP *ld )
  72. {
  73. if ( ld != NULL ) {
  74. ldap_unbind_ext( ld, NULL, NULL );
  75. }
  76. }
  77. /* mozldap ldap_init and ldap_url_parse accept a hostname in the form
  78. host1[:port1]SPACEhost2[:port2]SPACEhostN[:portN]
  79. where SPACE is a single space (0x20) character
  80. for openldap, we have to convert this to a string like this:
  81. PROTO://host1[:port1]/SPACEPROTO://host2[:port2]/SPACEPROTO://hostN[:portN]/
  82. where PROTO is ldap or ldaps or ldapi
  83. if proto is NULL, assume hostname_or_uri is really a valid ldap uri
  84. */
  85. static char *
  86. convert_to_openldap_uri(const char *hostname_or_uri, int port, const char *proto)
  87. {
  88. char *retstr = NULL;
  89. char *my_copy = NULL;
  90. char *start = NULL;
  91. char *iter = NULL;
  92. char *s = NULL;
  93. const char *brkstr = " ";
  94. if (!hostname_or_uri) {
  95. return NULL;
  96. }
  97. my_copy = slapi_ch_strdup(hostname_or_uri);
  98. /* see if hostname_or_uri is an ldap uri */
  99. if (!proto && !PL_strncasecmp(my_copy, "ldap", 4)) {
  100. start = my_copy + 4;
  101. if ((*start == 's') || (*start == 'i')) {
  102. start++;
  103. }
  104. if (!PL_strncmp(start, "://", 3)) {
  105. *start = '\0';
  106. proto = my_copy;
  107. start += 3;
  108. } else {
  109. slapi_log_error(SLAPI_LOG_FATAL, "convert_to_openldap_uri",
  110. "The given LDAP URI [%s] is not valid\n", hostname_or_uri);
  111. goto end;
  112. }
  113. } else if (!proto) {
  114. slapi_log_error(SLAPI_LOG_FATAL, "convert_to_openldap_uri",
  115. "The given LDAP URI [%s] is not valid\n", hostname_or_uri);
  116. goto end;
  117. } else {
  118. start = my_copy; /* just assume it's not a uri */
  119. }
  120. for (s = ldap_utf8strtok_r(my_copy, brkstr, &iter); s != NULL;
  121. s = ldap_utf8strtok_r(NULL, brkstr, &iter)) {
  122. char *ptr;
  123. int last = 0;
  124. /* strtok will grab the '/' at the end of the uri, if any,
  125. so terminate parsing there */
  126. if ((ptr = strchr(s, '/'))) {
  127. *ptr = '\0';
  128. last = 1;
  129. }
  130. if (retstr) {
  131. retstr = PR_sprintf_append(retstr, "/ %s://%s", proto, s);
  132. } else {
  133. retstr = PR_smprintf("%s://%s", proto, s);
  134. }
  135. if (last) {
  136. break;
  137. }
  138. }
  139. /* add the port on the last one */
  140. retstr = PR_sprintf_append(retstr, ":%d/", port);
  141. end:
  142. slapi_ch_free_string(&my_copy);
  143. return retstr;
  144. }
  145. const char *
  146. slapi_urlparse_err2string( int err )
  147. {
  148. const char *s="internal error";
  149. switch( err ) {
  150. case 0:
  151. s = "no error";
  152. break;
  153. case LDAP_URL_ERR_BADSCOPE:
  154. s = "invalid search scope";
  155. break;
  156. case LDAP_URL_ERR_MEM:
  157. s = "unable to allocate memory";
  158. break;
  159. case LDAP_URL_ERR_PARAM:
  160. s = "bad parameter to an LDAP URL function";
  161. break;
  162. #if defined(USE_OPENLDAP)
  163. case LDAP_URL_ERR_BADSCHEME:
  164. s = "does not begin with ldap://, ldaps://, or ldapi://";
  165. break;
  166. case LDAP_URL_ERR_BADENCLOSURE:
  167. s = "missing trailing '>' in enclosure";
  168. break;
  169. case LDAP_URL_ERR_BADURL:
  170. s = "not a valid LDAP URL";
  171. break;
  172. case LDAP_URL_ERR_BADHOST:
  173. s = "hostname part of url is not valid or not given";
  174. break;
  175. case LDAP_URL_ERR_BADATTRS:
  176. s = "attribute list not formatted correctly or missing";
  177. break;
  178. case LDAP_URL_ERR_BADFILTER:
  179. s = "search filter not correct";
  180. break;
  181. case LDAP_URL_ERR_BADEXTS:
  182. s = "extensions not specified correctly";
  183. break;
  184. #else /* !USE_OPENLDAP */
  185. case LDAP_URL_ERR_NOTLDAP:
  186. s = "missing ldap:// or ldaps:// or ldapi://";
  187. break;
  188. case LDAP_URL_ERR_NODN:
  189. s = "missing suffix";
  190. break;
  191. #endif
  192. }
  193. return( s );
  194. }
  195. /* there are various differences among url parsers - directory server
  196. needs the ability to parse partial URLs - those with no dn - and
  197. needs to be able to tell if it is a secure url (ldaps) or not */
  198. int
  199. slapi_ldap_url_parse(const char *url, LDAPURLDesc **ludpp, int require_dn, int *secure)
  200. {
  201. PR_ASSERT(url);
  202. PR_ASSERT(ludpp);
  203. int rc;
  204. const char *url_to_use = url;
  205. #if defined(USE_OPENLDAP)
  206. char *urlescaped = NULL;
  207. #endif
  208. if (secure) {
  209. *secure = 0;
  210. }
  211. #if defined(USE_OPENLDAP)
  212. /* openldap does not support the non-standard multi host:port URLs supported
  213. by mozldap - so we have to fake out openldap - replace all spaces with %20 -
  214. replace all but the last colon with %3A
  215. Go to the 3rd '/' or to the end of the string (convert only the host:port part) */
  216. if (url) {
  217. char *p = strstr(url, "://");
  218. if (p) {
  219. int foundspace = 0;
  220. int coloncount = 0;
  221. char *lastcolon = NULL;
  222. p += 3;
  223. for (; *p && (*p != '/'); p++) {
  224. if (*p == ' ') {
  225. foundspace = 1;
  226. }
  227. if (*p == ':') {
  228. coloncount++;
  229. lastcolon = p;
  230. }
  231. }
  232. if (foundspace) {
  233. char *src = NULL, *dest = NULL;
  234. /* have to convert url */
  235. /* len * 3 is way too much, but acceptable */
  236. urlescaped = slapi_ch_calloc(strlen(url) * 3, sizeof(char));
  237. dest = urlescaped;
  238. /* copy the scheme */
  239. src = strstr(url, "://");
  240. src += 3;
  241. memcpy(dest, url, src-url);
  242. dest += (src-url);
  243. /* we have to convert all spaces to %20 - we have to convert
  244. all colons except the last one to %3A */
  245. for (; *src; ++src) {
  246. if (src < p) {
  247. if (*src == ' ') {
  248. memcpy(dest, "%20", 3);
  249. dest += 3;
  250. } else if ((coloncount > 1) && (*src == ':') && (src != lastcolon)) {
  251. memcpy(dest, "%3A", 3);
  252. dest += 3;
  253. } else {
  254. *dest++ = *src;
  255. }
  256. } else {
  257. *dest++ = *src;
  258. }
  259. }
  260. *dest = '\0';
  261. url_to_use = urlescaped;
  262. }
  263. }
  264. }
  265. #endif
  266. #if defined(HAVE_LDAP_URL_PARSE_NO_DEFAULTS)
  267. rc = ldap_url_parse_no_defaults(url_to_use, ludpp, require_dn);
  268. if (!rc && *ludpp && secure) {
  269. *secure = (*ludpp)->lud_options & LDAP_URL_OPT_SECURE;
  270. }
  271. #else /* openldap */
  272. #if defined(HAVE_LDAP_URL_PARSE_EXT) && defined(LDAP_PVT_URL_PARSE_NONE) && defined(LDAP_PVT_URL_PARSE_NOEMPTY_DN)
  273. rc = ldap_url_parse_ext(url_to_use, ludpp, require_dn ? LDAP_PVT_URL_PARSE_NONE : LDAP_PVT_URL_PARSE_NOEMPTY_DN);
  274. #else
  275. rc = ldap_url_parse(url_to_use, ludpp);
  276. if ((rc || !*ludpp) && !require_dn) { /* failed - see if failure was due to missing dn */
  277. size_t len = strlen(url_to_use);
  278. /* assume the url is just scheme://host:port[/] - add the empty string
  279. as the DN (adding a trailing / first if needed) and try to parse
  280. again
  281. */
  282. char *urlcopy = slapi_ch_smprintf("%s%s%s", url_to_use, (url_to_use[len-1] == '/' ? "" : "/"), "");
  283. if (*ludpp) {
  284. ldap_free_urldesc(*ludpp); /* free the old one, if any */
  285. }
  286. rc = ldap_url_parse(urlcopy, ludpp);
  287. slapi_ch_free_string(&urlcopy);
  288. if (0 == rc) { /* only problem was the DN - free it */
  289. slapi_ch_free_string(&((*ludpp)->lud_dn));
  290. }
  291. }
  292. #endif
  293. if (!rc && *ludpp && secure) {
  294. *secure = (*ludpp)->lud_scheme && !strcmp((*ludpp)->lud_scheme, "ldaps");
  295. }
  296. #endif /* openldap */
  297. #if defined(USE_OPENLDAP)
  298. if (urlescaped && (*ludpp) && (*ludpp)->lud_host) {
  299. /* have to unescape lud_host - can unescape in place */
  300. char *p = strstr((*ludpp)->lud_host, "://");
  301. if (p) {
  302. char *dest = NULL;
  303. p += 3;
  304. dest = p;
  305. /* up to the first '/', unescape the host */
  306. for (; *p && (*p != '/'); p++) {
  307. if (!strncmp(p, "%20", 3)) {
  308. *dest++ = ' ';
  309. p += 2;
  310. } else if (!strncmp(p, "%3A", 3)) {
  311. *dest++ = ':';
  312. p += 2;
  313. } else {
  314. *dest++ = *p;
  315. }
  316. }
  317. /* just copy the remainder of the host, if any */
  318. while (*p) {
  319. *dest++ = *p++;
  320. }
  321. *dest = '\0';
  322. }
  323. }
  324. slapi_ch_free_string(&urlescaped);
  325. #endif
  326. return rc;
  327. }
  328. #include <sasl.h>
  329. int
  330. slapi_ldap_get_lderrno(LDAP *ld, char **m, char **s)
  331. {
  332. int rc = LDAP_SUCCESS;
  333. #if defined(USE_OPENLDAP)
  334. ldap_get_option(ld, LDAP_OPT_RESULT_CODE, &rc);
  335. if (m) {
  336. ldap_get_option(ld, LDAP_OPT_MATCHED_DN, m);
  337. }
  338. if (s) {
  339. #ifdef LDAP_OPT_DIAGNOSTIC_MESSAGE
  340. ldap_get_option(ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, s);
  341. #else
  342. ldap_get_option(ld, LDAP_OPT_ERROR_STRING, s);
  343. #endif
  344. }
  345. #else /* !USE_OPENLDAP */
  346. rc = ldap_get_lderrno( ld, m, s );
  347. #endif
  348. return rc;
  349. }
  350. void
  351. slapi_ldif_put_type_and_value_with_options( char **out, const char *t, const char *val, int vlen, unsigned long options )
  352. {
  353. #if defined(USE_OPENLDAP)
  354. /* openldap always wraps and always does conservative base64 encoding
  355. we unwrap here, but clients will have to do their own base64 decode */
  356. int type = LDIF_PUT_VALUE;
  357. char *save = *out;
  358. if (options & LDIF_OPT_VALUE_IS_URL) {
  359. type = LDIF_PUT_URL;
  360. }
  361. ldif_sput( out, type, t, val, vlen );
  362. if (options & LDIF_OPT_NOWRAP) {
  363. /* modify out in place, stripping out continuation lines */
  364. char *src = save;
  365. char *dest = save;
  366. for (; src && *src && (src != *out); ++src) {
  367. if (!strncmp(src, "\n ", 2)) {
  368. src += 2; /* skip continuation */
  369. }
  370. *dest++ = *src;
  371. }
  372. *out = dest; /* move 'out' back if we removed some continuation lines */
  373. }
  374. #else
  375. ldif_put_type_and_value_with_options( out, (char *)t, (char *)val, vlen, options );
  376. #endif
  377. }
  378. void
  379. slapi_ldap_value_free( char **vals )
  380. {
  381. #if defined(USE_OPENLDAP)
  382. slapi_ch_array_free(vals);
  383. #else
  384. ldap_value_free(vals);
  385. #endif
  386. }
  387. int
  388. slapi_ldap_count_values( char **vals )
  389. {
  390. #if defined(USE_OPENLDAP)
  391. return ldap_count_values_len((struct berval **)vals);
  392. #else
  393. return ldap_count_values(vals);
  394. #endif
  395. }
  396. int
  397. slapi_ldap_create_proxyauth_control (
  398. LDAP *ld, /* only used to get current ber options */
  399. const char *dn, /* proxy dn */
  400. const char ctl_iscritical,
  401. int usev2, /* use the v2 (.18) control instead */
  402. LDAPControl **ctrlp /* value to return */
  403. )
  404. {
  405. int rc = 0;
  406. #if defined(USE_OPENLDAP)
  407. BerElement *ber = NULL;
  408. int beropts = 0;
  409. char *berfmtstr = NULL;
  410. char *ctrloid = NULL;
  411. struct berval *bv = NULL;
  412. /* note - there is currently no way to get the beroptions from the ld*,
  413. so we just hard code it here */
  414. beropts = LBER_USE_DER; /* openldap seems to use DER by default */
  415. if (ctrlp == NULL) {
  416. return LDAP_PARAM_ERROR;
  417. }
  418. if (NULL == dn) {
  419. dn = "";
  420. }
  421. if (NULL == (ber = ber_alloc_t(beropts))) {
  422. return LDAP_NO_MEMORY;
  423. }
  424. if (usev2) {
  425. berfmtstr = "s";
  426. ctrloid = LDAP_CONTROL_PROXIEDAUTH;
  427. } else {
  428. berfmtstr = "{s}";
  429. ctrloid = LDAP_CONTROL_PROXYAUTH;
  430. }
  431. if (LBER_ERROR == ber_printf(ber, berfmtstr, dn)) {
  432. ber_free(ber, 1);
  433. return LDAP_ENCODING_ERROR;
  434. }
  435. if (LBER_ERROR == ber_flatten(ber, &bv)) {
  436. ber_bvfree(bv);
  437. ber_free(ber, 1);
  438. return LDAP_ENCODING_ERROR;
  439. }
  440. if (NULL == bv) {
  441. ber_free(ber, 1);
  442. return LDAP_NO_MEMORY;
  443. }
  444. rc = ldap_control_create(ctrloid, ctl_iscritical, bv, 1, ctrlp);
  445. ber_bvfree(bv);
  446. ber_free(ber, 1);
  447. #else
  448. if (usev2) {
  449. rc = ldap_create_proxiedauth_control(ld, dn, ctrlp);
  450. } else {
  451. rc = ldap_create_proxyauth_control(ld, dn, ctl_iscritical, ctrlp);
  452. }
  453. #endif
  454. return rc;
  455. }
  456. int
  457. slapi_ldif_parse_line(
  458. char *line,
  459. struct berval *type,
  460. struct berval *value,
  461. int *freeval
  462. )
  463. {
  464. int rc;
  465. #if defined(USE_OPENLDAP)
  466. rc = ldif_parse_line2(line, type, value, freeval);
  467. /* check that type and value are null terminated */
  468. #else
  469. int vlen;
  470. rc = ldif_parse_line(line, &type->bv_val, &value->bv_val, &vlen);
  471. type->bv_len = type->bv_val ? strlen(type->bv_val) : 0;
  472. value->bv_len = vlen;
  473. *freeval = 0; /* always returns in place */
  474. #endif
  475. return rc;
  476. }
  477. /*
  478. Perform LDAP init and return an LDAP* handle. If ldapurl is given,
  479. that is used as the basis for the protocol, host, port, and whether
  480. to use starttls (given on the end as ldap://..../?????starttlsOID
  481. If hostname is given, LDAP or LDAPS is assumed, and this will override
  482. the hostname from the ldapurl, if any. If port is > 0, this is the
  483. port number to use. It will override the port in the ldapurl, if any.
  484. If no port is given in port or ldapurl, the default will be used based
  485. on the secure setting (389 for ldap, 636 for ldaps, 389 for starttls)
  486. secure takes 1 of 3 values - 0 means regular ldap, 1 means ldaps, 2
  487. means regular ldap with starttls.
  488. filename is the ldapi file name - if this is given, and no other options
  489. are given, ldapi is assumed.
  490. */
  491. /* util_sasl_path: the string argument for putenv.
  492. It must be a global or a static */
  493. char util_sasl_path[MAXPATHLEN];
  494. LDAP *
  495. slapi_ldap_init_ext(
  496. const char *ldapurl, /* full ldap url */
  497. const char *hostname, /* can also use this to override
  498. host in url */
  499. int port, /* can also use this to override port in url */
  500. int secure, /* 0 for ldap, 1 for ldaps, 2 for starttls -
  501. override proto in url */
  502. int shared, /* if true, LDAP* will be shared among multiple threads */
  503. const char *filename /* for ldapi */
  504. )
  505. {
  506. LDAPURLDesc *ludp = NULL;
  507. LDAP *ld = NULL;
  508. int rc = 0;
  509. int secureurl = 0;
  510. /* We need to provide a sasl path used for client connections, especially
  511. if the server is not set up to be a sasl server - since mozldap provides
  512. no way to override the default path programatically, we set the sasl
  513. path to the environment variable SASL_PATH. */
  514. char *configpluginpath = config_get_saslpath();
  515. char *pluginpath = configpluginpath;
  516. char *pp = NULL;
  517. if (NULL == pluginpath || (*pluginpath == '\0')) {
  518. slapi_log_error(SLAPI_LOG_SHELL, "slapi_ldap_init_ext",
  519. "configpluginpath == NULL\n");
  520. if (!(pluginpath = getenv("SASL_PATH"))) {
  521. #if defined(LINUX) && defined(__LP64__)
  522. pluginpath = "/usr/lib64/sasl2";
  523. #else
  524. pluginpath = "/usr/lib/sasl2";
  525. #endif
  526. }
  527. }
  528. if ('\0' == util_sasl_path[0] || /* first time */
  529. NULL == (pp = strchr(util_sasl_path, '=')) || /* invalid arg for putenv */
  530. (0 != strcmp(++pp, pluginpath)) /* sasl_path has been updated */ ) {
  531. PR_snprintf(util_sasl_path, sizeof(util_sasl_path),
  532. "SASL_PATH=%s", pluginpath);
  533. slapi_log_error(SLAPI_LOG_SHELL, "slapi_ldap_init_ext",
  534. "putenv(%s)\n", util_sasl_path);
  535. putenv(util_sasl_path);
  536. }
  537. slapi_ch_free_string(&configpluginpath);
  538. /* if ldapurl is given, parse it */
  539. if (ldapurl && ((rc = slapi_ldap_url_parse(ldapurl, &ludp, 0, &secureurl)) ||
  540. !ludp)) {
  541. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_init_ext",
  542. "Could not parse given LDAP URL [%s] : error [%s]\n",
  543. ldapurl, /* ldapurl cannot be NULL here */
  544. slapi_urlparse_err2string(rc));
  545. goto done;
  546. }
  547. /* use url host if no host given */
  548. if (!hostname && ludp && ludp->lud_host) {
  549. hostname = ludp->lud_host;
  550. }
  551. /* use url port if no port given */
  552. if (!port && ludp && ludp->lud_port) {
  553. port = ludp->lud_port;
  554. }
  555. /* use secure setting from url if none given */
  556. if (!secure && ludp) {
  557. if (secureurl) {
  558. secure = 1;
  559. } else if (0/* starttls option - not supported yet in LDAP URLs */) {
  560. secure = 2;
  561. }
  562. }
  563. /* ldap_url_parse doesn't yet handle ldapi */
  564. /*
  565. if (!filename && ludp && ludp->lud_file) {
  566. filename = ludp->lud_file;
  567. }
  568. */
  569. #ifdef MEMPOOL_EXPERIMENTAL
  570. {
  571. /*
  572. * slapi_ch_malloc functions need to be set to LDAP C SDK
  573. */
  574. struct ldap_memalloc_fns memalloc_fns;
  575. memalloc_fns.ldapmem_malloc = (LDAP_MALLOC_CALLBACK *)slapi_ch_malloc;
  576. memalloc_fns.ldapmem_calloc = (LDAP_CALLOC_CALLBACK *)slapi_ch_calloc;
  577. memalloc_fns.ldapmem_realloc = (LDAP_REALLOC_CALLBACK *)slapi_ch_realloc;
  578. memalloc_fns.ldapmem_free = (LDAP_FREE_CALLBACK *)_free_wrapper;
  579. }
  580. /*
  581. * MEMPOOL_EXPERIMENTAL:
  582. * These LDAP C SDK init function needs to be revisited.
  583. * In ldap_init called via ldapssl_init and prldap_init initializes
  584. * options and set default values including memalloc_fns, then it
  585. * initializes as sasl client by calling sasl_client_init. In
  586. * sasl_client_init, it creates mechlist using the malloc function
  587. * available at the moment which could mismatch the malloc/free functions
  588. * set later.
  589. */
  590. #endif
  591. #if defined(USE_OPENLDAP)
  592. if (ldapurl) {
  593. rc = ldap_initialize(&ld, ldapurl);
  594. if (rc) {
  595. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_init_ext",
  596. "Could not initialize LDAP connection to [%s]: %d:%s\n",
  597. ldapurl, rc, ldap_err2string(rc));
  598. goto done;
  599. }
  600. } else {
  601. char *makeurl = NULL;
  602. if (filename) {
  603. makeurl = slapi_ch_smprintf("ldapi://%s/", filename);
  604. } else { /* host port */
  605. makeurl = convert_to_openldap_uri(hostname, port, (secure == 1 ? "ldaps" : "ldap"));
  606. }
  607. rc = ldap_initialize(&ld, makeurl);
  608. if (rc) {
  609. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_init_ext",
  610. "Could not initialize LDAP connection to [%s]: %d:%s\n",
  611. makeurl, rc, ldap_err2string(rc));
  612. slapi_ch_free_string(&makeurl);
  613. goto done;
  614. }
  615. slapi_ch_free_string(&makeurl);
  616. }
  617. #else /* !USE_OPENLDAP */
  618. if (filename) {
  619. /* ldapi in mozldap client is not yet supported */
  620. } else if (secure == 1) {
  621. ld = ldapssl_init(hostname, port, secure);
  622. } else { /* regular ldap and/or starttls */
  623. /*
  624. * Leverage the libprldap layer to take care of all the NSPR
  625. * integration.
  626. * Note that ldapssl_init() uses libprldap implicitly.
  627. */
  628. ld = prldap_init(hostname, port, shared);
  629. }
  630. #endif /* !USE_OPENLDAP */
  631. /* Update snmp interaction table */
  632. if (hostname) {
  633. if (ld == NULL) {
  634. set_snmp_interaction_row((char *)hostname, port, -1);
  635. } else {
  636. set_snmp_interaction_row((char *)hostname, port, 0);
  637. }
  638. }
  639. if ((ld != NULL) && !filename) {
  640. /*
  641. * Set the outbound LDAP I/O timeout based on the server config.
  642. */
  643. int io_timeout_ms = config_get_outbound_ldap_io_timeout();
  644. if (io_timeout_ms > 0) {
  645. #if defined(USE_OPENLDAP)
  646. struct timeval tv;
  647. tv.tv_sec = io_timeout_ms / 1000;
  648. tv.tv_usec = (io_timeout_ms % 1000) * 1000;
  649. if (LDAP_OPT_SUCCESS != ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &tv)) {
  650. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_init_ext",
  651. "failed: unable to set outbound I/O "
  652. "timeout to %dms\n",
  653. io_timeout_ms);
  654. slapi_ldap_unbind(ld);
  655. ld = NULL;
  656. goto done;
  657. }
  658. #else /* !USE_OPENLDAP */
  659. if (prldap_set_session_option(ld, NULL, PRLDAP_OPT_IO_MAX_TIMEOUT,
  660. io_timeout_ms) != LDAP_SUCCESS) {
  661. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_init_ext",
  662. "failed: unable to set outbound I/O "
  663. "timeout to %dms\n",
  664. io_timeout_ms);
  665. slapi_ldap_unbind(ld);
  666. ld = NULL;
  667. goto done;
  668. }
  669. #endif /* !USE_OPENLDAP */
  670. }
  671. /*
  672. * Set SSL strength (server certificate validity checking).
  673. */
  674. if (secure > 0) {
  675. #if defined(USE_OPENLDAP)
  676. char *certdir = config_get_certdir();
  677. int optval = 0;
  678. #endif /* !USE_OPENLDAP */
  679. int ssl_strength = 0;
  680. LDAP *myld = NULL;
  681. /* we can only use the set functions below with a real
  682. LDAP* if it has already gone through ldapssl_init -
  683. so, use NULL if using starttls */
  684. if (secure == 1) {
  685. myld = ld;
  686. }
  687. if (config_get_ssl_check_hostname()) {
  688. /* check hostname against name in certificate */
  689. #if defined(USE_OPENLDAP)
  690. ssl_strength = LDAP_OPT_X_TLS_HARD;
  691. #else /* !USE_OPENLDAP */
  692. ssl_strength = LDAPSSL_AUTH_CNCHECK;
  693. #endif /* !USE_OPENLDAP */
  694. } else {
  695. /* verify certificate only */
  696. #if defined(USE_OPENLDAP)
  697. ssl_strength = LDAP_OPT_X_TLS_NEVER;
  698. #else /* !USE_OPENLDAP */
  699. ssl_strength = LDAPSSL_AUTH_CERT;
  700. #endif /* !USE_OPENLDAP */
  701. }
  702. #if defined(USE_OPENLDAP)
  703. if ((rc = ldap_set_option(ld, LDAP_OPT_X_TLS_NEWCTX, &optval))) {
  704. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_init_ext",
  705. "failed: unable to create new TLS context\n");
  706. }
  707. if ((rc = ldap_set_option(ld, LDAP_OPT_X_TLS_REQUIRE_CERT, &ssl_strength))) {
  708. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_init_ext",
  709. "failed: unable to set REQUIRE_CERT option to %d\n", ssl_strength);
  710. }
  711. /* tell it where our cert db is */
  712. if ((rc = ldap_set_option(ld, LDAP_OPT_X_TLS_CACERTDIR, certdir))) {
  713. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_init_ext",
  714. "failed: unable to set CACERTDIR option to %s\n", certdir);
  715. }
  716. slapi_ch_free_string(&certdir);
  717. #if defined(LDAP_OPT_X_TLS_PROTOCOL_MIN)
  718. optval = LDAP_OPT_X_TLS_PROTOCOL_SSL3;
  719. if ((rc = ldap_set_option(ld, LDAP_OPT_X_TLS_PROTOCOL_MIN, &optval))) {
  720. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_init_ext",
  721. "failed: unable to set minimum TLS protocol level to SSL3\n");
  722. }
  723. #endif /* LDAP_OPT_X_TLS_PROTOCOL_MIN */
  724. #else /* !USE_OPENLDAP */
  725. if ((rc = ldapssl_set_strength(myld, ssl_strength)) ||
  726. (rc = ldapssl_set_option(myld, SSL_ENABLE_SSL2, PR_FALSE)) ||
  727. (rc = ldapssl_set_option(myld, SSL_ENABLE_SSL3, PR_TRUE)) ||
  728. (rc = ldapssl_set_option(myld, SSL_ENABLE_TLS, PR_TRUE))) {
  729. int prerr = PR_GetError();
  730. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_init_ext",
  731. "failed: unable to set SSL options ("
  732. SLAPI_COMPONENT_NAME_NSPR " error %d - %s)\n",
  733. prerr, slapd_pr_strerror(prerr));
  734. }
  735. if (secure == 1) {
  736. /* tell bind code we are using SSL */
  737. ldap_set_option(ld, LDAP_OPT_SSL, LDAP_OPT_ON);
  738. }
  739. #endif /* !USE_OPENLDAP */
  740. }
  741. }
  742. if (ld && (secure == 2)) {
  743. /* We don't have a way to stash context data with the LDAP*, so we
  744. stash the information in the client controls (currently unused).
  745. We don't want to open the connection in ldap_init, since that's
  746. not the semantic - the connection is not usually opened until
  747. the first operation is sent, which is usually the bind - or
  748. in this case, the start_tls - so we stash the start_tls so
  749. we can do it in slapi_ldap_bind - note that this will get
  750. cleaned up when the LDAP* is disposed of
  751. */
  752. LDAPControl start_tls_dummy_ctrl;
  753. LDAPControl **clientctrls = NULL;
  754. /* returns copy of controls */
  755. ldap_get_option(ld, LDAP_OPT_CLIENT_CONTROLS, &clientctrls);
  756. start_tls_dummy_ctrl.ldctl_oid = START_TLS_OID;
  757. start_tls_dummy_ctrl.ldctl_value.bv_val = NULL;
  758. start_tls_dummy_ctrl.ldctl_value.bv_len = 0;
  759. start_tls_dummy_ctrl.ldctl_iscritical = 0;
  760. slapi_add_control_ext(&clientctrls, &start_tls_dummy_ctrl, 1);
  761. /* set option frees old list and copies the new list */
  762. ldap_set_option(ld, LDAP_OPT_CLIENT_CONTROLS, clientctrls);
  763. ldap_controls_free(clientctrls); /* free the copy */
  764. }
  765. slapi_log_error(SLAPI_LOG_SHELL, "slapi_ldap_init_ext",
  766. "Success: set up conn to [%s:%d]%s\n",
  767. hostname, port,
  768. (secure == 2) ? " using startTLS" :
  769. ((secure == 1) ? " using SSL" : ""));
  770. done:
  771. ldap_free_urldesc(ludp);
  772. return( ld );
  773. }
  774. /*
  775. * Function: slapi_ldap_init()
  776. * Description: just like ldap_ssl_init() but also arranges for the LDAP
  777. * session handle returned to be safely shareable by multiple threads
  778. * if "shared" is non-zero.
  779. * Returns:
  780. * an LDAP session handle (NULL if some local error occurs).
  781. */
  782. LDAP *
  783. slapi_ldap_init( char *ldaphost, int ldapport, int secure, int shared )
  784. {
  785. return slapi_ldap_init_ext(NULL, ldaphost, ldapport, secure, shared, NULL);
  786. }
  787. /*
  788. * Does the correct bind operation simple/sasl/cert depending
  789. * on the arguments passed in. If the user specified to use
  790. * starttls in init, this will do the starttls first. If using
  791. * ssl or client cert auth, this will initialize the client side
  792. * of that.
  793. */
  794. int
  795. slapi_ldap_bind(
  796. LDAP *ld, /* ldap connection */
  797. const char *bindid, /* usually a bind DN for simple bind */
  798. const char *creds, /* usually a password for simple bind */
  799. const char *mech, /* name of mechanism */
  800. LDAPControl **serverctrls, /* additional controls to send */
  801. LDAPControl ***returnedctrls, /* returned controls */
  802. struct timeval *timeout, /* timeout */
  803. int *msgidp /* pass in non-NULL for async handling */
  804. )
  805. {
  806. int rc = LDAP_SUCCESS;
  807. LDAPControl **clientctrls = NULL;
  808. int secure = 0;
  809. struct berval bvcreds = {0, NULL};
  810. LDAPMessage *result = NULL;
  811. struct berval *servercredp = NULL;
  812. /* do starttls if requested
  813. NOTE - starttls is an extop, not a control, but we don't have
  814. a place we can stash this information in the LDAP*, other
  815. than the currently unused clientctrls */
  816. ldap_get_option(ld, LDAP_OPT_CLIENT_CONTROLS, &clientctrls);
  817. if (clientctrls && clientctrls[0] &&
  818. slapi_control_present(clientctrls, START_TLS_OID, NULL, NULL)) {
  819. secure = 2;
  820. } else {
  821. #if defined(USE_OPENLDAP)
  822. /* openldap doesn't have a SSL/TLS yes/no flag - so grab the
  823. ldapurl, parse it, and see if it is a secure one */
  824. char *ldapurl = NULL;
  825. ldap_get_option(ld, LDAP_OPT_URI, &ldapurl);
  826. if (ldapurl && !PL_strncasecmp(ldapurl, "ldaps", 5)) {
  827. secure = 1;
  828. }
  829. slapi_ch_free_string(&ldapurl);
  830. #else /* !USE_OPENLDAP */
  831. ldap_get_option(ld, LDAP_OPT_SSL, &secure);
  832. #endif
  833. }
  834. ldap_controls_free(clientctrls);
  835. ldap_set_option(ld, LDAP_OPT_CLIENT_CONTROLS, NULL);
  836. if ((secure > 0) && mech && !strcmp(mech, LDAP_SASL_EXTERNAL)) {
  837. /* SSL connections will use the server's security context
  838. and cert for client auth */
  839. rc = slapd_SSL_client_auth(ld);
  840. if (rc != 0) {
  841. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  842. "Error: could not configure the server for cert "
  843. "auth - error %d - make sure the server is "
  844. "correctly configured for SSL/TLS\n", rc);
  845. goto done;
  846. } else {
  847. slapi_log_error(SLAPI_LOG_SHELL, "slapi_ldap_bind",
  848. "Set up conn to use client auth\n");
  849. }
  850. bvcreds.bv_val = NULL; /* ignore username and passed in creds */
  851. bvcreds.bv_len = 0; /* for external auth */
  852. bindid = NULL;
  853. } else { /* other type of auth */
  854. bvcreds.bv_val = (char *)creds;
  855. bvcreds.bv_len = creds ? strlen(creds) : 0;
  856. }
  857. if (secure == 2) { /* send start tls */
  858. rc = ldap_start_tls_s(ld, NULL /* serverctrls?? */, NULL);
  859. if (LDAP_SUCCESS != rc) {
  860. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  861. "Error: could not send startTLS request: "
  862. "error %d (%s)\n",
  863. rc, ldap_err2string(rc));
  864. goto done;
  865. }
  866. slapi_log_error(SLAPI_LOG_SHELL, "slapi_ldap_bind",
  867. "startTLS started on connection\n");
  868. }
  869. /* The connection has been set up - now do the actual bind, depending on
  870. the mechanism and arguments */
  871. if (!mech || (mech == LDAP_SASL_SIMPLE) ||
  872. !strcmp(mech, LDAP_SASL_EXTERNAL)) {
  873. int mymsgid = 0;
  874. slapi_log_error(SLAPI_LOG_SHELL, "slapi_ldap_bind",
  875. "attempting %s bind with id [%s] creds [%s]\n",
  876. mech ? mech : "SIMPLE",
  877. bindid, creds);
  878. if ((rc = ldap_sasl_bind(ld, bindid, mech, &bvcreds, serverctrls,
  879. NULL /* clientctrls */, &mymsgid))) {
  880. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  881. "Error: could not send bind request for id "
  882. "[%s] mech [%s]: error %d (%s) %d (%s) %d (%s)\n",
  883. bindid ? bindid : "(anon)",
  884. mech ? mech : "SIMPLE",
  885. rc, ldap_err2string(rc),
  886. PR_GetError(), slapd_pr_strerror(PR_GetError()),
  887. errno, slapd_system_strerror(errno));
  888. goto done;
  889. }
  890. if (msgidp) { /* let caller process result */
  891. *msgidp = mymsgid;
  892. } else { /* process results */
  893. rc = ldap_result(ld, mymsgid, LDAP_MSG_ALL, timeout, &result);
  894. if (-1 == rc) { /* error */
  895. rc = slapi_ldap_get_lderrno(ld, NULL, NULL);
  896. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  897. "Error reading bind response for id "
  898. "[%s] mech [%s]: error %d (%s)\n",
  899. bindid ? bindid : "(anon)",
  900. mech ? mech : "SIMPLE",
  901. rc, ldap_err2string(rc));
  902. goto done;
  903. } else if (rc == 0) { /* timeout */
  904. rc = LDAP_TIMEOUT;
  905. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  906. "Error: timeout after [%ld.%ld] seconds reading "
  907. "bind response for [%s] mech [%s]\n",
  908. timeout ? timeout->tv_sec : 0,
  909. timeout ? timeout->tv_usec : 0,
  910. bindid ? bindid : "(anon)",
  911. mech ? mech : "SIMPLE");
  912. goto done;
  913. }
  914. /* if we got here, we were able to read success result */
  915. /* Get the controls sent by the server if requested */
  916. if (returnedctrls) {
  917. if ((rc = ldap_parse_result(ld, result, &rc, NULL, NULL,
  918. NULL, returnedctrls,
  919. 0)) != LDAP_SUCCESS) {
  920. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  921. "Error: could not bind id "
  922. "[%s] mech [%s]: error %d (%s)\n",
  923. bindid ? bindid : "(anon)",
  924. mech ? mech : "SIMPLE",
  925. rc, ldap_err2string(rc));
  926. goto done;
  927. }
  928. }
  929. /* parse the bind result and get the ldap error code */
  930. if ((rc = ldap_parse_sasl_bind_result(ld, result, &servercredp,
  931. 0))) {
  932. rc = slapi_ldap_get_lderrno(ld, NULL, NULL);
  933. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  934. "Error: could not read bind results for id "
  935. "[%s] mech [%s]: error %d (%s)\n",
  936. bindid ? bindid : "(anon)",
  937. mech ? mech : "SIMPLE",
  938. rc, ldap_err2string(rc));
  939. goto done;
  940. }
  941. }
  942. } else {
  943. /* a SASL mech - set the sasl ssf to 0 if using TLS/SSL */
  944. /* openldap supports tls + sasl security */
  945. #if !defined(USE_OPENLDAP)
  946. if (secure) {
  947. sasl_ssf_t max_ssf = 0;
  948. ldap_set_option(ld, LDAP_OPT_X_SASL_SSF_MAX, &max_ssf);
  949. }
  950. #endif
  951. rc = slapd_ldap_sasl_interactive_bind(ld, bindid, creds, mech,
  952. serverctrls, returnedctrls,
  953. msgidp);
  954. if (LDAP_SUCCESS != rc) {
  955. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  956. "Error: could not perform interactive bind for id "
  957. "[%s] mech [%s]: error %d (%s)\n",
  958. bindid ? bindid : "(anon)",
  959. mech, /* mech cannot be SIMPLE here */
  960. rc, ldap_err2string(rc));
  961. }
  962. }
  963. done:
  964. slapi_ch_bvfree(&servercredp);
  965. ldap_msgfree(result);
  966. return rc;
  967. }
  968. void
  969. slapi_add_auth_response_control( Slapi_PBlock *pb, const char *binddn )
  970. {
  971. LDAPControl arctrl;
  972. char dnbuf_fixedsize[ 512 ], *dnbuf, *dnbuf_dynamic = NULL;
  973. size_t dnlen;
  974. if ( NULL == binddn ) {
  975. binddn = "";
  976. }
  977. dnlen = strlen( binddn );
  978. /*
  979. * According to draft-weltman-ldapv3-auth-response-03.txt section
  980. * 4 (Authentication Response Control):
  981. *
  982. * The controlType is "2.16.840.1.113730.3.4.15". If the bind request
  983. * succeeded and resulted in an identity (not anonymous), the
  984. * controlValue contains the authorization identity [AUTH] granted to
  985. * the requestor. If the bind request resulted in anonymous
  986. * authentication, the controlValue field is a string of zero length.
  987. *
  988. * [AUTH] is a reference to RFC 2829, which in section 9 defines
  989. * authorization identity as:
  990. *
  991. *
  992. * The authorization identity is a string in the UTF-8 character set,
  993. * corresponding to the following ABNF [7]:
  994. *
  995. * ; Specific predefined authorization (authz) id schemes are
  996. * ; defined below -- new schemes may be defined in the future.
  997. *
  998. * authzId = dnAuthzId / uAuthzId
  999. *
  1000. * ; distinguished-name-based authz id.
  1001. * dnAuthzId = "dn:" dn
  1002. * dn = utf8string ; with syntax defined in RFC 2253
  1003. *
  1004. * ; unspecified userid, UTF-8 encoded.
  1005. * uAuthzId = "u:" userid
  1006. * userid = utf8string ; syntax unspecified
  1007. *
  1008. * A utf8string is defined to be the UTF-8 encoding of one or more ISO
  1009. * 10646 characters.
  1010. *
  1011. * We always map identities to DNs, so we always use the dnAuthzId form.
  1012. */
  1013. arctrl.ldctl_oid = LDAP_CONTROL_AUTH_RESPONSE;
  1014. arctrl.ldctl_iscritical = 0;
  1015. if ( dnlen == 0 ) { /* anonymous -- return zero length value */
  1016. arctrl.ldctl_value.bv_val = "";
  1017. arctrl.ldctl_value.bv_len = 0;
  1018. } else { /* mapped to a DN -- return "dn:<DN>" */
  1019. if ( 3 + dnlen < sizeof( dnbuf_fixedsize )) {
  1020. dnbuf = dnbuf_fixedsize;
  1021. } else {
  1022. dnbuf = dnbuf_dynamic = slapi_ch_malloc( 4 + dnlen );
  1023. }
  1024. strcpy( dnbuf, "dn:" );
  1025. strcpy( dnbuf + 3, binddn );
  1026. arctrl.ldctl_value.bv_val = dnbuf;
  1027. arctrl.ldctl_value.bv_len = 3 + dnlen;
  1028. }
  1029. if ( slapi_pblock_set( pb, SLAPI_ADD_RESCONTROL, &arctrl ) != 0 ) {
  1030. slapi_log_error( SLAPI_LOG_FATAL, "bind",
  1031. "unable to add authentication response control" );
  1032. }
  1033. if ( NULL != dnbuf_dynamic ) {
  1034. slapi_ch_free_string( &dnbuf_dynamic );
  1035. }
  1036. }
  1037. /* the following implements the client side of sasl bind, for LDAP server
  1038. -> LDAP server SASL */
  1039. typedef struct {
  1040. char *mech;
  1041. char *authid;
  1042. char *username;
  1043. char *passwd;
  1044. char *realm;
  1045. } ldapSaslInteractVals;
  1046. #ifdef HAVE_KRB5
  1047. static void set_krb5_creds(
  1048. const char *authid,
  1049. const char *username,
  1050. const char *passwd,
  1051. const char *realm,
  1052. ldapSaslInteractVals *vals
  1053. );
  1054. #endif
  1055. static void *
  1056. ldap_sasl_set_interact_vals(LDAP *ld, const char *mech, const char *authid,
  1057. const char *username, const char *passwd,
  1058. const char *realm)
  1059. {
  1060. ldapSaslInteractVals *vals = NULL;
  1061. char *idprefix = "";
  1062. vals = (ldapSaslInteractVals *)
  1063. slapi_ch_calloc(1, sizeof(ldapSaslInteractVals));
  1064. if (!vals) {
  1065. return NULL;
  1066. }
  1067. if (mech) {
  1068. vals->mech = slapi_ch_strdup(mech);
  1069. } else {
  1070. ldap_get_option(ld, LDAP_OPT_X_SASL_MECH, &vals->mech);
  1071. }
  1072. if (vals->mech && !strcasecmp(vals->mech, "DIGEST-MD5")) {
  1073. idprefix = "dn:"; /* prefix name and id with this string */
  1074. }
  1075. if (authid) { /* use explicit passed in value */
  1076. vals->authid = slapi_ch_smprintf("%s%s", idprefix, authid);
  1077. } else { /* use option value if any */
  1078. ldap_get_option(ld, LDAP_OPT_X_SASL_AUTHCID, &vals->authid);
  1079. if (!vals->authid) {
  1080. /* get server user id? */
  1081. vals->authid = slapi_ch_strdup("");
  1082. }
  1083. }
  1084. if (username) { /* use explicit passed in value */
  1085. vals->username = slapi_ch_smprintf("%s%s", idprefix, username);
  1086. } else { /* use option value if any */
  1087. ldap_get_option(ld, LDAP_OPT_X_SASL_AUTHZID, &vals->username);
  1088. if (!vals->username) { /* use default sasl value */
  1089. vals->username = slapi_ch_strdup("");
  1090. }
  1091. }
  1092. if (passwd) {
  1093. vals->passwd = slapi_ch_strdup(passwd);
  1094. } else {
  1095. vals->passwd = slapi_ch_strdup("");
  1096. }
  1097. if (realm) {
  1098. vals->realm = slapi_ch_strdup(realm);
  1099. } else {
  1100. ldap_get_option(ld, LDAP_OPT_X_SASL_REALM, &vals->realm);
  1101. if (!vals->realm) { /* use default sasl value */
  1102. vals->realm = slapi_ch_strdup("");
  1103. }
  1104. }
  1105. #ifdef HAVE_KRB5
  1106. if (mech && !strcmp(mech, "GSSAPI")) {
  1107. set_krb5_creds(authid, username, passwd, realm, vals);
  1108. }
  1109. #endif /* HAVE_KRB5 */
  1110. return vals;
  1111. }
  1112. static void
  1113. ldap_sasl_free_interact_vals(void *defaults)
  1114. {
  1115. ldapSaslInteractVals *vals = defaults;
  1116. if (vals) {
  1117. slapi_ch_free_string(&vals->mech);
  1118. slapi_ch_free_string(&vals->authid);
  1119. slapi_ch_free_string(&vals->username);
  1120. slapi_ch_free_string(&vals->passwd);
  1121. slapi_ch_free_string(&vals->realm);
  1122. slapi_ch_free(&defaults);
  1123. }
  1124. }
  1125. static int
  1126. ldap_sasl_get_val(ldapSaslInteractVals *vals, sasl_interact_t *interact, unsigned flags)
  1127. {
  1128. const char *defvalue = interact->defresult;
  1129. int authtracelevel = SLAPI_LOG_SHELL; /* special auth tracing */
  1130. if (vals != NULL) {
  1131. switch(interact->id) {
  1132. case SASL_CB_AUTHNAME:
  1133. defvalue = vals->authid;
  1134. slapi_log_error(authtracelevel, "ldap_sasl_get_val",
  1135. "Using value [%s] for SASL_CB_AUTHNAME\n",
  1136. defvalue ? defvalue : "(null)");
  1137. break;
  1138. case SASL_CB_USER:
  1139. defvalue = vals->username;
  1140. slapi_log_error(authtracelevel, "ldap_sasl_get_val",
  1141. "Using value [%s] for SASL_CB_USER\n",
  1142. defvalue ? defvalue : "(null)");
  1143. break;
  1144. case SASL_CB_PASS:
  1145. defvalue = vals->passwd;
  1146. slapi_log_error(authtracelevel, "ldap_sasl_get_val",
  1147. "Using value [%s] for SASL_CB_PASS\n",
  1148. defvalue ? defvalue : "(null)");
  1149. break;
  1150. case SASL_CB_GETREALM:
  1151. defvalue = vals->realm;
  1152. slapi_log_error(authtracelevel, "ldap_sasl_get_val",
  1153. "Using value [%s] for SASL_CB_GETREALM\n",
  1154. defvalue ? defvalue : "(null)");
  1155. break;
  1156. }
  1157. }
  1158. if (defvalue != NULL) {
  1159. interact->result = defvalue;
  1160. if ((char *)interact->result == NULL)
  1161. return (LDAP_NO_MEMORY);
  1162. interact->len = strlen((char *)(interact->result));
  1163. }
  1164. return (LDAP_SUCCESS);
  1165. }
  1166. static int
  1167. ldap_sasl_interact_cb(LDAP *ld, unsigned flags, void *defaults, void *prompts)
  1168. {
  1169. sasl_interact_t *interact = NULL;
  1170. ldapSaslInteractVals *sasldefaults = defaults;
  1171. int rc;
  1172. if (prompts == NULL) {
  1173. return (LDAP_PARAM_ERROR);
  1174. }
  1175. for (interact = prompts; interact->id != SASL_CB_LIST_END; interact++) {
  1176. /* Obtain the default value */
  1177. if ((rc = ldap_sasl_get_val(sasldefaults, interact, flags)) != LDAP_SUCCESS) {
  1178. return (rc);
  1179. }
  1180. }
  1181. return (LDAP_SUCCESS);
  1182. }
  1183. /* figure out from the context and this error if we should
  1184. attempt to retry the bind */
  1185. static int
  1186. can_retry_bind(LDAP *ld, const char *mech, const char *bindid,
  1187. const char *creds, int rc, const char *errmsg)
  1188. {
  1189. int localrc = 0;
  1190. if (errmsg && strstr(errmsg, "Ticket expired")) {
  1191. localrc = 1;
  1192. }
  1193. return localrc;
  1194. }
  1195. int
  1196. slapd_ldap_sasl_interactive_bind(
  1197. LDAP *ld, /* ldap connection */
  1198. const char *bindid, /* usually a bind DN for simple bind */
  1199. const char *creds, /* usually a password for simple bind */
  1200. const char *mech, /* name of mechanism */
  1201. LDAPControl **serverctrls, /* additional controls to send */
  1202. LDAPControl ***returnedctrls, /* returned controls */
  1203. int *msgidp /* pass in non-NULL for async handling */
  1204. )
  1205. {
  1206. int rc = LDAP_SUCCESS;
  1207. int tries = 0;
  1208. while (tries < 2) {
  1209. void *defaults = ldap_sasl_set_interact_vals(ld, mech, bindid, bindid,
  1210. creds, NULL);
  1211. /* have to first set the defaults used by the callback function */
  1212. /* call the bind function */
  1213. /* openldap does not have the ext version - not sure how to get the
  1214. returned controls */
  1215. #if defined(USE_OPENLDAP)
  1216. rc = ldap_sasl_interactive_bind_s(ld, bindid, mech, serverctrls,
  1217. NULL, LDAP_SASL_QUIET,
  1218. ldap_sasl_interact_cb, defaults);
  1219. #else
  1220. rc = ldap_sasl_interactive_bind_ext_s(ld, bindid, mech, serverctrls,
  1221. NULL, LDAP_SASL_QUIET,
  1222. ldap_sasl_interact_cb, defaults,
  1223. returnedctrls);
  1224. #endif
  1225. ldap_sasl_free_interact_vals(defaults);
  1226. if (LDAP_SUCCESS != rc) {
  1227. char *errmsg = NULL;
  1228. rc = slapi_ldap_get_lderrno(ld, NULL, &errmsg);
  1229. slapi_log_error(SLAPI_LOG_FATAL, "slapd_ldap_sasl_interactive_bind",
  1230. "Error: could not perform interactive bind for id "
  1231. "[%s] mech [%s]: error %d (%s) (%s)\n",
  1232. bindid ? bindid : "(anon)",
  1233. mech ? mech : "SIMPLE",
  1234. rc, ldap_err2string(rc), errmsg);
  1235. if (can_retry_bind(ld, mech, bindid, creds, rc, errmsg)) {
  1236. ; /* pass through to retry one time */
  1237. } else {
  1238. break; /* done - fail - cannot retry */
  1239. }
  1240. } else {
  1241. break; /* done - success */
  1242. }
  1243. tries++;
  1244. }
  1245. return rc;
  1246. }
  1247. #ifdef HAVE_KRB5
  1248. #include <krb5.h>
  1249. /* for some reason this is not in the public API?
  1250. but it is documented e.g. man kinit */
  1251. #ifndef KRB5_ENV_CCNAME
  1252. #define KRB5_ENV_CCNAME "KRB5CCNAME"
  1253. #endif
  1254. static void
  1255. show_one_credential(int authtracelevel,
  1256. krb5_context ctx, krb5_creds *cred)
  1257. {
  1258. char *logname = "show_one_credential";
  1259. krb5_error_code rc;
  1260. char *name = NULL, *sname = NULL;
  1261. char startts[BUFSIZ], endts[BUFSIZ], renewts[BUFSIZ];
  1262. if ((rc = krb5_unparse_name(ctx, cred->client, &name))) {
  1263. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1264. "Could not get client name from credential: %d (%s)\n",
  1265. rc, error_message(rc));
  1266. goto cleanup;
  1267. }
  1268. if ((rc = krb5_unparse_name(ctx, cred->server, &sname))) {
  1269. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1270. "Could not get server name from credential: %d (%s)\n",
  1271. rc, error_message(rc));
  1272. goto cleanup;
  1273. }
  1274. if (!cred->times.starttime) {
  1275. cred->times.starttime = cred->times.authtime;
  1276. }
  1277. krb5_timestamp_to_sfstring((krb5_timestamp)cred->times.starttime,
  1278. startts, sizeof(startts), NULL);
  1279. krb5_timestamp_to_sfstring((krb5_timestamp)cred->times.endtime,
  1280. endts, sizeof(endts), NULL);
  1281. krb5_timestamp_to_sfstring((krb5_timestamp)cred->times.renew_till,
  1282. renewts, sizeof(renewts), NULL);
  1283. slapi_log_error(authtracelevel, logname,
  1284. "\tKerberos credential: client [%s] server [%s] "
  1285. "start time [%s] end time [%s] renew time [%s] "
  1286. "flags [0x%x]\n", name, sname, startts, endts,
  1287. renewts, (uint32_t)cred->ticket_flags);
  1288. cleanup:
  1289. krb5_free_unparsed_name(ctx, name);
  1290. krb5_free_unparsed_name(ctx, sname);
  1291. return;
  1292. }
  1293. /*
  1294. * Call this after storing the credentials in the cache
  1295. */
  1296. static void
  1297. show_cached_credentials(int authtracelevel,
  1298. krb5_context ctx, krb5_ccache cc,
  1299. krb5_principal princ)
  1300. {
  1301. char *logname = "show_cached_credentials";
  1302. krb5_error_code rc = 0;
  1303. krb5_creds creds;
  1304. krb5_cc_cursor cur;
  1305. char *princ_name = NULL;
  1306. if ((rc = krb5_unparse_name(ctx, princ, &princ_name))) {
  1307. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1308. "Could not get principal name from principal: %d (%s)\n",
  1309. rc, error_message(rc));
  1310. goto cleanup;
  1311. }
  1312. slapi_log_error(authtracelevel, logname,
  1313. "Ticket cache: %s:%s\nDefault principal: %s\n\n",
  1314. krb5_cc_get_type(ctx, cc),
  1315. krb5_cc_get_name(ctx, cc), princ_name);
  1316. if ((rc = krb5_cc_start_seq_get(ctx, cc, &cur))) {
  1317. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1318. "Could not get cursor to iterate cached credentials: "
  1319. "%d (%s)\n", rc, error_message(rc));
  1320. goto cleanup;
  1321. }
  1322. while (!(rc = krb5_cc_next_cred(ctx, cc, &cur, &creds))) {
  1323. show_one_credential(authtracelevel, ctx, &creds);
  1324. krb5_free_cred_contents(ctx, &creds);
  1325. }
  1326. if (rc == KRB5_CC_END) {
  1327. if ((rc = krb5_cc_end_seq_get(ctx, cc, &cur))) {
  1328. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1329. "Could not close cached credentials cursor: "
  1330. "%d (%s)\n", rc, error_message(rc));
  1331. goto cleanup;
  1332. }
  1333. }
  1334. cleanup:
  1335. krb5_free_unparsed_name(ctx, princ_name);
  1336. return;
  1337. }
  1338. static int
  1339. looks_like_a_princ_name(const char *name)
  1340. {
  1341. /* a valid principal name will be a non-empty string
  1342. that doesn't have a = in it (which will likely be
  1343. a bind DN) */
  1344. return (name && *name && !strchr(name, '='));
  1345. }
  1346. static int
  1347. credentials_are_valid(
  1348. krb5_context ctx,
  1349. krb5_ccache cc,
  1350. krb5_principal princ,
  1351. const char *princ_name,
  1352. int *rc
  1353. )
  1354. {
  1355. char *logname = "credentials_are_valid";
  1356. int myrc = 0;
  1357. krb5_creds mcreds; /* match these values */
  1358. krb5_creds creds; /* returned creds */
  1359. char *tgs_princ_name = NULL;
  1360. krb5_timestamp currenttime;
  1361. int authtracelevel = SLAPI_LOG_SHELL; /* special auth tracing */
  1362. int realm_len;
  1363. char *realm_str;
  1364. int time_buffer = 30; /* seconds - go ahead and renew if creds are
  1365. about to expire */
  1366. memset(&mcreds, 0, sizeof(mcreds));
  1367. memset(&creds, 0, sizeof(creds));
  1368. *rc = 0;
  1369. if (!cc) {
  1370. /* ok - no error */
  1371. goto cleanup;
  1372. }
  1373. /* have to construct the tgs server principal in
  1374. order to set mcreds.server required in order
  1375. to use krb5_cc_retrieve_creds() */
  1376. /* get default realm first */
  1377. realm_len = krb5_princ_realm(ctx, princ)->length;
  1378. realm_str = krb5_princ_realm(ctx, princ)->data;
  1379. tgs_princ_name = slapi_ch_smprintf("%s/%*s@%*s", KRB5_TGS_NAME,
  1380. realm_len, realm_str,
  1381. realm_len, realm_str);
  1382. if ((*rc = krb5_parse_name(ctx, tgs_princ_name, &mcreds.server))) {
  1383. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1384. "Could parse principal [%s]: %d (%s)\n",
  1385. tgs_princ_name, *rc, error_message(*rc));
  1386. goto cleanup;
  1387. }
  1388. mcreds.client = princ;
  1389. if ((*rc = krb5_cc_retrieve_cred(ctx, cc, 0, &mcreds, &creds))) {
  1390. if (*rc == KRB5_CC_NOTFOUND) {
  1391. /* ok - no creds for this princ in the cache */
  1392. *rc = 0;
  1393. }
  1394. goto cleanup;
  1395. }
  1396. /* have the creds - now look at the timestamp */
  1397. if ((*rc = krb5_timeofday(ctx, &currenttime))) {
  1398. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1399. "Could not get current time: %d (%s)\n",
  1400. *rc, error_message(*rc));
  1401. goto cleanup;
  1402. }
  1403. if (currenttime > (creds.times.endtime + time_buffer)) {
  1404. slapi_log_error(authtracelevel, logname,
  1405. "Credentials for [%s] have expired or will soon "
  1406. "expire - now [%d] endtime [%d]\n", princ_name,
  1407. currenttime, creds.times.endtime);
  1408. goto cleanup;
  1409. }
  1410. myrc = 1; /* credentials are valid */
  1411. cleanup:
  1412. krb5_free_cred_contents(ctx, &creds);
  1413. slapi_ch_free_string(&tgs_princ_name);
  1414. if (mcreds.server) {
  1415. krb5_free_principal(ctx, mcreds.server);
  1416. }
  1417. return myrc;
  1418. }
  1419. /*
  1420. * This implementation assumes that we want to use the
  1421. * keytab from the default keytab env. var KRB5_KTNAME
  1422. * as. This code is very similar to kinit -k -t. We
  1423. * get a krb context, get the default keytab, get
  1424. * the credentials from the keytab, authenticate with
  1425. * those credentials, create a ccache, store the
  1426. * credentials in the ccache, and set the ccache
  1427. * env var to point to those credentials.
  1428. */
  1429. static void
  1430. set_krb5_creds(
  1431. const char *authid,
  1432. const char *username,
  1433. const char *passwd,
  1434. const char *realm,
  1435. ldapSaslInteractVals *vals
  1436. )
  1437. {
  1438. char *logname = "set_krb5_creds";
  1439. const char *cc_type = "MEMORY"; /* keep cred cache in memory */
  1440. krb5_context ctx = NULL;
  1441. krb5_ccache cc = NULL;
  1442. krb5_principal princ = NULL;
  1443. char *princ_name = NULL;
  1444. krb5_error_code rc = 0;
  1445. krb5_creds creds;
  1446. krb5_keytab kt = NULL;
  1447. char *cc_name = NULL;
  1448. char ktname[MAX_KEYTAB_NAME_LEN];
  1449. static char cc_env_name[1024+32]; /* size from ccdefname.c */
  1450. int new_ccache = 0;
  1451. int authtracelevel = SLAPI_LOG_SHELL; /* special auth tracing
  1452. not sure what shell was
  1453. used for, does not
  1454. appear to be used
  1455. currently */
  1456. /* probably have to put a mutex around this whole thing, to avoid
  1457. problems with reentrancy, since we are setting a "global"
  1458. variable via an environment variable */
  1459. /* wipe this out so we can safely free it later if we
  1460. short circuit */
  1461. memset(&creds, 0, sizeof(creds));
  1462. /* initialize the kerberos context */
  1463. if ((rc = krb5_init_context(&ctx))) {
  1464. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1465. "Could not init Kerberos context: %d (%s)\n",
  1466. rc, error_message(rc));
  1467. goto cleanup;
  1468. }
  1469. /* see if there is already a ccache, and see if there are
  1470. creds in the ccache */
  1471. /* grab the default ccache - note: this does not open the cache */
  1472. if ((rc = krb5_cc_default(ctx, &cc))) {
  1473. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1474. "Could not get default Kerberos ccache: %d (%s)\n",
  1475. rc, error_message(rc));
  1476. goto cleanup;
  1477. }
  1478. /* use this cache - construct the full cache name */
  1479. cc_name = slapi_ch_smprintf("%s:%s", krb5_cc_get_type(ctx, cc),
  1480. krb5_cc_get_name(ctx, cc));
  1481. /* grab the principal from the ccache - will fail if there
  1482. is no ccache */
  1483. if ((rc = krb5_cc_get_principal(ctx, cc, &princ))) {
  1484. if (KRB5_FCC_NOFILE == rc) { /* no cache - ok */
  1485. slapi_log_error(authtracelevel, logname,
  1486. "The default credentials cache [%s] not found: "
  1487. "will create a new one.\n", cc_name);
  1488. /* close the cache - we will create a new one below */
  1489. krb5_cc_close(ctx, cc);
  1490. cc = NULL;
  1491. slapi_ch_free_string(&cc_name);
  1492. /* fall through to the keytab auth code below */
  1493. } else { /* fatal */
  1494. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1495. "Could not open default Kerberos ccache [%s]: "
  1496. "%d (%s)\n", cc_name, rc, error_message(rc));
  1497. goto cleanup;
  1498. }
  1499. } else { /* have a valid ccache && found principal */
  1500. if ((rc = krb5_unparse_name(ctx, princ, &princ_name))) {
  1501. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1502. "Unable to get name of principal from ccache [%s]: "
  1503. "%d (%s)\n", cc_name, rc, error_message(rc));
  1504. goto cleanup;
  1505. }
  1506. slapi_log_error(authtracelevel, logname,
  1507. "Using principal [%s] from ccache [%s]\n",
  1508. princ_name, cc_name);
  1509. }
  1510. /* if this is not our type of ccache, there is nothing more we can
  1511. do - just punt and let sasl/gssapi take it's course - this
  1512. usually means there has been an external kinit e.g. in the
  1513. start up script, and it is the responsibility of the script to
  1514. renew those credentials or face lots of sasl/gssapi failures
  1515. This means, however, that the caller MUST MAKE SURE THERE IS NO
  1516. DEFAULT CCACHE FILE or the server will attempt to use it (and
  1517. likely fail) - THERE MUST BE NO DEFAULT CCACHE FILE IF YOU WANT
  1518. THE SERVER TO AUTHENTICATE WITH THE KEYTAB
  1519. NOTE: cc types are case sensitive and always upper case */
  1520. if (cc && strcmp(cc_type, krb5_cc_get_type(ctx, cc))) {
  1521. static int errmsgcounter = 0;
  1522. int loglevel = SLAPI_LOG_FATAL;
  1523. if (errmsgcounter) {
  1524. loglevel = authtracelevel;
  1525. }
  1526. /* make sure we log this message once, in case the user has
  1527. done something unintended, we want to make sure they know
  1528. about it. However, if the user knows what he/she is doing,
  1529. by using an external ccache file, they probably don't want
  1530. to be notified with an error every time. */
  1531. slapi_log_error(loglevel, logname,
  1532. "The server will use the external SASL/GSSAPI "
  1533. "credentials cache [%s:%s]. If you want the "
  1534. "server to automatically authenticate with its "
  1535. "keytab, you must remove this cache. If you "
  1536. "did not intend to use this cache, you will likely "
  1537. "see many SASL/GSSAPI authentication failures.\n",
  1538. krb5_cc_get_type(ctx, cc), krb5_cc_get_name(ctx, cc));
  1539. errmsgcounter++;
  1540. goto cleanup;
  1541. }
  1542. /* need to figure out which principal to use
  1543. 1) use the one from the ccache
  1544. 2) use username
  1545. 3) construct one in the form ldap/fqdn@REALM
  1546. */
  1547. if (!princ && looks_like_a_princ_name(username) &&
  1548. (rc = krb5_parse_name(ctx, username, &princ))) {
  1549. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1550. "Error: could not convert [%s] into a kerberos "
  1551. "principal: %d (%s)\n", username,
  1552. rc, error_message(rc));
  1553. goto cleanup;
  1554. }
  1555. /* if still no principal, construct one */
  1556. if (!princ &&
  1557. (rc = krb5_sname_to_principal(ctx, NULL, "ldap",
  1558. KRB5_NT_SRV_HST, &princ))) {
  1559. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1560. "Error: could not construct ldap service "
  1561. "principal: %d (%s)\n", rc, error_message(rc));
  1562. goto cleanup;
  1563. }
  1564. if ((rc = krb5_unparse_name(ctx, princ, &princ_name))) {
  1565. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1566. "Unable to get name of principal: "
  1567. "%d (%s)\n", rc, error_message(rc));
  1568. goto cleanup;
  1569. }
  1570. slapi_log_error(authtracelevel, logname,
  1571. "Using principal named [%s]\n", princ_name);
  1572. /* grab the credentials from the ccache, if any -
  1573. if the credentials are still valid, we do not have
  1574. to authenticate again */
  1575. if (credentials_are_valid(ctx, cc, princ, princ_name, &rc)) {
  1576. slapi_log_error(authtracelevel, logname,
  1577. "Credentials for principal [%s] are still "
  1578. "valid - no auth is necessary.\n",
  1579. princ_name);
  1580. goto cleanup;
  1581. } else if (rc) { /* some error other than "there are no credentials" */
  1582. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1583. "Unable to verify cached credentials for "
  1584. "principal [%s]: %d (%s)\n", princ_name,
  1585. rc, error_message(rc));
  1586. goto cleanup;
  1587. }
  1588. /* find our default keytab */
  1589. if ((rc = krb5_kt_default(ctx, &kt))) {
  1590. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1591. "Unable to get default keytab: %d (%s)\n",
  1592. rc, error_message(rc));
  1593. goto cleanup;
  1594. }
  1595. /* get name of keytab for debugging purposes */
  1596. if ((rc = krb5_kt_get_name(ctx, kt, ktname, sizeof(ktname)))) {
  1597. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1598. "Unable to get name of default keytab: %d (%s)\n",
  1599. rc, error_message(rc));
  1600. goto cleanup;
  1601. }
  1602. slapi_log_error(authtracelevel, logname,
  1603. "Using keytab named [%s]\n", ktname);
  1604. /* now do the actual kerberos authentication using
  1605. the keytab, and get the creds */
  1606. rc = krb5_get_init_creds_keytab(ctx, &creds, princ, kt,
  1607. 0, NULL, NULL);
  1608. if (rc) {
  1609. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1610. "Could not get initial credentials for principal [%s] "
  1611. "in keytab [%s]: %d (%s)\n",
  1612. princ_name, ktname, rc, error_message(rc));
  1613. goto cleanup;
  1614. }
  1615. /* completely done with the keytab now, close it */
  1616. krb5_kt_close(ctx, kt);
  1617. kt = NULL; /* no double free */
  1618. /* we now have the creds and the principal to which the
  1619. creds belong - use or allocate a new memory based
  1620. cache to hold the creds */
  1621. if (!cc_name) {
  1622. #if HAVE_KRB5_CC_NEW_UNIQUE
  1623. /* krb5_cc_new_unique is a new convenience function which
  1624. generates a new unique name and returns a memory
  1625. cache with that name */
  1626. if ((rc = krb5_cc_new_unique(ctx, cc_type, NULL, &cc))) {
  1627. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1628. "Could not create new unique memory ccache: "
  1629. "%d (%s)\n",
  1630. rc, error_message(rc));
  1631. goto cleanup;
  1632. }
  1633. cc_name = slapi_ch_smprintf("%s:%s", cc_type,
  1634. krb5_cc_get_name(ctx, cc));
  1635. #else
  1636. /* store the cache in memory - krb5_init_context uses malloc
  1637. to create the ctx, so the address should be unique enough
  1638. for our purposes */
  1639. if (!(cc_name = slapi_ch_smprintf("%s:%p", cc_type, ctx))) {
  1640. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1641. "Could create Kerberos memory ccache: "
  1642. "out of memory\n");
  1643. rc = 1;
  1644. goto cleanup;
  1645. }
  1646. #endif
  1647. slapi_log_error(authtracelevel, logname,
  1648. "Generated new memory ccache [%s]\n", cc_name);
  1649. new_ccache = 1; /* need to set this in env. */
  1650. } else {
  1651. slapi_log_error(authtracelevel, logname,
  1652. "Using existing ccache [%s]\n", cc_name);
  1653. }
  1654. /* krb5_cc_resolve is basically like an init -
  1655. this creates the cache structure, and creates a slot
  1656. for the cache in the static linked list in memory, if
  1657. there is not already a slot -
  1658. see cc_memory.c for details
  1659. cc could already have been created by new_unique above
  1660. */
  1661. if (!cc && (rc = krb5_cc_resolve(ctx, cc_name, &cc))) {
  1662. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1663. "Could not create ccache [%s]: %d (%s)\n",
  1664. cc_name, rc, error_message(rc));
  1665. goto cleanup;
  1666. }
  1667. /* wipe out previous contents of cache for this principal, if any */
  1668. if ((rc = krb5_cc_initialize(ctx, cc, princ))) {
  1669. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1670. "Could not initialize ccache [%s] for the new "
  1671. "credentials for principal [%s]: %d (%s)\n",
  1672. cc_name, princ_name, rc, error_message(rc));
  1673. goto cleanup;
  1674. }
  1675. /* store the credentials in the cache */
  1676. if ((rc = krb5_cc_store_cred(ctx, cc, &creds))) {
  1677. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1678. "Could not store the credentials in the "
  1679. "ccache [%s] for principal [%s]: %d (%s)\n",
  1680. cc_name, princ_name, rc, error_message(rc));
  1681. goto cleanup;
  1682. }
  1683. /* now, do a "klist" to show the credential information, and log it */
  1684. show_cached_credentials(authtracelevel, ctx, cc, princ);
  1685. /* set the CC env var to the value of the cc cache name */
  1686. /* since we can't pass krb5 context up and out of here
  1687. and down through the ldap sasl layer, we set this
  1688. env var so that calls to krb5_cc_default_name will
  1689. use this */
  1690. if (new_ccache) {
  1691. PR_snprintf(cc_env_name, sizeof(cc_env_name),
  1692. "%s=%s", KRB5_ENV_CCNAME, cc_name);
  1693. PR_SetEnv(cc_env_name);
  1694. slapi_log_error(authtracelevel, logname,
  1695. "Set new env for ccache: [%s]\n",
  1696. cc_env_name);
  1697. }
  1698. cleanup:
  1699. /* use NULL as username and authid */
  1700. slapi_ch_free_string(&vals->username);
  1701. slapi_ch_free_string(&vals->authid);
  1702. krb5_free_unparsed_name(ctx, princ_name);
  1703. if (kt) { /* NULL not allowed */
  1704. krb5_kt_close(ctx, kt);
  1705. }
  1706. if (creds.client == princ) {
  1707. creds.client = NULL;
  1708. }
  1709. krb5_free_cred_contents(ctx, &creds);
  1710. slapi_ch_free_string(&cc_name);
  1711. krb5_free_principal(ctx, princ);
  1712. if (cc) {
  1713. krb5_cc_close(ctx, cc);
  1714. }
  1715. if (ctx) { /* cannot pass NULL to free context */
  1716. krb5_free_context(ctx);
  1717. }
  1718. return;
  1719. }
  1720. #endif /* HAVE_KRB5 */