ldaputil.c 81 KB

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