1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) The Exim Maintainers 2022 */
6 /* Copyright (c) Jeremy Harris 2014 - 2019 */
8 /* This module provides TLS (aka SSL) support for Exim using the OpenSSL
9 library. It is #included into the tls.c file when that library is used.
15 #include <openssl/lhash.h>
16 #include <openssl/ssl.h>
17 #include <openssl/err.h>
18 #include <openssl/rand.h>
19 #include <openssl/x509v3.h>
21 #ifdef LIBRESSL_VERSION_NUMBER /* LibreSSL */
22 # if LIBRESSL_VERSION_NUMBER >= 0x2090000fL
23 # define EXIM_HAVE_ASN1_MACROS
26 # if OPENSSL_VERSION_NUMBER >= 0x10100000L
27 # define EXIM_HAVE_ASN1_MACROS
31 #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
32 # define ASN1_STRING_get0_data ASN1_STRING_data
35 /*****************************************************
36 * Export/import a certificate, binary/printable
37 ******************************************************
38 Return booolean success
41 tls_export_cert(uschar * buf, size_t buflen, void * cert)
43 BIO * bp = BIO_new(BIO_s_mem());
46 if ((fail = PEM_write_bio_X509(bp, (X509 *)cert) ? 0 : 1))
47 log_write(0, LOG_MAIN, "TLS error in certificate export: %s",
48 ERR_error_string(ERR_get_error(), NULL));
56 if ((n = BIO_gets(bp, cp, (int)buflen)) <= 0) break;
59 cp[-2] = '\\'; cp[-1] = 'n'; /* newline->"\n" */
60 } /* compat with string_printing() */
68 /* On error, NULL out the destination */
70 tls_import_cert(const uschar * buf, void ** cert)
72 rmark reset_point = store_mark();
73 const uschar * cp = string_unprinting(US buf);
75 X509 * x = *(X509 **)cert;
79 bp = BIO_new_mem_buf(US cp, -1);
80 if (!(x = PEM_read_bio_X509(bp, NULL, 0, NULL)))
81 log_write(0, LOG_MAIN, "TLS error in certificate import: %s",
82 ERR_error_string(ERR_get_error(), NULL));
86 store_reset(reset_point);
91 tls_free_cert(void ** cert)
93 X509 * x = *(X509 **)cert;
102 /*****************************************************
103 * Certificate field extraction routines
104 *****************************************************/
106 /* First, some internal service functions */
111 expand_string_message = US"allocation failure";
116 bio_string_copy(BIO * bp, int len)
119 len = len > 0 ? (int) BIO_get_mem_data(bp, &cp) : 0;
120 cp = string_copyn(cp, len);
126 asn1_time_copy(const ASN1_TIME * asntime, uschar * mod)
129 BIO * bp = BIO_new(BIO_s_mem());
134 len = ASN1_TIME_print(bp, asntime);
135 len = len > 0 ? (int) BIO_get_mem_data(bp, CSS &s) : 0;
137 if (mod && Ustrcmp(mod, "raw") == 0) /* native ASN */
138 s = string_copyn(s, len);
142 struct tm * tm_p = &tm;
144 uschar * tz = to_tz(US"GMT0"); /* need to call strptime with baseline TZ */
146 /* Parse OpenSSL ASN1_TIME_print output. A shame there seems to
147 be no other interface for the times.
150 /*XXX %Z might be glibc-specific? Solaris has it, at least*/
151 /*XXX should we switch to POSIX locale for this? */
153 if (!len || !strptime(CCS s, "%b %e %T %Y %Z", &tm))
154 expand_string_message = US"failed time conversion";
158 time_t t = mktime(&tm); /* make the tm self-consistent */
160 if (mod && Ustrcmp(mod, "int") == 0) /* seconds since epoch */
161 s = string_sprintf(TIME_T_FMT, t);
165 if (!f.timestamps_utc) /* decoded string in local TZ */
166 { /* shift to local TZ */
169 tm_p = localtime(&t);
171 /* "utc" is default, and rfc5280 says cert times should be Zulu */
173 /* convert to string in our format */
175 s = store_get(len, GET_UNTAINTED);
176 strftime(CS s, (size_t)len, "%b %e %T %Y %z", tm_p);
188 x509_name_copy(X509_NAME * name)
190 BIO * bp = BIO_new(BIO_s_mem());
193 if (!bp) return badalloc();
196 X509_NAME_print_ex(bp, name, 0, XN_FLAG_RFC2253) >= 0
198 return bio_string_copy(bp, len_good);
202 /* Now the extractors, called from expand.c
205 mod Optional modifiers for the operator
208 Allocated string with extracted value
212 tls_cert_issuer(void * cert, uschar * mod)
214 uschar * cp = x509_name_copy(X509_get_issuer_name((X509 *)cert));
215 return mod ? tls_field_from_dn(cp, mod) : cp;
219 tls_cert_not_before(void * cert, uschar * mod)
221 return asn1_time_copy(X509_get_notBefore((X509 *)cert), mod);
225 tls_cert_not_after(void * cert, uschar * mod)
227 return asn1_time_copy(X509_get_notAfter((X509 *)cert), mod);
231 tls_cert_serial_number(void * cert, uschar * mod)
234 BIO * bp = BIO_new(BIO_s_mem());
237 if (!bp) return badalloc();
239 len = i2a_ASN1_INTEGER(bp, X509_get_serialNumber((X509 *)cert));
240 if (len < sizeof(txt))
241 BIO_read(bp, txt, len);
245 return string_copynlc(txt, len); /* lowercase */
249 tls_cert_signature(void * cert, uschar * mod)
252 BIO * bp = BIO_new(BIO_s_mem());
254 if (!bp) return badalloc();
256 if (X509_print_ex(bp, (X509 *)cert, 0,
257 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION | X509_FLAG_NO_SERIAL |
258 X509_FLAG_NO_SIGNAME | X509_FLAG_NO_ISSUER | X509_FLAG_NO_VALIDITY |
259 X509_FLAG_NO_SUBJECT | X509_FLAG_NO_PUBKEY | X509_FLAG_NO_EXTENSIONS |
260 /* X509_FLAG_NO_SIGDUMP is the missing one */
261 X509_FLAG_NO_AUX) == 1)
263 long len = BIO_get_mem_data(bp, &cp);
266 /* Strip leading "Signature Algorithm" line */
267 while (*cp && *cp != '\n') { cp++; len--; }
268 if (*cp) { cp++; len--; }
270 /* Strip possible leading " Signature Value:\n" (seen with OpenSSL 3.0.5) */
271 if (Ustrncmp(cp, " Signature Value:\n", 21) == 0) { cp += 21; len -= 21; }
273 /* Copy only hexchars and colon (different OpenSSL versions do different spacing) */
274 for ( ; len-- && *cp; cp++)
275 if (Ustrchr("0123456789abcdef:", *cp)) g = string_catn(g, cp, 1);
276 cp = string_from_gstring(g);
283 tls_cert_signature_algorithm(void * cert, uschar * mod)
286 BIO * bp = BIO_new(BIO_s_mem());
288 if (!bp) return badalloc();
290 if (X509_print_ex(bp, (X509 *)cert, 0,
291 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION | X509_FLAG_NO_SERIAL |
292 /* X509_FLAG_NO_SIGNAME is the missing one */
293 X509_FLAG_NO_ISSUER | X509_FLAG_NO_VALIDITY |
294 X509_FLAG_NO_SUBJECT | X509_FLAG_NO_PUBKEY | X509_FLAG_NO_EXTENSIONS |
295 X509_FLAG_NO_SIGDUMP | X509_FLAG_NO_AUX) == 1)
297 long len = BIO_get_mem_data(bp, &cp);
299 /* Strip leading " Signature Algorithm: " and trailing newline */
300 while (*cp && *cp != ':') { cp++; len--; }
301 do { cp++; len--; } while (*cp && *cp == ' ');
302 if (cp[len-1] == '\n') len--;
304 cp = string_copyn(cp, len);
311 tls_cert_subject(void * cert, uschar * mod)
313 uschar * cp = x509_name_copy(X509_get_subject_name((X509 *)cert));
314 return mod ? tls_field_from_dn(cp, mod) : cp;
318 tls_cert_version(void * cert, uschar * mod)
320 return string_sprintf("%ld", X509_get_version((X509 *)cert));
324 tls_cert_ext_by_oid(void * cert, uschar * oid, int idx)
326 int nid = OBJ_create(CS oid, "", "");
327 int nidx = X509_get_ext_by_NID((X509 *)cert, nid, idx);
328 X509_EXTENSION * ex = X509_get_ext((X509 *)cert, nidx);
329 ASN1_OCTET_STRING * adata = X509_EXTENSION_get_data(ex);
330 BIO * bp = BIO_new(BIO_s_mem());
336 if (!bp) return badalloc();
338 #ifdef EXIM_HAVE_ASN1_MACROS
339 ASN1_STRING_print(bp, adata);
341 M_ASN1_OCTET_STRING_print(bp, adata);
344 /* binary data, DER encoded */
345 /* just dump for now */
346 len = BIO_get_mem_data(bp, &cp1);
347 cp3 = cp2 = store_get(len*3+1, GET_TAINTED);
351 cp2 += sprintf(CS cp2, "%.2x ", *cp1++);
360 tls_cert_subject_altname(void * cert, uschar * mod)
362 gstring * list = NULL;
363 STACK_OF(GENERAL_NAME) * san = (STACK_OF(GENERAL_NAME) *)
364 X509_get_ext_d2i((X509 *)cert, NID_subject_alt_name, NULL, NULL);
371 if (!san) return NULL;
375 if (*mod == '>' && *++mod) osep = *mod++;
376 else if (Ustrncmp(mod,"dns",3)==0) { match = GEN_DNS; mod += 3; }
377 else if (Ustrncmp(mod,"uri",3)==0) { match = GEN_URI; mod += 3; }
378 else if (Ustrncmp(mod,"mail",4)==0) { match = GEN_EMAIL; mod += 4; }
381 if (*mod == ',') mod++;
384 while (sk_GENERAL_NAME_num(san) > 0)
386 GENERAL_NAME * namePart = sk_GENERAL_NAME_pop(san);
387 if (match != -1 && match != namePart->type)
389 switch (namePart->type)
393 ele = US ASN1_STRING_get0_data(namePart->d.dNSName);
394 len = ASN1_STRING_length(namePart->d.dNSName);
398 ele = US ASN1_STRING_get0_data(namePart->d.uniformResourceIdentifier);
399 len = ASN1_STRING_length(namePart->d.uniformResourceIdentifier);
403 ele = US ASN1_STRING_get0_data(namePart->d.rfc822Name);
404 len = ASN1_STRING_length(namePart->d.rfc822Name);
407 continue; /* ignore unrecognised types */
409 if (ele[len]) /* not nul-terminated */
410 ele = string_copyn(ele, len);
412 if (Ustrlen(ele) == len) /* ignore any with embedded nul */
413 list = string_append_listele(list, osep,
414 match == -1 ? string_sprintf("%s=%s", tag, ele) : ele);
417 sk_GENERAL_NAME_free(san);
418 return string_from_gstring(list);
422 tls_cert_ocsp_uri(void * cert, uschar * mod)
424 STACK_OF(ACCESS_DESCRIPTION) * ads = (STACK_OF(ACCESS_DESCRIPTION) *)
425 X509_get_ext_d2i((X509 *)cert, NID_info_access, NULL, NULL);
426 int adsnum = sk_ACCESS_DESCRIPTION_num(ads);
428 gstring * list = NULL;
431 if (*mod == '>' && *++mod) sep = *mod++;
433 for (int i = 0; i < adsnum; i++)
435 ACCESS_DESCRIPTION * ad = sk_ACCESS_DESCRIPTION_value(ads, i);
437 if (ad && OBJ_obj2nid(ad->method) == NID_ad_OCSP)
438 list = string_append_listele_n(list, sep,
439 US ASN1_STRING_get0_data(ad->location->d.ia5),
440 ASN1_STRING_length(ad->location->d.ia5));
442 sk_ACCESS_DESCRIPTION_free(ads);
443 return string_from_gstring(list);
447 tls_cert_crl_uri(void * cert, uschar * mod)
449 STACK_OF(DIST_POINT) * dps = (STACK_OF(DIST_POINT) *)
450 X509_get_ext_d2i((X509 *)cert, NID_crl_distribution_points,
454 gstring * list = NULL;
457 if (*mod == '>' && *++mod) sep = *mod++;
459 if (dps) for (int i = 0, dpsnum = sk_DIST_POINT_num(dps); i < dpsnum; i++)
460 if ((dp = sk_DIST_POINT_value(dps, i)))
462 STACK_OF(GENERAL_NAME) * names = dp->distpoint->name.fullname;
465 for (int j = 0, nnum = sk_GENERAL_NAME_num(names); j < nnum; j++)
466 if ( (np = sk_GENERAL_NAME_value(names, j))
467 && np->type == GEN_URI
469 list = string_append_listele_n(list, sep,
470 US ASN1_STRING_get0_data(np->d.uniformResourceIdentifier),
471 ASN1_STRING_length(np->d.uniformResourceIdentifier));
473 sk_DIST_POINT_free(dps);
474 return string_from_gstring(list);
479 /*****************************************************
480 * Certificate operator routines
481 *****************************************************/
483 tls_cert_der_b64(void * cert)
485 BIO * bp = BIO_new(BIO_s_mem());
488 if (!i2d_X509_bio(bp, (X509 *)cert))
489 log_write(0, LOG_MAIN, "TLS error in certificate export: %s",
490 ERR_error_string(ERR_get_error(), NULL));
493 long len = BIO_get_mem_data(bp, &cp);
494 cp = b64encode(CUS cp, (int)len);
503 fingerprint(X509 * cert, const EVP_MD * fdig)
506 uschar md[EVP_MAX_MD_SIZE];
509 if (!X509_digest(cert,fdig,md,&n))
511 expand_string_message = US"tls_cert_fprt: out of mem\n";
514 cp = store_get(n*2+1, GET_TAINTED);
515 for (int j = 0; j < (int)n; j++) sprintf(CS cp+2*j, "%02X", md[j]);
520 tls_cert_fprt_md5(void * cert)
522 return fingerprint((X509 *)cert, EVP_md5());
526 tls_cert_fprt_sha1(void * cert)
528 return fingerprint((X509 *)cert, EVP_sha1());
532 tls_cert_fprt_sha256(void * cert)
534 return fingerprint((X509 *)cert, EVP_sha256());
540 /* End of tlscert-openssl.c */