util.c 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035
  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. /* util.c -- utility functions -- functions available form libslapd */
  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. #include <ldap_ssl.h>
  57. #include <ldappr.h>
  58. #define UTIL_ESCAPE_NONE 0
  59. #define UTIL_ESCAPE_HEX 1
  60. #define UTIL_ESCAPE_BACKSLASH 2
  61. #if defined( _WIN32 )
  62. #define _PSEP "\\"
  63. #define _PSEP2 "\\\\"
  64. #define _CSEP '\\'
  65. #else
  66. #define _PSEP "/"
  67. #define _PSEP2 "//"
  68. #define _CSEP '/'
  69. #endif
  70. static int special_np(unsigned char c)
  71. {
  72. if(c < 32 || c > 126) {
  73. return UTIL_ESCAPE_HEX;
  74. } else if ((c== '"') || (c=='\\'))
  75. {
  76. return UTIL_ESCAPE_HEX;
  77. }
  78. return UTIL_ESCAPE_NONE;
  79. }
  80. static int special_np_and_punct(unsigned char c)
  81. {
  82. if (c < 32 || c > 126 || c == '*') return UTIL_ESCAPE_HEX;
  83. if (c == '\\' || c == '"') return UTIL_ESCAPE_BACKSLASH;
  84. return UTIL_ESCAPE_NONE;
  85. }
  86. static int special_filter(unsigned char c)
  87. {
  88. /*
  89. * Escape all non-printing chars and double-quotes in addition
  90. * to those required by RFC 2254 so that we can use the string
  91. * in log files.
  92. */
  93. return (c < 32 ||
  94. c > 126 ||
  95. c == '*' ||
  96. c == '(' ||
  97. c == ')' ||
  98. c == '\\' ||
  99. c == '"') ? UTIL_ESCAPE_HEX : UTIL_ESCAPE_NONE;
  100. }
  101. static const char*
  102. do_escape_string (
  103. const char* str,
  104. int len, /* -1 means str is nul-terminated */
  105. char buf[BUFSIZ],
  106. int (*special)(unsigned char)
  107. )
  108. {
  109. const char* s;
  110. const char* last;
  111. int esc;
  112. if (str == NULL) {
  113. *buf = '\0';
  114. return buf;
  115. }
  116. if (len == -1) len = strlen (str);
  117. if (len == 0) return str;
  118. last = str + len - 1;
  119. for (s = str; s <= last; ++s) {
  120. if ( (esc = (*special)((unsigned char)*s))) {
  121. const char* first = str;
  122. char* bufNext = buf;
  123. int bufSpace = BUFSIZ - 4;
  124. while (1) {
  125. if (bufSpace < (s - first)) s = first + bufSpace - 1;
  126. if (s > first) {
  127. memcpy (bufNext, first, s - first);
  128. bufNext += (s - first);
  129. bufSpace -= (s - first);
  130. }
  131. if (s > last) {
  132. break;
  133. }
  134. do {
  135. *bufNext++ = '\\'; --bufSpace;
  136. if (bufSpace < 2) {
  137. memcpy (bufNext, "..", 2);
  138. bufNext += 2;
  139. goto bail;
  140. }
  141. if (esc == UTIL_ESCAPE_BACKSLASH) {
  142. *bufNext++ = *s; --bufSpace;
  143. } else { /* UTIL_ESCAPE_HEX */
  144. sprintf (bufNext, "%02x", (unsigned)*(unsigned char*)s);
  145. bufNext += 2; bufSpace -= 2;
  146. }
  147. } while (++s <= last &&
  148. (esc = (*special)((unsigned char)*s)));
  149. if (s > last) break;
  150. first = s;
  151. while ( (esc = (*special)((unsigned char)*s)) == UTIL_ESCAPE_NONE && s <= last) ++s;
  152. }
  153. bail:
  154. *bufNext = '\0';
  155. return buf;
  156. }
  157. }
  158. return str;
  159. }
  160. /*
  161. * Function: escape_string
  162. * Arguments: str: string
  163. * buf: a char array of BUFSIZ length, in which the escaped string will
  164. * be returned.
  165. * Returns: a pointer to buf, if str==NULL or it needed to be escaped, or
  166. * str itself otherwise.
  167. *
  168. * This function should only be used for generating loggable strings.
  169. */
  170. const char*
  171. escape_string (const char* str, char buf[BUFSIZ])
  172. {
  173. return do_escape_string(str,-1,buf,special_np);
  174. }
  175. const char*
  176. escape_string_with_punctuation(const char* str, char buf[BUFSIZ])
  177. {
  178. return do_escape_string(str,-1,buf,special_np_and_punct);
  179. }
  180. const char*
  181. escape_filter_value(const char* str, int len, char buf[BUFSIZ])
  182. {
  183. return do_escape_string(str,len,buf,special_filter);
  184. }
  185. /*
  186. ** This function takes a quoted attribute value of the form "abc",
  187. ** and strips off the enclosing quotes. It also deals with quoted
  188. ** characters by removing the preceeding '\' character.
  189. **
  190. */
  191. void
  192. strcpy_unescape_value( char *d, const char *s )
  193. {
  194. char *head = d;
  195. int gotesc = 0;
  196. const char *end = s + strlen(s);
  197. for ( ; *s; s++ )
  198. {
  199. switch ( *s )
  200. {
  201. case '\\':
  202. if ( gotesc ) {
  203. gotesc = 0;
  204. } else {
  205. gotesc = 1;
  206. if ( s+2 < end ) {
  207. int n = hexchar2int( s[1] );
  208. /* If 8th bit is on, the char is not ASCII (not UTF-8).
  209. * Thus, not UTF-8 */
  210. if ( n >= 0 && n < 8 ) {
  211. int n2 = hexchar2int( s[2] );
  212. if ( n2 >= 0 ) {
  213. n = (n << 4) + n2;
  214. if (n == 0) { /* don't change \00 */
  215. *d++ = *s++;
  216. *d++ = *s++;
  217. *d++ = *s;
  218. } else { /* change \xx to a single char */
  219. *d++ = (char)n;
  220. s += 2;
  221. }
  222. gotesc = 0;
  223. }
  224. }
  225. }
  226. if (gotesc) {
  227. *d++ = *s;
  228. }
  229. }
  230. break;
  231. default:
  232. if (gotesc) {
  233. d--;
  234. }
  235. *d++ = *s;
  236. gotesc = 0;
  237. break;
  238. }
  239. }
  240. *d = '\0';
  241. }
  242. /* functions to convert between an entry and a set of mods */
  243. int slapi_mods2entry (Slapi_Entry **e, const char *idn, LDAPMod **iattrs)
  244. {
  245. int i, rc = LDAP_SUCCESS;
  246. LDAPMod **attrs= NULL;
  247. PR_ASSERT (idn);
  248. PR_ASSERT (iattrs);
  249. PR_ASSERT (e);
  250. attrs = normalize_mods2bvals((const LDAPMod **)iattrs);
  251. PR_ASSERT (attrs);
  252. /* Construct an entry */
  253. *e = slapi_entry_alloc();
  254. PR_ASSERT (*e);
  255. slapi_entry_init(*e, slapi_ch_strdup(idn), NULL);
  256. for (i = 0; rc==LDAP_SUCCESS && attrs[ i ]!=NULL; i++)
  257. {
  258. char *normtype;
  259. Slapi_Value **vals;
  260. normtype = slapi_attr_syntax_normalize(attrs[ i ]->mod_type);
  261. valuearray_init_bervalarray(attrs[ i ]->mod_bvalues, &vals);
  262. if (strcasecmp(normtype, SLAPI_USERPWD_ATTR) == 0)
  263. {
  264. pw_encodevals(vals);
  265. }
  266. /* set entry uniqueid - also adds attribute to the list */
  267. if (strcasecmp(normtype, SLAPI_ATTR_UNIQUEID) == 0)
  268. slapi_entry_set_uniqueid (*e, slapi_ch_strdup (slapi_value_get_string(vals[0])));
  269. else
  270. rc = slapi_entry_add_values_sv(*e, normtype, vals);
  271. valuearray_free(&vals);
  272. if (rc != LDAP_SUCCESS)
  273. {
  274. LDAPDebug(LDAP_DEBUG_ANY, "slapi_add_internal: add_values for type %s failed\n", normtype, 0, 0 );
  275. slapi_entry_free (*e);
  276. *e = NULL;
  277. }
  278. slapi_ch_free((void **) &normtype);
  279. }
  280. freepmods(attrs);
  281. return rc;
  282. }
  283. int slapi_entry2mods (const Slapi_Entry *e, char **dn, LDAPMod ***attrs)
  284. {
  285. Slapi_Mods smods;
  286. Slapi_Attr *attr;
  287. Slapi_Value **va;
  288. char *type;
  289. int rc;
  290. PR_ASSERT (e && attrs);
  291. if (dn)
  292. *dn = slapi_ch_strdup (slapi_entry_get_dn ((Slapi_Entry *)e));
  293. slapi_mods_init (&smods, 0);
  294. rc = slapi_entry_first_attr(e, &attr);
  295. while (rc == 0)
  296. {
  297. if ( NULL != ( va = attr_get_present_values( attr ))) {
  298. slapi_attr_get_type(attr, &type);
  299. slapi_mods_add_mod_values(&smods, LDAP_MOD_ADD, type, va );
  300. }
  301. rc = slapi_entry_next_attr(e, attr, &attr);
  302. }
  303. *attrs = slapi_mods_get_ldapmods_passout (&smods);
  304. slapi_mods_done (&smods);
  305. return 0;
  306. }
  307. /******************************************************************************
  308. *
  309. * normalize_mods2bvals
  310. *
  311. *
  312. *
  313. *
  314. *******************************************************************************/
  315. LDAPMod **
  316. normalize_mods2bvals(const LDAPMod **mods)
  317. {
  318. int w, x, vlen, num_values, num_mods;
  319. LDAPMod **normalized_mods;
  320. if (mods == NULL)
  321. {
  322. return NULL;
  323. }
  324. /* first normalize the mods so they are bvalues */
  325. /* count the number of mods -- sucks but should be small */
  326. num_mods = 1;
  327. for (w=0; mods[w] != NULL; w++) num_mods++;
  328. normalized_mods = (LDAPMod **) slapi_ch_calloc(num_mods, sizeof(LDAPMod *));
  329. for (w = 0; mods[w] != NULL; w++)
  330. {
  331. /* copy each mod into a normalized modbvalue */
  332. normalized_mods[w] = (LDAPMod *) slapi_ch_calloc(1, sizeof(LDAPMod));
  333. normalized_mods[w]->mod_op = mods[w]->mod_op | LDAP_MOD_BVALUES;
  334. normalized_mods[w]->mod_type = slapi_ch_strdup(mods[w]->mod_type);
  335. /*
  336. * count the number of values -- kinda sucks but probably
  337. * less expensive then reallocing, and num_values
  338. * should typically be very small
  339. */
  340. num_values = 0;
  341. if (mods[w]->mod_op & LDAP_MOD_BVALUES)
  342. {
  343. for (x = 0; mods[w]->mod_bvalues != NULL &&
  344. mods[w]->mod_bvalues[x] != NULL; x++)
  345. {
  346. num_values++;
  347. }
  348. } else {
  349. for (x = 0; mods[w]->mod_values[x] != NULL &&
  350. mods[w]->mod_values[x] != NULL; x++)
  351. {
  352. num_values++;
  353. }
  354. }
  355. if (num_values > 0)
  356. {
  357. normalized_mods[w]->mod_bvalues = (struct berval **)
  358. slapi_ch_calloc(num_values + 1, sizeof(struct berval *));
  359. } else {
  360. normalized_mods[w]->mod_bvalues = NULL;
  361. }
  362. if (mods[w]->mod_op & LDAP_MOD_BVALUES)
  363. {
  364. for (x = 0; mods[w]->mod_bvalues != NULL &&
  365. mods[w]->mod_bvalues[x] != NULL; x++)
  366. {
  367. normalized_mods[w]->mod_bvalues[x] = ber_bvdup(mods[w]->mod_bvalues[x]);
  368. }
  369. } else {
  370. for (x = 0; mods[w]->mod_values != NULL &&
  371. mods[w]->mod_values[x] != NULL; x++)
  372. {
  373. normalized_mods[w]->mod_bvalues[ x ] = (struct berval *)
  374. slapi_ch_calloc(1, sizeof(struct berval));
  375. vlen = strlen(mods[w]->mod_values[x]);
  376. normalized_mods[w]->mod_bvalues[ x ]->bv_val =
  377. slapi_ch_calloc(vlen + 1, sizeof(char));
  378. memcpy(normalized_mods[w]->mod_bvalues[ x ]->bv_val,
  379. mods[w]->mod_values[x], vlen);
  380. normalized_mods[w]->mod_bvalues[ x ]->bv_val[vlen] = '\0';
  381. normalized_mods[w]->mod_bvalues[ x ]->bv_len = vlen;
  382. }
  383. }
  384. /* don't forget to null terminate it */
  385. if (num_values > 0)
  386. {
  387. normalized_mods[w]->mod_bvalues[ x ] = NULL;
  388. }
  389. }
  390. /* don't forget to null terminate the normalize list of mods */
  391. normalized_mods[w] = NULL;
  392. return(normalized_mods);
  393. }
  394. /*
  395. * Return true if the given path is an absolute path, false otherwise
  396. */
  397. int
  398. is_abspath(const char *path)
  399. {
  400. if (path == NULL || *path == '\0') {
  401. return 0; /* empty path is not absolute? */
  402. }
  403. #if defined( XP_WIN32 )
  404. if (path[0] == '/' || path[0] == '\\' ||
  405. (isalpha(path[0]) && (path[1] == ':'))) {
  406. return 1; /* Windows abs path */
  407. }
  408. #else
  409. if (path[0] == '/') {
  410. return 1; /* unix abs path */
  411. }
  412. #endif
  413. return 0; /* not an abs path */
  414. }
  415. static void
  416. clean_path(char **norm_path)
  417. {
  418. char **np;
  419. for (np = norm_path; np && *np; np++)
  420. slapi_ch_free_string(np);
  421. slapi_ch_free((void **)&norm_path);
  422. }
  423. static char **
  424. normalize_path(char *path)
  425. {
  426. char *dname = NULL;
  427. char *dnamep = NULL;
  428. char **dirs = (char **)slapi_ch_calloc(strlen(path), sizeof(char *));
  429. char **rdirs = (char **)slapi_ch_calloc(strlen(path), sizeof(char *));
  430. char **dp = dirs;
  431. char **rdp;
  432. int elimdots = 0;
  433. if (NULL == path || '\0' == *path) {
  434. return NULL;
  435. }
  436. dname = slapi_ch_strdup(path);
  437. do {
  438. dnamep = strrchr(dname, _CSEP);
  439. if (NULL == dnamep) {
  440. dnamep = dname;
  441. } else {
  442. *dnamep = '\0';
  443. dnamep++;
  444. }
  445. if (0 != strcmp(dnamep, ".") && strlen(dnamep) > 0) {
  446. *dp++ = slapi_ch_strdup(dnamep); /* rm "/./" and "//" in the path */
  447. }
  448. } while ( dnamep > dname /* == -> no more _CSEP */ );
  449. slapi_ch_free_string(&dname);
  450. /* remove "xxx/.." in the path */
  451. for (dp = dirs, rdp = rdirs; dp && *dp; dp++) {
  452. while (*dp && 0 == strcmp(*dp, "..")) {
  453. dp++;
  454. elimdots++;
  455. }
  456. if (elimdots > 0) {
  457. elimdots--;
  458. } else if (*dp) {
  459. *rdp++ = slapi_ch_strdup(*dp);
  460. }
  461. }
  462. /* reverse */
  463. for (--rdp, dp = rdirs; rdp >= dp && rdp >= rdirs; --rdp, dp++) {
  464. char *tmpp = *dp;
  465. *dp = *rdp;
  466. *rdp = tmpp;
  467. }
  468. clean_path(dirs);
  469. return rdirs;
  470. }
  471. /*
  472. * Take "relpath" and prepend the current working directory to it
  473. * if it isn't an absolute pathname already. The caller is responsible
  474. * for freeing the returned string.
  475. */
  476. char *
  477. rel2abspath( char *relpath )
  478. {
  479. return rel2abspath_ext( relpath, NULL );
  480. }
  481. char *
  482. rel2abspath_ext( char *relpath, char *cwd )
  483. {
  484. char abspath[ MAXPATHLEN + 1 ];
  485. char *retpath = NULL;
  486. #if defined( _WIN32 )
  487. CHAR szDrive[_MAX_DRIVE];
  488. CHAR szDir[_MAX_DIR];
  489. CHAR szFname[_MAX_FNAME];
  490. CHAR szExt[_MAX_EXT];
  491. #endif
  492. if ( relpath == NULL ) {
  493. return NULL;
  494. }
  495. #if defined( _WIN32 )
  496. memset (&szDrive, 0, sizeof (szDrive));
  497. memset (&szDir, 0, sizeof (szDir));
  498. memset (&szFname, 0, sizeof (szFname));
  499. memset (&szExt, 0, sizeof (szExt));
  500. _splitpath( relpath, szDrive, szDir, szFname, szExt );
  501. if( szDrive[0] && szDir[0] )
  502. return( slapi_ch_strdup( relpath ));
  503. #endif
  504. if ( relpath[ 0 ] == _CSEP ) { /* absolute path */
  505. PR_snprintf(abspath, sizeof(abspath), "%s", relpath);
  506. } else { /* relative path */
  507. if ( NULL == cwd ) {
  508. if ( getcwd( abspath, MAXPATHLEN ) == NULL ) {
  509. perror( "getcwd" );
  510. LDAPDebug( LDAP_DEBUG_ANY, "Cannot determine current directory\n",
  511. 0, 0, 0 );
  512. exit( 1 );
  513. }
  514. } else {
  515. PR_snprintf(abspath, sizeof(abspath), "%s", cwd);
  516. }
  517. if ( strlen( relpath ) + strlen( abspath ) + 1 > MAXPATHLEN ) {
  518. LDAPDebug( LDAP_DEBUG_ANY, "Pathname \"%s" _PSEP "%s\" too long\n",
  519. abspath, relpath, 0 );
  520. exit( 1 );
  521. }
  522. if ( strcmp( relpath, "." )) {
  523. if ( abspath[ 0 ] != '\0' &&
  524. abspath[ strlen( abspath ) - 1 ] != _CSEP )
  525. {
  526. PL_strcatn( abspath, sizeof(abspath), _PSEP );
  527. }
  528. PL_strcatn( abspath, sizeof(abspath), relpath );
  529. }
  530. }
  531. retpath = slapi_ch_strdup(abspath);
  532. /* if there's no '.' or separators, no need to call normalize_path */
  533. if (NULL != strchr(abspath, '.') || NULL != strstr(abspath, _PSEP))
  534. {
  535. char **norm_path = normalize_path(abspath);
  536. char **np, *rp;
  537. int pathlen = strlen(abspath) + 1;
  538. int usedlen = 0;
  539. for (np = norm_path, rp = retpath; np && *np; np++) {
  540. int thislen = strlen(*np) + 1;
  541. if (0 != strcmp(*np, _PSEP))
  542. PR_snprintf(rp, pathlen - usedlen, "%c%s", _CSEP, *np);
  543. rp += thislen;
  544. usedlen += thislen;
  545. }
  546. clean_path(norm_path);
  547. }
  548. return retpath;
  549. }
  550. /*
  551. * Allocate a buffer large enough to hold a berval's
  552. * value and a terminating null byte. The returned buffer
  553. * is null-terminated. Returns NULL if bval is NULL or if
  554. * bval->bv_val is NULL.
  555. */
  556. char *
  557. slapi_berval_get_string_copy(const struct berval *bval)
  558. {
  559. char *return_value = NULL;
  560. if (NULL != bval && NULL != bval->bv_val)
  561. {
  562. return_value = slapi_ch_malloc(bval->bv_len + 1);
  563. memcpy(return_value, bval->bv_val, bval->bv_len);
  564. return_value[bval->bv_len] = '\0';
  565. }
  566. return return_value;
  567. }
  568. /* Takes a return code supposed to be errno or from a plugin
  569. which we don't expect to see and prints a handy log message */
  570. void slapd_nasty(char* str, int c, int err)
  571. {
  572. char *msg = NULL;
  573. char buffer[100];
  574. PR_snprintf(buffer,sizeof(buffer), "%s BAD %d",str,c);
  575. LDAPDebug(LDAP_DEBUG_ANY,"%s, err=%d %s\n",buffer,err,(msg = strerror( err )) ? msg : "");
  576. }
  577. /* ***************************************************
  578. Random function (very similar to rand_r())
  579. *************************************************** */
  580. int
  581. slapi_rand_r(unsigned int *randx)
  582. {
  583. if (*randx)
  584. {
  585. PK11_RandomUpdate(randx, sizeof(*randx));
  586. }
  587. PK11_GenerateRandom((unsigned char *)randx, (int)sizeof(*randx));
  588. return (int)(*randx & 0x7FFFFFFF);
  589. }
  590. /* ***************************************************
  591. Random function (very similar to rand_r() but takes and returns an array)
  592. Note: there is an identical function in plugins/pwdstorage/ssha_pwd.c.
  593. That module can't use a libslapd function because the module is included
  594. in libds_admin, which doesn't link to libslapd. Eventually, shared
  595. functions should be moved to a shared library.
  596. *************************************************** */
  597. void
  598. slapi_rand_array(void *randx, size_t len)
  599. {
  600. PK11_RandomUpdate(randx, len);
  601. PK11_GenerateRandom((unsigned char *)randx, (int)len);
  602. }
  603. /* ***************************************************
  604. Random function (very similar to rand()...)
  605. *************************************************** */
  606. int
  607. slapi_rand()
  608. {
  609. unsigned int randx = 0;
  610. return slapi_rand_r(&randx);
  611. }
  612. /************************************************************************
  613. Function: DS_Sleep(PRIntervalTime ticks)
  614. Purpose: To replace PR_Sleep()
  615. Author: Scott Hopson <[email protected]>
  616. Description:
  617. Causes the current thread to wait for ticks number of intervals.
  618. In UNIX this is accomplished by using select()
  619. which should be supported across all UNIX platforms.
  620. In WIN32 we simply use the Sleep() function which yields
  621. for the number of milliseconds specified.
  622. ************************************************************************/
  623. #if defined(_WIN32)
  624. #include "windows.h"
  625. void DS_Sleep(PRIntervalTime ticks)
  626. {
  627. DWORD mSecs = PR_IntervalToMilliseconds(ticks);
  628. Sleep(mSecs);
  629. }
  630. #else /*** UNIX ***/
  631. #include <sys/time.h>
  632. void DS_Sleep(PRIntervalTime ticks)
  633. {
  634. long mSecs = PR_IntervalToMilliseconds(ticks);
  635. struct timeval tm;
  636. tm.tv_sec = mSecs / 1000;
  637. tm.tv_usec = (mSecs % 1000) * 1000;
  638. select(0,NULL,NULL,NULL,&tm);
  639. }
  640. #endif
  641. /*****************************************************************************
  642. * strarray2str(): convert the array of strings in "a" into a single
  643. * space-separated string like:
  644. * str1 str2 str3
  645. * If buf is too small, the result will be truncated and end with "...".
  646. * If include_quotes is non-zero, double quote marks are included around
  647. * the string, e.g.,
  648. * "str2 str2 str3"
  649. *
  650. * Returns: 0 if completely successful and -1 if result is truncated.
  651. */
  652. int
  653. strarray2str( char **a, char *buf, size_t buflen, int include_quotes )
  654. {
  655. int rc = 0; /* optimistic */
  656. char *p = buf;
  657. size_t totlen = 0;
  658. if ( include_quotes ) {
  659. if ( buflen < 3 ) {
  660. return -1; /* not enough room for the quote marks! */
  661. }
  662. *p++ = '"';
  663. ++totlen;
  664. }
  665. if ( NULL != a ) {
  666. int ii;
  667. size_t len = 0;
  668. for ( ii = 0; a[ ii ] != NULL; ii++ ) {
  669. if ( ii > 0 ) {
  670. *p++ = ' ';
  671. totlen++;
  672. }
  673. len = strlen( a[ ii ]);
  674. if ( totlen + len > buflen - 5 ) {
  675. strcpy ( p, "..." );
  676. p += 3;
  677. totlen += 3;
  678. rc = -1;
  679. break; /* result truncated */
  680. } else {
  681. strcpy( p, a[ ii ]);
  682. p += len;
  683. totlen += len;
  684. }
  685. }
  686. }
  687. if ( include_quotes ) {
  688. *p++ = '"';
  689. ++totlen;
  690. }
  691. buf[ totlen ] = '\0';
  692. return( rc );
  693. }
  694. /*****************************************************************************/
  695. /* Changes the ownership of the given file/directory if not
  696. already the owner
  697. Returns 0 upon success or non-zero otherwise, usually -1 if
  698. some system error occurred
  699. */
  700. #ifndef _WIN32
  701. int
  702. slapd_chown_if_not_owner(const char *filename, uid_t uid, gid_t gid)
  703. {
  704. struct stat statbuf;
  705. int result = 1;
  706. if (!filename)
  707. return result;
  708. memset(&statbuf, '\0', sizeof(statbuf));
  709. if (!(result = stat(filename, &statbuf)))
  710. {
  711. if (((uid != -1) && (uid != statbuf.st_uid)) ||
  712. ((gid != -1) && (gid != statbuf.st_gid)))
  713. {
  714. result = chown(filename, uid, gid);
  715. }
  716. }
  717. return result;
  718. }
  719. #endif
  720. /*
  721. * Compare 2 pathes
  722. * Paths could contain ".", "..", "//" in the path, thus normalize them first.
  723. * One or two of the paths could be a relative path.
  724. */
  725. int
  726. slapd_comp_path(char *p0, char *p1)
  727. {
  728. int rval = 0;
  729. char *norm_p0 = rel2abspath(p0);
  730. char *norm_p1 = rel2abspath(p1);
  731. rval = strcmp(norm_p0, norm_p1);
  732. slapi_ch_free_string(&norm_p0);
  733. slapi_ch_free_string(&norm_p1);
  734. return rval;
  735. }
  736. #ifdef MEMPOOL_EXPERIMENTAL
  737. void _free_wrapper(void *ptr)
  738. {
  739. slapi_ch_free(&ptr);
  740. }
  741. #endif
  742. /*
  743. * Function: slapi_ldap_unbind()
  744. * Purpose: release an LDAP session obtained from a call to slapi_ldap_init().
  745. */
  746. void
  747. slapi_ldap_unbind( LDAP *ld )
  748. {
  749. if ( ld != NULL ) {
  750. ldap_unbind( ld );
  751. }
  752. }
  753. const char *
  754. slapi_urlparse_err2string( int err )
  755. {
  756. const char *s="internal error";
  757. switch( err ) {
  758. case 0:
  759. s = "no error";
  760. break;
  761. case LDAP_URL_ERR_NOTLDAP:
  762. s = "missing ldap:// or ldaps:// or ldapi://";
  763. break;
  764. case LDAP_URL_ERR_NODN:
  765. s = "missing suffix";
  766. break;
  767. case LDAP_URL_ERR_BADSCOPE:
  768. s = "invalid search scope";
  769. break;
  770. case LDAP_URL_ERR_MEM:
  771. s = "unable to allocate memory";
  772. break;
  773. case LDAP_URL_ERR_PARAM:
  774. s = "bad parameter to an LDAP URL function";
  775. break;
  776. }
  777. return( s );
  778. }
  779. /*
  780. Perform LDAP init and return an LDAP* handle. If ldapurl is given,
  781. that is used as the basis for the protocol, host, port, and whether
  782. to use starttls (given on the end as ldap://..../?????starttlsOID
  783. If hostname is given, LDAP or LDAPS is assumed, and this will override
  784. the hostname from the ldapurl, if any. If port is > 0, this is the
  785. port number to use. It will override the port in the ldapurl, if any.
  786. If no port is given in port or ldapurl, the default will be used based
  787. on the secure setting (389 for ldap, 636 for ldaps, 389 for starttls)
  788. secure takes 1 of 3 values - 0 means regular ldap, 1 means ldaps, 2
  789. means regular ldap with starttls.
  790. filename is the ldapi file name - if this is given, and no other options
  791. are given, ldapi is assumed.
  792. */
  793. LDAP *
  794. slapi_ldap_init_ext(
  795. const char *ldapurl, /* full ldap url */
  796. const char *hostname, /* can also use this to override
  797. host in url */
  798. int port, /* can also use this to override port in url */
  799. int secure, /* 0 for ldap, 1 for ldaps, 2 for starttls -
  800. override proto in url */
  801. int shared, /* if true, LDAP* will be shared among multiple threads */
  802. const char *filename /* for ldapi */
  803. )
  804. {
  805. LDAPURLDesc *ludp = NULL;
  806. LDAP *ld = NULL;
  807. int rc = 0;
  808. /* if ldapurl is given, parse it */
  809. if (ldapurl && ((rc = ldap_url_parse_no_defaults(ldapurl, &ludp, 0)) ||
  810. !ludp)) {
  811. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_init_ext",
  812. "Could not parse given LDAP URL [%s] : error [%s]\n",
  813. ldapurl ? ldapurl : "NULL",
  814. slapi_urlparse_err2string(rc));
  815. goto done;
  816. }
  817. /* use url host if no host given */
  818. if (!hostname && ludp && ludp->lud_host) {
  819. hostname = ludp->lud_host;
  820. }
  821. /* use url port if no port given */
  822. if (!port && ludp && ludp->lud_port) {
  823. port = ludp->lud_port;
  824. }
  825. /* use secure setting from url if none given */
  826. if (!secure && ludp) {
  827. if (ludp->lud_options & LDAP_URL_OPT_SECURE) {
  828. secure = 1;
  829. } else if (0/* starttls option - not supported yet in LDAP URLs */) {
  830. secure = 2;
  831. }
  832. }
  833. /* ldap_url_parse doesn't yet handle ldapi */
  834. /*
  835. if (!filename && ludp && ludp->lud_file) {
  836. filename = ludp->lud_file;
  837. }
  838. */
  839. #ifdef MEMPOOL_EXPERIMENTAL
  840. {
  841. /*
  842. * slapi_ch_malloc functions need to be set to LDAP C SDK
  843. */
  844. struct ldap_memalloc_fns memalloc_fns;
  845. memalloc_fns.ldapmem_malloc = (LDAP_MALLOC_CALLBACK *)slapi_ch_malloc;
  846. memalloc_fns.ldapmem_calloc = (LDAP_CALLOC_CALLBACK *)slapi_ch_calloc;
  847. memalloc_fns.ldapmem_realloc = (LDAP_REALLOC_CALLBACK *)slapi_ch_realloc;
  848. memalloc_fns.ldapmem_free = (LDAP_FREE_CALLBACK *)_free_wrapper;
  849. }
  850. /*
  851. * MEMPOOL_EXPERIMENTAL:
  852. * These LDAP C SDK init function needs to be revisited.
  853. * In ldap_init called via ldapssl_init and prldap_init initializes
  854. * options and set default values including memalloc_fns, then it
  855. * initializes as sasl client by calling sasl_client_init. In
  856. * sasl_client_init, it creates mechlist using the malloc function
  857. * available at the moment which could mismatch the malloc/free functions
  858. * set later.
  859. */
  860. #endif
  861. if (filename) {
  862. /* ldapi in mozldap client is not yet supported */
  863. } else if (secure == 1) {
  864. ld = ldapssl_init(hostname, port, secure);
  865. } else { /* regular ldap and/or starttls */
  866. /*
  867. * Leverage the libprldap layer to take care of all the NSPR
  868. * integration.
  869. * Note that ldapssl_init() uses libprldap implicitly.
  870. */
  871. ld = prldap_init(hostname, port, shared);
  872. }
  873. /* Update snmp interaction table */
  874. if (hostname) {
  875. if (ld == NULL) {
  876. set_snmp_interaction_row((char *)hostname, port, -1);
  877. } else {
  878. set_snmp_interaction_row((char *)hostname, port, 0);
  879. }
  880. }
  881. if ((ld != NULL) && !filename) {
  882. /*
  883. * Set the outbound LDAP I/O timeout based on the server config.
  884. */
  885. int io_timeout_ms = config_get_outbound_ldap_io_timeout();
  886. if (io_timeout_ms > 0) {
  887. if (prldap_set_session_option(ld, NULL, PRLDAP_OPT_IO_MAX_TIMEOUT,
  888. io_timeout_ms) != LDAP_SUCCESS) {
  889. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_init_ext",
  890. "failed: unable to set outbound I/O "
  891. "timeout to %dms\n",
  892. io_timeout_ms);
  893. slapi_ldap_unbind(ld);
  894. ld = NULL;
  895. goto done;
  896. }
  897. }
  898. /*
  899. * Set SSL strength (server certificate validity checking).
  900. */
  901. if (secure > 0) {
  902. int ssl_strength = 0;
  903. LDAP *myld = NULL;
  904. if (config_get_ssl_check_hostname()) {
  905. /* check hostname against name in certificate */
  906. ssl_strength = LDAPSSL_AUTH_CNCHECK;
  907. } else {
  908. /* verify certificate only */
  909. ssl_strength = LDAPSSL_AUTH_CERT;
  910. }
  911. /* we can only use the set functions below with a real
  912. LDAP* if it has already gone through ldapssl_init -
  913. so, use NULL if using starttls */
  914. if (secure == 1) {
  915. myld = ld;
  916. }
  917. if ((rc = ldapssl_set_strength(myld, ssl_strength)) ||
  918. (rc = ldapssl_set_option(myld, SSL_ENABLE_SSL2, PR_FALSE)) ||
  919. (rc = ldapssl_set_option(myld, SSL_ENABLE_SSL3, PR_TRUE)) ||
  920. (rc = ldapssl_set_option(myld, SSL_ENABLE_TLS, PR_TRUE))) {
  921. int prerr = PR_GetError();
  922. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_init_ext",
  923. "failed: unable to set SSL options ("
  924. SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  925. prerr, slapd_pr_strerror(prerr));
  926. }
  927. if (secure == 1) {
  928. /* tell bind code we are using SSL */
  929. ldap_set_option(ld, LDAP_OPT_SSL, LDAP_OPT_ON);
  930. }
  931. }
  932. }
  933. if (ld && (secure == 2)) {
  934. /* We don't have a way to stash context data with the LDAP*, so we
  935. stash the information in the client controls (currently unused).
  936. We don't want to open the connection in ldap_init, since that's
  937. not the semantic - the connection is not usually opened until
  938. the first operation is sent, which is usually the bind - or
  939. in this case, the start_tls - so we stash the start_tls so
  940. we can do it in slapi_ldap_bind - note that this will get
  941. cleaned up when the LDAP* is disposed of
  942. */
  943. LDAPControl start_tls_dummy_ctrl;
  944. LDAPControl **clientctrls = NULL;
  945. /* returns copy of controls */
  946. ldap_get_option(ld, LDAP_OPT_CLIENT_CONTROLS, &clientctrls);
  947. start_tls_dummy_ctrl.ldctl_oid = slapi_ch_strdup(START_TLS_OID);
  948. start_tls_dummy_ctrl.ldctl_value.bv_val = NULL;
  949. start_tls_dummy_ctrl.ldctl_value.bv_len = 0;
  950. start_tls_dummy_ctrl.ldctl_iscritical = 0;
  951. slapi_add_control_ext(&clientctrls, &start_tls_dummy_ctrl, 1);
  952. /* set option frees old list and copies the new list */
  953. ldap_set_option(ld, LDAP_OPT_CLIENT_CONTROLS, clientctrls);
  954. ldap_controls_free(clientctrls); /* free the copy */
  955. }
  956. slapi_log_error(SLAPI_LOG_SHELL, "slapi_ldap_init_ext",
  957. "Success: set up conn to [%s:%d]%s\n",
  958. hostname, port,
  959. (secure == 2) ? " using startTLS" :
  960. ((secure == 1) ? " using SSL" : ""));
  961. done:
  962. ldap_free_urldesc(ludp);
  963. return( ld );
  964. }
  965. /*
  966. * Function: slapi_ldap_init()
  967. * Description: just like ldap_ssl_init() but also arranges for the LDAP
  968. * session handle returned to be safely shareable by multiple threads
  969. * if "shared" is non-zero.
  970. * Returns:
  971. * an LDAP session handle (NULL if some local error occurs).
  972. */
  973. LDAP *
  974. slapi_ldap_init( char *ldaphost, int ldapport, int secure, int shared )
  975. {
  976. return slapi_ldap_init_ext(NULL, ldaphost, ldapport, secure, shared, NULL);
  977. }
  978. /*
  979. * Does the correct bind operation simple/sasl/cert depending
  980. * on the arguments passed in. If the user specified to use
  981. * starttls in init, this will do the starttls first. If using
  982. * ssl or client cert auth, this will initialize the client side
  983. * of that.
  984. */
  985. int
  986. slapi_ldap_bind(
  987. LDAP *ld, /* ldap connection */
  988. const char *bindid, /* usually a bind DN for simple bind */
  989. const char *creds, /* usually a password for simple bind */
  990. const char *mech, /* name of mechanism */
  991. LDAPControl **serverctrls, /* additional controls to send */
  992. LDAPControl ***returnedctrls, /* returned controls */
  993. struct timeval *timeout, /* timeout */
  994. int *msgidp /* pass in non-NULL for async handling */
  995. )
  996. {
  997. int rc = LDAP_SUCCESS;
  998. LDAPControl **clientctrls = NULL;
  999. int secure = 0;
  1000. struct berval bvcreds = {0, NULL};
  1001. LDAPMessage *result = NULL;
  1002. struct berval *servercredp = NULL;
  1003. /* do starttls if requested
  1004. NOTE - starttls is an extop, not a control, but we don't have
  1005. a place we can stash this information in the LDAP*, other
  1006. than the currently unused clientctrls */
  1007. ldap_get_option(ld, LDAP_OPT_CLIENT_CONTROLS, &clientctrls);
  1008. if (clientctrls && clientctrls[0] &&
  1009. slapi_control_present(clientctrls, START_TLS_OID, NULL, NULL)) {
  1010. secure = 2;
  1011. } else {
  1012. ldap_get_option(ld, LDAP_OPT_SSL, &secure);
  1013. }
  1014. if ((secure > 0) && mech && !strcmp(mech, LDAP_SASL_EXTERNAL)) {
  1015. /* SSL connections will use the server's security context
  1016. and cert for client auth */
  1017. rc = slapd_SSL_client_auth(ld);
  1018. if (rc != 0) {
  1019. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  1020. "Error: could not configure the server for cert "
  1021. "auth - error %d - make sure the server is "
  1022. "correctly configured for SSL/TLS\n", rc);
  1023. goto done;
  1024. } else {
  1025. slapi_log_error(SLAPI_LOG_SHELL, "slapi_ldap_bind",
  1026. "Set up conn to use client auth\n");
  1027. }
  1028. bvcreds.bv_val = NULL; /* ignore username and passed in creds */
  1029. bvcreds.bv_len = 0; /* for external auth */
  1030. bindid = NULL;
  1031. } else { /* other type of auth */
  1032. bvcreds.bv_val = (char *)creds;
  1033. bvcreds.bv_len = creds ? strlen(creds) : 0;
  1034. }
  1035. if (secure == 2) { /* send start tls */
  1036. rc = ldap_start_tls_s(ld, NULL /* serverctrls?? */, NULL);
  1037. if (LDAP_SUCCESS != rc) {
  1038. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  1039. "Error: could not send startTLS request: "
  1040. "error %d (%s)\n",
  1041. rc, ldap_err2string(rc));
  1042. goto done;
  1043. }
  1044. slapi_log_error(SLAPI_LOG_SHELL, "slapi_ldap_bind",
  1045. "startTLS started on connection\n");
  1046. }
  1047. /* The connection has been set up - now do the actual bind, depending on
  1048. the mechanism and arguments */
  1049. if (!mech || (mech == LDAP_SASL_SIMPLE) ||
  1050. !strcmp(mech, LDAP_SASL_EXTERNAL)) {
  1051. int mymsgid = 0;
  1052. slapi_log_error(SLAPI_LOG_SHELL, "slapi_ldap_bind",
  1053. "attempting %s bind with id [%s] creds [%s]\n",
  1054. mech ? mech : "SIMPLE",
  1055. bindid, creds);
  1056. if ((rc = ldap_sasl_bind(ld, bindid, mech, &bvcreds, serverctrls,
  1057. NULL /* clientctrls */, &mymsgid))) {
  1058. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  1059. "Error: could not send bind request for id "
  1060. "[%s] mech [%s]: error %d (%s) %d (%s) %d (%s)\n",
  1061. bindid ? bindid : "(anon)",
  1062. mech ? mech : "SIMPLE",
  1063. rc, ldap_err2string(rc),
  1064. PR_GetError(), slapd_pr_strerror(PR_GetError()),
  1065. errno, slapd_system_strerror(errno));
  1066. goto done;
  1067. }
  1068. if (msgidp) { /* let caller process result */
  1069. *msgidp = mymsgid;
  1070. } else { /* process results */
  1071. rc = ldap_result(ld, mymsgid, LDAP_MSG_ALL, timeout, &result);
  1072. if (-1 == rc) { /* error */
  1073. rc = ldap_get_lderrno(ld, NULL, NULL);
  1074. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  1075. "Error reading bind response for id "
  1076. "[%s] mech [%s]: error %d (%s)\n",
  1077. bindid ? bindid : "(anon)",
  1078. mech ? mech : "SIMPLE",
  1079. rc, ldap_err2string(rc));
  1080. goto done;
  1081. } else if (rc == 0) { /* timeout */
  1082. rc = LDAP_TIMEOUT;
  1083. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  1084. "Error: timeout after [%ld.%ld] seconds reading "
  1085. "bind response for [%s] mech [%s]\n",
  1086. timeout ? timeout->tv_sec : 0,
  1087. timeout ? timeout->tv_usec : 0,
  1088. bindid ? bindid : "(anon)",
  1089. mech ? mech : "SIMPLE");
  1090. goto done;
  1091. }
  1092. /* if we got here, we were able to read success result */
  1093. /* Get the controls sent by the server if requested */
  1094. if (returnedctrls) {
  1095. if ((rc = ldap_parse_result(ld, result, &rc, NULL, NULL,
  1096. NULL, returnedctrls,
  1097. 0)) != LDAP_SUCCESS) {
  1098. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  1099. "Error: could not bind id "
  1100. "[%s] mech [%s]: error %d (%s)\n",
  1101. bindid ? bindid : "(anon)",
  1102. mech ? mech : "SIMPLE",
  1103. rc, ldap_err2string(rc));
  1104. goto done;
  1105. }
  1106. }
  1107. /* parse the bind result and get the ldap error code */
  1108. if ((rc = ldap_parse_sasl_bind_result(ld, result, &servercredp,
  1109. 0)) ||
  1110. (rc = ldap_result2error(ld, result, 0))) {
  1111. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  1112. "Error: could not read bind results for id "
  1113. "[%s] mech [%s]: error %d (%s)\n",
  1114. bindid ? bindid : "(anon)",
  1115. mech ? mech : "SIMPLE",
  1116. rc, ldap_err2string(rc));
  1117. goto done;
  1118. }
  1119. }
  1120. } else {
  1121. /* a SASL mech - set the sasl ssf to 0 if using TLS/SSL */
  1122. if (secure) {
  1123. ldap_set_option(ld, LDAP_OPT_X_SASL_SECPROPS, "maxssf=0");
  1124. }
  1125. rc = slapd_ldap_sasl_interactive_bind(ld, bindid, creds, mech,
  1126. serverctrls, returnedctrls,
  1127. msgidp);
  1128. if (LDAP_SUCCESS != rc) {
  1129. slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind",
  1130. "Error: could not perform interactive bind for id "
  1131. "[%s] mech [%s]: error %d (%s)\n",
  1132. bindid ? bindid : "(anon)",
  1133. mech ? mech : "SIMPLE",
  1134. rc, ldap_err2string(rc));
  1135. }
  1136. }
  1137. done:
  1138. slapi_ch_bvfree(&servercredp);
  1139. ldap_msgfree(result);
  1140. return rc;
  1141. }
  1142. /* the following implements the client side of sasl bind, for LDAP server
  1143. -> LDAP server SASL */
  1144. #include <sasl.h>
  1145. typedef struct {
  1146. char *mech;
  1147. char *authid;
  1148. char *username;
  1149. char *passwd;
  1150. char *realm;
  1151. } ldapSaslInteractVals;
  1152. #ifdef HAVE_KRB5
  1153. static void set_krb5_creds(
  1154. const char *authid,
  1155. const char *username,
  1156. const char *passwd,
  1157. const char *realm,
  1158. ldapSaslInteractVals *vals
  1159. );
  1160. #endif
  1161. static void *
  1162. ldap_sasl_set_interact_vals(LDAP *ld, const char *mech, const char *authid,
  1163. const char *username, const char *passwd,
  1164. const char *realm)
  1165. {
  1166. ldapSaslInteractVals *vals = NULL;
  1167. char *idprefix = "";
  1168. vals = (ldapSaslInteractVals *)
  1169. slapi_ch_calloc(1, sizeof(ldapSaslInteractVals));
  1170. if (!vals) {
  1171. return NULL;
  1172. }
  1173. if (mech) {
  1174. vals->mech = slapi_ch_strdup(mech);
  1175. } else {
  1176. ldap_get_option(ld, LDAP_OPT_X_SASL_MECH, &vals->mech);
  1177. }
  1178. if (vals->mech && !strcasecmp(vals->mech, "DIGEST-MD5")) {
  1179. idprefix = "dn:"; /* prefix name and id with this string */
  1180. }
  1181. if (authid) { /* use explicit passed in value */
  1182. vals->authid = slapi_ch_smprintf("%s%s", idprefix, authid);
  1183. } else { /* use option value if any */
  1184. ldap_get_option(ld, LDAP_OPT_X_SASL_AUTHCID, &vals->authid);
  1185. if (!vals->authid) {
  1186. /* get server user id? */
  1187. vals->authid = slapi_ch_strdup("");
  1188. }
  1189. }
  1190. if (username) { /* use explicit passed in value */
  1191. vals->username = slapi_ch_smprintf("%s%s", idprefix, username);
  1192. } else { /* use option value if any */
  1193. ldap_get_option(ld, LDAP_OPT_X_SASL_AUTHZID, &vals->username);
  1194. if (!vals->username) { /* use default sasl value */
  1195. vals->username = slapi_ch_strdup("");
  1196. }
  1197. }
  1198. if (passwd) {
  1199. vals->passwd = slapi_ch_strdup(passwd);
  1200. } else {
  1201. vals->passwd = slapi_ch_strdup("");
  1202. }
  1203. if (realm) {
  1204. vals->realm = slapi_ch_strdup(realm);
  1205. } else {
  1206. ldap_get_option(ld, LDAP_OPT_X_SASL_REALM, &vals->realm);
  1207. if (!vals->realm) { /* use default sasl value */
  1208. vals->realm = slapi_ch_strdup("");
  1209. }
  1210. }
  1211. #ifdef HAVE_KRB5
  1212. if (mech && !strcmp(mech, "GSSAPI")) {
  1213. set_krb5_creds(authid, username, passwd, realm, vals);
  1214. }
  1215. #endif /* HAVE_KRB5 */
  1216. return vals;
  1217. }
  1218. static void
  1219. ldap_sasl_free_interact_vals(void *defaults)
  1220. {
  1221. ldapSaslInteractVals *vals = defaults;
  1222. if (vals) {
  1223. slapi_ch_free_string(&vals->mech);
  1224. slapi_ch_free_string(&vals->authid);
  1225. slapi_ch_free_string(&vals->username);
  1226. slapi_ch_free_string(&vals->passwd);
  1227. slapi_ch_free_string(&vals->realm);
  1228. slapi_ch_free(&defaults);
  1229. }
  1230. }
  1231. static int
  1232. ldap_sasl_get_val(ldapSaslInteractVals *vals, sasl_interact_t *interact, unsigned flags)
  1233. {
  1234. const char *defvalue = interact->defresult;
  1235. int authtracelevel = SLAPI_LOG_SHELL; /* special auth tracing */
  1236. if (vals != NULL) {
  1237. switch(interact->id) {
  1238. case SASL_CB_AUTHNAME:
  1239. defvalue = vals->authid;
  1240. slapi_log_error(authtracelevel, "ldap_sasl_get_val",
  1241. "Using value [%s] for SASL_CB_AUTHNAME\n",
  1242. defvalue ? defvalue : "(null)");
  1243. break;
  1244. case SASL_CB_USER:
  1245. defvalue = vals->username;
  1246. slapi_log_error(authtracelevel, "ldap_sasl_get_val",
  1247. "Using value [%s] for SASL_CB_USER\n",
  1248. defvalue ? defvalue : "(null)");
  1249. break;
  1250. case SASL_CB_PASS:
  1251. defvalue = vals->passwd;
  1252. slapi_log_error(authtracelevel, "ldap_sasl_get_val",
  1253. "Using value [%s] for SASL_CB_PASS\n",
  1254. defvalue ? defvalue : "(null)");
  1255. break;
  1256. case SASL_CB_GETREALM:
  1257. defvalue = vals->realm;
  1258. slapi_log_error(authtracelevel, "ldap_sasl_get_val",
  1259. "Using value [%s] for SASL_CB_GETREALM\n",
  1260. defvalue ? defvalue : "(null)");
  1261. break;
  1262. }
  1263. }
  1264. if (defvalue != NULL) {
  1265. interact->result = defvalue;
  1266. if ((char *)interact->result == NULL)
  1267. return (LDAP_NO_MEMORY);
  1268. interact->len = strlen((char *)(interact->result));
  1269. }
  1270. return (LDAP_SUCCESS);
  1271. }
  1272. static int
  1273. ldap_sasl_interact_cb(LDAP *ld, unsigned flags, void *defaults, void *prompts)
  1274. {
  1275. sasl_interact_t *interact = NULL;
  1276. ldapSaslInteractVals *sasldefaults = defaults;
  1277. int rc;
  1278. if (prompts == NULL) {
  1279. return (LDAP_PARAM_ERROR);
  1280. }
  1281. for (interact = prompts; interact->id != SASL_CB_LIST_END; interact++) {
  1282. /* Obtain the default value */
  1283. if ((rc = ldap_sasl_get_val(sasldefaults, interact, flags)) != LDAP_SUCCESS) {
  1284. return (rc);
  1285. }
  1286. }
  1287. return (LDAP_SUCCESS);
  1288. }
  1289. /* figure out from the context and this error if we should
  1290. attempt to retry the bind */
  1291. static int
  1292. can_retry_bind(LDAP *ld, const char *mech, const char *bindid,
  1293. const char *creds, int rc, const char *errmsg)
  1294. {
  1295. int localrc = 0;
  1296. if (errmsg && strstr(errmsg, "Ticket expired")) {
  1297. localrc = 1;
  1298. }
  1299. return localrc;
  1300. }
  1301. int
  1302. slapd_ldap_sasl_interactive_bind(
  1303. LDAP *ld, /* ldap connection */
  1304. const char *bindid, /* usually a bind DN for simple bind */
  1305. const char *creds, /* usually a password for simple bind */
  1306. const char *mech, /* name of mechanism */
  1307. LDAPControl **serverctrls, /* additional controls to send */
  1308. LDAPControl ***returnedctrls, /* returned controls */
  1309. int *msgidp /* pass in non-NULL for async handling */
  1310. )
  1311. {
  1312. int rc = LDAP_SUCCESS;
  1313. int tries = 0;
  1314. while (tries < 2) {
  1315. void *defaults = ldap_sasl_set_interact_vals(ld, mech, bindid, bindid,
  1316. creds, NULL);
  1317. /* have to first set the defaults used by the callback function */
  1318. /* call the bind function */
  1319. rc = ldap_sasl_interactive_bind_ext_s(ld, bindid, mech, serverctrls,
  1320. NULL, LDAP_SASL_QUIET,
  1321. ldap_sasl_interact_cb, defaults,
  1322. returnedctrls);
  1323. ldap_sasl_free_interact_vals(defaults);
  1324. if (LDAP_SUCCESS != rc) {
  1325. char *errmsg = NULL;
  1326. rc = ldap_get_lderrno(ld, NULL, &errmsg);
  1327. slapi_log_error(SLAPI_LOG_FATAL, "slapd_ldap_sasl_interactive_bind",
  1328. "Error: could not perform interactive bind for id "
  1329. "[%s] mech [%s]: error %d (%s) (%s)\n",
  1330. bindid ? bindid : "(anon)",
  1331. mech ? mech : "SIMPLE",
  1332. rc, ldap_err2string(rc), errmsg);
  1333. if (can_retry_bind(ld, mech, bindid, creds, rc, errmsg)) {
  1334. ; /* pass through to retry one time */
  1335. } else {
  1336. break; /* done - fail - cannot retry */
  1337. }
  1338. } else {
  1339. break; /* done - success */
  1340. }
  1341. tries++;
  1342. }
  1343. return rc;
  1344. }
  1345. #ifdef HAVE_KRB5
  1346. #include <krb5.h>
  1347. /* for some reason this is not in the public API?
  1348. but it is documented e.g. man kinit */
  1349. #ifndef KRB5_ENV_CCNAME
  1350. #define KRB5_ENV_CCNAME "KRB5CCNAME"
  1351. #endif
  1352. static void
  1353. show_one_credential(int authtracelevel,
  1354. krb5_context ctx, krb5_creds *cred)
  1355. {
  1356. char *logname = "show_one_credential";
  1357. krb5_error_code rc;
  1358. char *name = NULL, *sname = NULL;
  1359. char startts[BUFSIZ], endts[BUFSIZ], renewts[BUFSIZ];
  1360. if ((rc = krb5_unparse_name(ctx, cred->client, &name))) {
  1361. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1362. "Could not get client name from credential: %d (%s)\n",
  1363. rc, error_message(rc));
  1364. goto cleanup;
  1365. }
  1366. if ((rc = krb5_unparse_name(ctx, cred->server, &sname))) {
  1367. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1368. "Could not get server name from credential: %d (%s)\n",
  1369. rc, error_message(rc));
  1370. goto cleanup;
  1371. }
  1372. if (!cred->times.starttime) {
  1373. cred->times.starttime = cred->times.authtime;
  1374. }
  1375. krb5_timestamp_to_sfstring((krb5_timestamp)cred->times.starttime,
  1376. startts, sizeof(startts), NULL);
  1377. krb5_timestamp_to_sfstring((krb5_timestamp)cred->times.endtime,
  1378. endts, sizeof(endts), NULL);
  1379. krb5_timestamp_to_sfstring((krb5_timestamp)cred->times.renew_till,
  1380. renewts, sizeof(renewts), NULL);
  1381. slapi_log_error(authtracelevel, logname,
  1382. "\tKerberos credential: client [%s] server [%s] "
  1383. "start time [%s] end time [%s] renew time [%s] "
  1384. "flags [0x%x]\n", name, sname, startts, endts,
  1385. renewts, (uint32_t)cred->ticket_flags);
  1386. cleanup:
  1387. krb5_free_unparsed_name(ctx, name);
  1388. krb5_free_unparsed_name(ctx, sname);
  1389. return;
  1390. }
  1391. /*
  1392. * Call this after storing the credentials in the cache
  1393. */
  1394. static void
  1395. show_cached_credentials(int authtracelevel,
  1396. krb5_context ctx, krb5_ccache cc,
  1397. krb5_principal princ)
  1398. {
  1399. char *logname = "show_cached_credentials";
  1400. krb5_error_code rc = 0;
  1401. krb5_creds creds;
  1402. krb5_cc_cursor cur;
  1403. char *princ_name = NULL;
  1404. if ((rc = krb5_unparse_name(ctx, princ, &princ_name))) {
  1405. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1406. "Could not get principal name from principal: %d (%s)\n",
  1407. rc, error_message(rc));
  1408. goto cleanup;
  1409. }
  1410. slapi_log_error(authtracelevel, logname,
  1411. "Ticket cache: %s:%s\nDefault principal: %s\n\n",
  1412. krb5_cc_get_type(ctx, cc),
  1413. krb5_cc_get_name(ctx, cc), princ_name);
  1414. if ((rc = krb5_cc_start_seq_get(ctx, cc, &cur))) {
  1415. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1416. "Could not get cursor to iterate cached credentials: "
  1417. "%d (%s)\n", rc, error_message(rc));
  1418. goto cleanup;
  1419. }
  1420. while (!(rc = krb5_cc_next_cred(ctx, cc, &cur, &creds))) {
  1421. show_one_credential(authtracelevel, ctx, &creds);
  1422. krb5_free_cred_contents(ctx, &creds);
  1423. }
  1424. if (rc == KRB5_CC_END) {
  1425. if ((rc = krb5_cc_end_seq_get(ctx, cc, &cur))) {
  1426. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1427. "Could not close cached credentials cursor: "
  1428. "%d (%s)\n", rc, error_message(rc));
  1429. goto cleanup;
  1430. }
  1431. }
  1432. cleanup:
  1433. krb5_free_unparsed_name(ctx, princ_name);
  1434. return;
  1435. }
  1436. static int
  1437. looks_like_a_dn(const char *username)
  1438. {
  1439. return (username && strchr(username, '='));
  1440. }
  1441. static int
  1442. credentials_are_valid(
  1443. krb5_context ctx,
  1444. krb5_ccache cc,
  1445. krb5_principal princ,
  1446. const char *princ_name,
  1447. int *rc
  1448. )
  1449. {
  1450. char *logname = "credentials_are_valid";
  1451. int myrc = 0;
  1452. krb5_creds mcreds; /* match these values */
  1453. krb5_creds creds; /* returned creds */
  1454. char *tgs_princ_name = NULL;
  1455. krb5_timestamp currenttime;
  1456. int authtracelevel = SLAPI_LOG_SHELL; /* special auth tracing */
  1457. int realm_len;
  1458. char *realm_str;
  1459. int time_buffer = 30; /* seconds - go ahead and renew if creds are
  1460. about to expire */
  1461. memset(&mcreds, 0, sizeof(mcreds));
  1462. memset(&creds, 0, sizeof(creds));
  1463. *rc = 0;
  1464. if (!cc) {
  1465. /* ok - no error */
  1466. goto cleanup;
  1467. }
  1468. /* have to construct the tgs server principal in
  1469. order to set mcreds.server required in order
  1470. to use krb5_cc_retrieve_creds() */
  1471. /* get default realm first */
  1472. realm_len = krb5_princ_realm(ctx, princ)->length;
  1473. realm_str = krb5_princ_realm(ctx, princ)->data;
  1474. tgs_princ_name = slapi_ch_smprintf("%s/%*s@%*s", KRB5_TGS_NAME,
  1475. realm_len, realm_str,
  1476. realm_len, realm_str);
  1477. if ((*rc = krb5_parse_name(ctx, tgs_princ_name, &mcreds.server))) {
  1478. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1479. "Could parse principal [%s]: %d (%s)\n",
  1480. tgs_princ_name, *rc, error_message(*rc));
  1481. goto cleanup;
  1482. }
  1483. mcreds.client = princ;
  1484. if ((*rc = krb5_cc_retrieve_cred(ctx, cc, 0, &mcreds, &creds))) {
  1485. if (*rc == KRB5_CC_NOTFOUND) {
  1486. /* ok - no creds for this princ in the cache */
  1487. *rc = 0;
  1488. }
  1489. goto cleanup;
  1490. }
  1491. /* have the creds - now look at the timestamp */
  1492. if ((*rc = krb5_timeofday(ctx, &currenttime))) {
  1493. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1494. "Could not get current time: %d (%s)\n",
  1495. *rc, error_message(*rc));
  1496. goto cleanup;
  1497. }
  1498. if (currenttime > (creds.times.endtime + time_buffer)) {
  1499. slapi_log_error(authtracelevel, logname,
  1500. "Credentials for [%s] have expired or will soon "
  1501. "expire - now [%d] endtime [%d]\n", princ_name,
  1502. currenttime, creds.times.endtime);
  1503. goto cleanup;
  1504. }
  1505. myrc = 1; /* credentials are valid */
  1506. cleanup:
  1507. krb5_free_cred_contents(ctx, &creds);
  1508. slapi_ch_free_string(&tgs_princ_name);
  1509. if (mcreds.server) {
  1510. krb5_free_principal(ctx, mcreds.server);
  1511. }
  1512. return myrc;
  1513. }
  1514. /*
  1515. * This implementation assumes that we want to use the
  1516. * keytab from the default keytab env. var KRB5_KTNAME
  1517. * as. This code is very similar to kinit -k -t. We
  1518. * get a krb context, get the default keytab, get
  1519. * the credentials from the keytab, authenticate with
  1520. * those credentials, create a ccache, store the
  1521. * credentials in the ccache, and set the ccache
  1522. * env var to point to those credentials.
  1523. */
  1524. static void
  1525. set_krb5_creds(
  1526. const char *authid,
  1527. const char *username,
  1528. const char *passwd,
  1529. const char *realm,
  1530. ldapSaslInteractVals *vals
  1531. )
  1532. {
  1533. char *logname = "set_krb5_creds";
  1534. const char *cc_type = "MEMORY"; /* keep cred cache in memory */
  1535. krb5_context ctx = NULL;
  1536. krb5_ccache cc = NULL;
  1537. krb5_principal princ = NULL;
  1538. char *princ_name = NULL;
  1539. krb5_error_code rc = 0;
  1540. krb5_creds creds;
  1541. krb5_keytab kt = NULL;
  1542. char *cc_name = NULL;
  1543. char ktname[MAX_KEYTAB_NAME_LEN];
  1544. static char cc_env_name[1024+32]; /* size from ccdefname.c */
  1545. int new_ccache = 0;
  1546. int authtracelevel = SLAPI_LOG_SHELL; /* special auth tracing
  1547. not sure what shell was
  1548. used for, does not
  1549. appear to be used
  1550. currently */
  1551. /* probably have to put a mutex around this whole thing, to avoid
  1552. problems with reentrancy, since we are setting a "global"
  1553. variable via an environment variable */
  1554. /* wipe this out so we can safely free it later if we
  1555. short circuit */
  1556. memset(&creds, 0, sizeof(creds));
  1557. /* initialize the kerberos context */
  1558. if ((rc = krb5_init_context(&ctx))) {
  1559. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1560. "Could not init Kerberos context: %d (%s)\n",
  1561. rc, error_message(rc));
  1562. goto cleanup;
  1563. }
  1564. /* see if there is already a ccache, and see if there are
  1565. creds in the ccache */
  1566. /* grab the default ccache - note: this does not open the cache */
  1567. if ((rc = krb5_cc_default(ctx, &cc))) {
  1568. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1569. "Could not get default Kerberos ccache: %d (%s)\n",
  1570. rc, error_message(rc));
  1571. goto cleanup;
  1572. }
  1573. /* use this cache - construct the full cache name */
  1574. cc_name = slapi_ch_smprintf("%s:%s", krb5_cc_get_type(ctx, cc),
  1575. krb5_cc_get_name(ctx, cc));
  1576. /* grab the principal from the ccache - will fail if there
  1577. is no ccache */
  1578. if ((rc = krb5_cc_get_principal(ctx, cc, &princ))) {
  1579. if (KRB5_FCC_NOFILE == rc) { /* no cache - ok */
  1580. slapi_log_error(authtracelevel, logname,
  1581. "The default credentials cache [%s] not found: "
  1582. "will create a new one.\n", cc_name);
  1583. /* close the cache - we will create a new one below */
  1584. krb5_cc_close(ctx, cc);
  1585. cc = NULL;
  1586. slapi_ch_free_string(&cc_name);
  1587. /* fall through to the keytab auth code below */
  1588. } else { /* fatal */
  1589. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1590. "Could not open default Kerberos ccache [%s]: "
  1591. "%d (%s)\n", cc_name, rc, error_message(rc));
  1592. goto cleanup;
  1593. }
  1594. } else { /* have a valid ccache && found principal */
  1595. if ((rc = krb5_unparse_name(ctx, princ, &princ_name))) {
  1596. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1597. "Unable to get name of principal from ccache [%s]: "
  1598. "%d (%s)\n", cc_name, rc, error_message(rc));
  1599. goto cleanup;
  1600. }
  1601. slapi_log_error(authtracelevel, logname,
  1602. "Using principal [%s] from ccache [%s]\n",
  1603. princ_name, cc_name);
  1604. }
  1605. /* if this is not our type of ccache, there is nothing more we can
  1606. do - just punt and let sasl/gssapi take it's course - this
  1607. usually means there has been an external kinit e.g. in the
  1608. start up script, and it is the responsibility of the script to
  1609. renew those credentials or face lots of sasl/gssapi failures
  1610. This means, however, that the caller MUST MAKE SURE THERE IS NO
  1611. DEFAULT CCACHE FILE or the server will attempt to use it (and
  1612. likely fail) - THERE MUST BE NO DEFAULT CCACHE FILE IF YOU WANT
  1613. THE SERVER TO AUTHENTICATE WITH THE KEYTAB
  1614. NOTE: cc types are case sensitive and always upper case */
  1615. if (cc && strcmp(cc_type, krb5_cc_get_type(ctx, cc))) {
  1616. static int errmsgcounter = 0;
  1617. int loglevel = SLAPI_LOG_FATAL;
  1618. if (errmsgcounter) {
  1619. loglevel = authtracelevel;
  1620. }
  1621. /* make sure we log this message once, in case the user has
  1622. done something unintended, we want to make sure they know
  1623. about it. However, if the user knows what he/she is doing,
  1624. by using an external ccache file, they probably don't want
  1625. to be notified with an error every time. */
  1626. slapi_log_error(loglevel, logname,
  1627. "The server will use the external SASL/GSSAPI "
  1628. "credentials cache [%s:%s]. If you want the "
  1629. "server to automatically authenticate with its "
  1630. "keytab, you must remove this cache. If you "
  1631. "did not intend to use this cache, you will likely "
  1632. "see many SASL/GSSAPI authentication failures.\n",
  1633. krb5_cc_get_type(ctx, cc), krb5_cc_get_name(ctx, cc));
  1634. errmsgcounter++;
  1635. goto cleanup;
  1636. }
  1637. /* need to figure out which principal to use
  1638. 1) use the one from the ccache
  1639. 2) use username
  1640. 3) construct one in the form ldap/fqdn@REALM
  1641. */
  1642. if (!princ && username && !looks_like_a_dn(username) &&
  1643. (rc = krb5_parse_name(ctx, username, &princ))) {
  1644. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1645. "Error: could not convert [%s] into a kerberos "
  1646. "principal: %d (%s)\n", username,
  1647. rc, error_message(rc));
  1648. goto cleanup;
  1649. }
  1650. /* if still no principal, construct one */
  1651. if (!princ &&
  1652. (rc = krb5_sname_to_principal(ctx, NULL, "ldap",
  1653. KRB5_NT_SRV_HST, &princ))) {
  1654. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1655. "Error: could not construct ldap service "
  1656. "principal: %d (%s)\n", rc, error_message(rc));
  1657. goto cleanup;
  1658. }
  1659. if ((rc = krb5_unparse_name(ctx, princ, &princ_name))) {
  1660. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1661. "Unable to get name of principal: "
  1662. "%d (%s)\n", rc, error_message(rc));
  1663. goto cleanup;
  1664. }
  1665. slapi_log_error(authtracelevel, logname,
  1666. "Using principal named [%s]\n", princ_name);
  1667. /* grab the credentials from the ccache, if any -
  1668. if the credentials are still valid, we do not have
  1669. to authenticate again */
  1670. if (credentials_are_valid(ctx, cc, princ, princ_name, &rc)) {
  1671. slapi_log_error(authtracelevel, logname,
  1672. "Credentials for principal [%s] are still "
  1673. "valid - no auth is necessary.\n",
  1674. princ_name);
  1675. goto cleanup;
  1676. } else if (rc) { /* some error other than "there are no credentials" */
  1677. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1678. "Unable to verify cached credentials for "
  1679. "principal [%s]: %d (%s)\n", princ_name,
  1680. rc, error_message(rc));
  1681. goto cleanup;
  1682. }
  1683. /* find our default keytab */
  1684. if ((rc = krb5_kt_default(ctx, &kt))) {
  1685. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1686. "Unable to get default keytab: %d (%s)\n",
  1687. rc, error_message(rc));
  1688. goto cleanup;
  1689. }
  1690. /* get name of keytab for debugging purposes */
  1691. if ((rc = krb5_kt_get_name(ctx, kt, ktname, sizeof(ktname)))) {
  1692. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1693. "Unable to get name of default keytab: %d (%s)\n",
  1694. rc, error_message(rc));
  1695. goto cleanup;
  1696. }
  1697. slapi_log_error(authtracelevel, logname,
  1698. "Using keytab named [%s]\n", ktname);
  1699. /* now do the actual kerberos authentication using
  1700. the keytab, and get the creds */
  1701. rc = krb5_get_init_creds_keytab(ctx, &creds, princ, kt,
  1702. 0, NULL, NULL);
  1703. if (rc) {
  1704. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1705. "Could not get initial credentials for principal [%s] "
  1706. "in keytab [%s]: %d (%s)\n",
  1707. princ_name, ktname, rc, error_message(rc));
  1708. goto cleanup;
  1709. }
  1710. /* completely done with the keytab now, close it */
  1711. krb5_kt_close(ctx, kt);
  1712. kt = NULL; /* no double free */
  1713. /* we now have the creds and the principal to which the
  1714. creds belong - use or allocate a new memory based
  1715. cache to hold the creds */
  1716. if (!cc_name) {
  1717. #if HAVE_KRB5_CC_NEW_UNIQUE
  1718. /* krb5_cc_new_unique is a new convenience function which
  1719. generates a new unique name and returns a memory
  1720. cache with that name */
  1721. if ((rc = krb5_cc_new_unique(ctx, cc_type, NULL, &cc))) {
  1722. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1723. "Could not create new unique memory ccache: "
  1724. "%d (%s)\n",
  1725. rc, error_message(rc));
  1726. goto cleanup;
  1727. }
  1728. cc_name = slapi_ch_smprintf("%s:%s", cc_type,
  1729. krb5_cc_get_name(ctx, cc));
  1730. #else
  1731. /* store the cache in memory - krb5_init_context uses malloc
  1732. to create the ctx, so the address should be unique enough
  1733. for our purposes */
  1734. if (!(cc_name = slapi_ch_smprintf("%s:%p", cc_type, ctx))) {
  1735. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1736. "Could create Kerberos memory ccache: "
  1737. "out of memory\n");
  1738. rc = 1;
  1739. goto cleanup;
  1740. }
  1741. #endif
  1742. slapi_log_error(authtracelevel, logname,
  1743. "Generated new memory ccache [%s]\n", cc_name);
  1744. new_ccache = 1; /* need to set this in env. */
  1745. } else {
  1746. slapi_log_error(authtracelevel, logname,
  1747. "Using existing ccache [%s]\n", cc_name);
  1748. }
  1749. /* krb5_cc_resolve is basically like an init -
  1750. this creates the cache structure, and creates a slot
  1751. for the cache in the static linked list in memory, if
  1752. there is not already a slot -
  1753. see cc_memory.c for details
  1754. cc could already have been created by new_unique above
  1755. */
  1756. if (!cc && (rc = krb5_cc_resolve(ctx, cc_name, &cc))) {
  1757. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1758. "Could not create ccache [%s]: %d (%s)\n",
  1759. cc_name, rc, error_message(rc));
  1760. goto cleanup;
  1761. }
  1762. /* wipe out previous contents of cache for this principal, if any */
  1763. if ((rc = krb5_cc_initialize(ctx, cc, princ))) {
  1764. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1765. "Could not initialize ccache [%s] for the new "
  1766. "credentials for principal [%s]: %d (%s)\n",
  1767. cc_name, princ_name, rc, error_message(rc));
  1768. goto cleanup;
  1769. }
  1770. /* store the credentials in the cache */
  1771. if ((rc = krb5_cc_store_cred(ctx, cc, &creds))) {
  1772. slapi_log_error(SLAPI_LOG_FATAL, logname,
  1773. "Could not store the credentials in the "
  1774. "ccache [%s] for principal [%s]: %d (%s)\n",
  1775. cc_name, princ_name, rc, error_message(rc));
  1776. goto cleanup;
  1777. }
  1778. /* now, do a "klist" to show the credential information, and log it */
  1779. show_cached_credentials(authtracelevel, ctx, cc, princ);
  1780. /* set the CC env var to the value of the cc cache name */
  1781. /* since we can't pass krb5 context up and out of here
  1782. and down through the ldap sasl layer, we set this
  1783. env var so that calls to krb5_cc_default_name will
  1784. use this */
  1785. if (new_ccache) {
  1786. PR_snprintf(cc_env_name, sizeof(cc_env_name),
  1787. "%s=%s", KRB5_ENV_CCNAME, cc_name);
  1788. PR_SetEnv(cc_env_name);
  1789. slapi_log_error(authtracelevel, logname,
  1790. "Set new env for ccache: [%s]\n",
  1791. cc_env_name);
  1792. }
  1793. cleanup:
  1794. /* use NULL as username and authid */
  1795. slapi_ch_free_string(&vals->username);
  1796. slapi_ch_free_string(&vals->authid);
  1797. krb5_free_unparsed_name(ctx, princ_name);
  1798. if (kt) { /* NULL not allowed */
  1799. krb5_kt_close(ctx, kt);
  1800. }
  1801. if (creds.client == princ) {
  1802. creds.client = NULL;
  1803. }
  1804. krb5_free_cred_contents(ctx, &creds);
  1805. slapi_ch_free_string(&cc_name);
  1806. krb5_free_principal(ctx, princ);
  1807. if (cc) {
  1808. krb5_cc_close(ctx, cc);
  1809. }
  1810. if (ctx) { /* cannot pass NULL to free context */
  1811. krb5_free_context(ctx);
  1812. }
  1813. return;
  1814. }
  1815. #endif /* HAVE_KRB5 */