1 /* ldap.c - LDAP access
2 * Copyright (C) 2002 Klarälvdalens Datakonsult AB
3 * Copyright (C) 2003, 2004, 2005, 2007, 2008, 2010 g10 Code GmbH
5 * This file is part of DirMngr.
7 * DirMngr is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * DirMngr is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
36 #include "ldapserver.h"
38 #include "ldap-wrapper.h"
42 #define UNENCODED_URL_CHARS "abcdefghijklmnopqrstuvwxyz" \
43 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
46 #define USERCERTIFICATE "userCertificate"
47 #define CACERTIFICATE "caCertificate"
48 #define X509CACERT "x509caCert"
49 #define USERSMIMECERTIFICATE "userSMIMECertificate"
52 /* Definition for the context of the cert fetch functions. */
53 struct cert_fetch_context_s
55 ksba_reader_t reader; /* The reader used (shallow copy). */
56 unsigned char *tmpbuf; /* Helper buffer. */
57 size_t tmpbufsize; /* Allocated size of tmpbuf. */
58 int truncated; /* Flag to indicate a truncated output. */
64 /* Add HOST and PORT to our list of LDAP servers. Fixme: We should
65 better use an extra list of servers. */
67 add_server_to_servers (const char *host, int port)
70 ldap_server_t last = NULL;
76 for (server=opt.ldapservers; server; server = server->next)
78 if (!strcmp (server->host, host) && server->port == port)
79 return; /* already in list... */
83 /* We assume that the host names are all supplied by our
84 configuration files and thus are sane. To keep this assumption
85 we must reject all invalid host names. */
87 if (!strchr ("abcdefghijklmnopqrstuvwxyz"
88 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
91 log_error (_("invalid char 0x%02x in host name - not added\n"), *s);
95 log_info (_("adding '%s:%d' to the ldap server list\n"), host, port);
96 server = xtrycalloc (1, sizeof *s);
98 log_error (_("malloc failed: %s\n"), strerror (errno));
101 server->host = xstrdup (host);
106 opt.ldapservers = server;
113 /* Perform an LDAP query. Returns an gpg error code or 0 on success.
114 The function returns a new reader object at READER. */
116 run_ldap_wrapper (ctrl_t ctrl,
120 const char *host, int port,
121 const char *user, const char *pass,
122 const char *dn, const char *filter, const char *attr,
124 ksba_reader_t *reader)
126 const char *argv[40];
128 char portbuf[30], timeoutbuf[30];
134 if (pass) /* Note, that the password must be the first item. */
136 argv[argc++] = "--pass";
140 argv[argc++] = "-vv";
141 argv[argc++] = "--log-with-pid";
143 argv[argc++] = "--multi";
146 sprintf (timeoutbuf, "%u", opt.ldaptimeout);
147 argv[argc++] = "--timeout";
148 argv[argc++] = timeoutbuf;
150 argv[argc++] = "--only-search-timeout";
154 argv[argc++] = "--proxy";
155 argv[argc++] = proxy;
159 argv[argc++] = "--host";
164 sprintf (portbuf, "%d", port);
165 argv[argc++] = "--port";
166 argv[argc++] = portbuf;
170 argv[argc++] = "--user";
175 argv[argc++] = "--dn";
180 argv[argc++] = "--filter";
181 argv[argc++] = filter;
185 argv[argc++] = "--attr";
188 argv[argc++] = url? url : "ldap://";
191 return ldap_wrapper (ctrl, reader, argv);
197 /* Perform a LDAP query using a given URL. On success a new ksba
198 reader is returned. If HOST or PORT are not 0, they are used to
199 override the values from the URL. */
201 url_fetch_ldap (ctrl_t ctrl, const char *url, const char *host, int port,
202 ksba_reader_t *reader)
206 err = run_ldap_wrapper (ctrl,
207 1, /* Ignore explicit timeout because CRLs
208 might be very large. */
213 NULL, NULL, NULL, url,
216 /* FIXME: This option might be used for DoS attacks. Because it
217 will enlarge the list of servers to consult without a limit and
218 all LDAP queries w/o a host are will then try each host in
220 if (!err && opt.add_new_ldapservers && !opt.ldap_proxy)
223 add_server_to_servers (host, port);
226 char *tmp = host_and_port_from_url (url, &port);
229 add_server_to_servers (tmp, port);
235 /* If the lookup failed and we are not only using the proxy, we try
236 again using our default list of servers. */
237 if (err && !(opt.ldap_proxy && opt.only_ldap_proxy))
239 struct ldapserver_iter iter;
242 log_debug ("no hostname in URL or query failed; "
243 "trying all default hostnames\n");
245 for (ldapserver_iter_begin (&iter, ctrl);
246 err && ! ldapserver_iter_end_p (&iter);
247 ldapserver_iter_next (&iter))
249 ldap_server_t server = iter.server;
251 err = run_ldap_wrapper (ctrl,
255 server->host, server->port,
257 NULL, NULL, NULL, url,
269 /* Perform an LDAP query on all configured servers. On error the
270 error code of the last try is returned. */
272 attr_fetch_ldap (ctrl_t ctrl,
273 const char *dn, const char *attr, ksba_reader_t *reader)
275 gpg_error_t err = gpg_error (GPG_ERR_CONFIGURATION);
276 struct ldapserver_iter iter;
280 /* FIXME; we might want to look at the Base SN to try matching
282 for (ldapserver_iter_begin (&iter, ctrl); ! ldapserver_iter_end_p (&iter);
283 ldapserver_iter_next (&iter))
285 ldap_server_t server = iter.server;
287 err = run_ldap_wrapper (ctrl,
291 server->host, server->port,
292 server->user, server->pass,
293 dn, "objectClass=*", attr, NULL,
296 break; /* Probably found a result. Ready. */
302 /* Parse PATTERN and return a new strlist to be used for the actual
303 LDAP query. Bit 0 of the flags field is set if that pattern is
304 actually a base specification. Caller must release the returned
305 strlist. NULL is returned on error.
312 * x Email address Indicated by a left angle bracket.
313 * Exact word match in user id or subj. name
314 * x Subj. DN indicated bu a leading slash
316 * Serial number + subj. DN
317 * x Substring match indicated by a leading '*; is also the default.
321 parse_one_pattern (const char *pattern)
323 strlist_t result = NULL;
328 case '<': /* Email. */
331 result = xmalloc (sizeof *result + 5 + strlen (pattern));
334 p = stpcpy (stpcpy (result->d, "mail="), pattern);
337 if (!*result->d) /* Error. */
344 case '/': /* Subject DN. */
348 result = xmalloc (sizeof *result + strlen (pattern));
350 result->flags = 1; /* Base spec. */
351 strcpy (result->d, pattern);
354 case '#': /* Issuer DN. */
356 if (*pattern == '/') /* Just issuer DN. */
360 else /* Serial number + issuer DN */
366 default: /* Take as substring match. */
368 const char format[] = "(|(sn=*%s*)(|(cn=*%s*)(mail=*%s*)))";
372 result = xmalloc (sizeof *result
373 + strlen (format) + 3 * strlen (pattern));
376 sprintf (result->d, format, pattern, pattern, pattern);
385 /* Take the string STRING and escape it according to the URL rules.
386 Retun a newly allocated string. */
388 escape4url (const char *string)
397 for (s=string,n=0; *s; s++)
398 if (strchr (UNENCODED_URL_CHARS, *s))
407 for (s=string,p=buf; *s; s++)
408 if (strchr (UNENCODED_URL_CHARS, *s))
412 sprintf (p, "%%%02X", *(const unsigned char *)s);
422 /* Create a LDAP URL from DN and FILTER and return it in URL. We don't
423 need the host and port because this will be specified using the
426 make_url (char **url, const char *dn, const char *filter)
429 char *u_dn, *u_filter;
430 char const attrs[] = (USERCERTIFICATE ","
431 /* USERSMIMECERTIFICATE "," */
437 u_dn = escape4url (dn);
439 return gpg_error_from_errno (errno);
441 u_filter = escape4url (filter);
444 err = gpg_error_from_errno (errno);
448 *url = malloc ( 8 + strlen (u_dn)
450 + 5 + strlen (u_filter) + 1 );
453 err = gpg_error_from_errno (errno);
459 stpcpy (stpcpy (stpcpy (stpcpy (stpcpy (stpcpy (*url, "ldap:///"),
471 /* Prepare an LDAP query to return the attribute ATTR for the DN. All
472 configured default servers are queried until one responds. This
473 function returns an error code or 0 and a CONTEXT on success. */
475 start_default_fetch_ldap (ctrl_t ctrl, cert_fetch_context_t *context,
476 const char *dn, const char *attr)
479 struct ldapserver_iter iter;
481 *context = xtrycalloc (1, sizeof **context);
483 return gpg_error_from_errno (errno);
485 /* FIXME; we might want to look at the Base SN to try matching
487 err = gpg_error (GPG_ERR_CONFIGURATION);
489 for (ldapserver_iter_begin (&iter, ctrl); ! ldapserver_iter_end_p (&iter);
490 ldapserver_iter_next (&iter))
492 ldap_server_t server = iter.server;
494 err = run_ldap_wrapper (ctrl,
498 server->host, server->port,
499 server->user, server->pass,
500 dn, "objectClass=*", attr, NULL,
501 &(*context)->reader);
503 break; /* Probably found a result. */
515 /* Prepare an LDAP query to return certificates matching PATTERNS using
516 the SERVER. This function returns an error code or 0 and a CONTEXT
519 start_cert_fetch_ldap (ctrl_t ctrl, cert_fetch_context_t *context,
520 strlist_t patterns, const ldap_server_t server)
531 int argc_malloced = 0;
532 char portbuf[30], timeoutbuf[30];
537 if (opt.ldap_proxy && !(proxy = xtrystrdup (opt.ldap_proxy)))
539 err = gpg_error_from_syserror ();
545 if (server->host && !(host = xtrystrdup (server->host)))
547 err = gpg_error_from_syserror ();
551 if (server->user && !(user = xtrystrdup (server->user)))
553 err = gpg_error_from_syserror ();
556 if (server->pass && !(pass = xtrystrdup (server->pass)))
558 err = gpg_error_from_syserror ();
564 else /* Use a default server. */
565 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
571 if (pass) /* Note: Must be the first item. */
573 argv[argc++] = "--pass";
577 argv[argc++] = "-vv";
578 argv[argc++] = "--log-with-pid";
579 argv[argc++] = "--multi";
582 snprintf (timeoutbuf, sizeof timeoutbuf, "%u", opt.ldaptimeout);
583 argv[argc++] = "--timeout";
584 argv[argc++] = timeoutbuf;
588 argv[argc++] = "--proxy";
589 argv[argc++] = proxy;
593 argv[argc++] = "--host";
598 snprintf (portbuf, sizeof portbuf, "%d", port);
599 argv[argc++] = "--port";
600 argv[argc++] = portbuf;
604 argv[argc++] = "--user";
608 /* All entries in argv from this index on are malloc'ed. */
609 argc_malloced = argc;
611 for (; patterns; patterns = patterns->next)
616 if (argc >= DIM (argv) - 1)
618 /* Too many patterns. It does not make sense to allow an
619 arbitrary number of patters because the length of the
620 command line is limited anyway. */
621 /* fixme: cleanup. */
622 return gpg_error (GPG_ERR_RESOURCE_LIMIT);
624 sl = parse_one_pattern (patterns->d);
627 log_error (_("start_cert_fetch: invalid pattern '%s'\n"),
629 err = gpg_error (GPG_ERR_INV_USER_ID);
633 err = make_url (&url, sl->d, "objectClass=*");
635 err = make_url (&url, base, sl->d);
643 *context = xtrycalloc (1, sizeof **context);
646 err = gpg_error_from_errno (errno);
650 err = ldap_wrapper (ctrl, &(*context)->reader, (const char**)argv);
659 for (; argc_malloced < argc; argc_malloced++)
660 xfree (argv[argc_malloced]);
669 /* Read a fixed amount of data from READER into BUFFER. */
671 read_buffer (ksba_reader_t reader, unsigned char *buffer, size_t count)
678 err = ksba_reader_read (reader, buffer, count, &nread);
688 /* Fetch the next certificate. Return 0 on success, GPG_ERR_EOF if no
689 (more) certificates are available or any other error
690 code. GPG_ERR_TRUNCATED may be returned to indicate that the result
691 has been truncated. */
693 fetch_next_cert_ldap (cert_fetch_context_t context,
694 unsigned char **value, size_t *valuelen)
697 unsigned char hdr[5];
701 /* int is_cms = 0; */
709 err = read_buffer (context->reader, hdr, 5);
712 n = buf32_to_ulong (hdr+1);
713 if (*hdr == 'V' && okay)
715 #if 0 /* That code is not yet ready. */
719 /* The certificate needs to be parsed from CMS data. */
721 ksba_stop_reason_t stopreason;
724 err = ksba_cms_new (&cms);
727 err = ksba_cms_set_reader_writer (cms, context->reader, NULL);
730 log_error ("ksba_cms_set_reader_writer failed: %s\n",
737 err = ksba_cms_parse (cms, &stopreason);
740 log_error ("ksba_cms_parse failed: %s\n",
745 if (stopreason == KSBA_SR_BEGIN_DATA)
746 log_error ("userSMIMECertificate is not "
747 "a certs-only message\n");
749 while (stopreason != KSBA_SR_READY);
751 for (i=0; (cert=ksba_cms_get_cert (cms, i)); i++)
753 check_and_store (ctrl, stats, cert, 0);
754 ksba_cert_release (cert);
758 log_error ("no certificate found\n");
765 *value = xtrymalloc (n);
767 return gpg_error_from_errno (errno);
769 err = read_buffer (context->reader, *value, n);
770 break; /* Ready or error. */
773 else if (!n && *hdr == 'A')
777 if (n > context->tmpbufsize)
779 xfree (context->tmpbuf);
780 context->tmpbufsize = 0;
781 context->tmpbuf = xtrymalloc (n+1);
782 if (!context->tmpbuf)
783 return gpg_error_from_errno (errno);
784 context->tmpbufsize = n;
786 err = read_buffer (context->reader, context->tmpbuf, n);
792 p[n] = 0; /*(we allocated one extra byte for this.)*/
793 /* fixme: is_cms = 0; */
794 if ( (pend = strchr (p, ';')) )
795 *pend = 0; /* Strip off the extension. */
796 if (!ascii_strcasecmp (p, USERCERTIFICATE))
799 log_debug ("fetch_next_cert_ldap: got attribute '%s'\n",
803 else if (!ascii_strcasecmp (p, CACERTIFICATE))
806 log_debug ("fetch_next_cert_ldap: got attribute '%s'\n",
810 else if (!ascii_strcasecmp (p, X509CACERT))
813 log_debug ("fetch_next_cert_ldap: got attribute '%s'\n",
817 /* else if (!ascii_strcasecmp (p, USERSMIMECERTIFICATE)) */
819 /* if (DBG_LOOKUP) */
820 /* log_debug ("fetch_next_cert_ldap: got attribute '%s'\n", */
821 /* USERSMIMECERTIFICATE); */
828 log_debug ("fetch_next_cert_ldap: got attribute '%s'"
833 else if (*hdr == 'E')
836 p[n] = 0; /*(we allocated one extra byte for this.)*/
837 if (!strcmp (p, "truncated"))
839 context->truncated = 1;
840 log_info (_("ldap_search hit the size limit of"
852 if (gpg_err_code (err) == GPG_ERR_EOF && context->truncated)
854 context->truncated = 0; /* So that the next call would return EOF. */
855 err = gpg_error (GPG_ERR_TRUNCATED);
864 end_cert_fetch_ldap (cert_fetch_context_t context)
868 ksba_reader_t reader = context->reader;
870 xfree (context->tmpbuf);
872 ldap_wrapper_release_context (reader);
873 ksba_reader_release (reader);