ldaputil.c 78 KB

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