util.c 57 KB

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