SPDX: license tags (mostly by guesswork)
[exim.git] / src / src / tlscert-openssl.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) The Exim Maintainers 2022 */
6 /* Copyright (c) Jeremy Harris 2014 - 2019 */
7 /* SPDX-License-Identifier: GPL-2.0-only */
8
9 /* This module provides TLS (aka SSL) support for Exim using the OpenSSL
10 library. It is #included into the tls.c file when that library is used.
11 */
12
13
14 /* Heading stuff */
15
16 #include <openssl/lhash.h>
17 #include <openssl/ssl.h>
18 #include <openssl/err.h>
19 #include <openssl/rand.h>
20 #include <openssl/x509v3.h>
21
22 #ifdef LIBRESSL_VERSION_NUMBER  /* LibreSSL */
23 # if LIBRESSL_VERSION_NUMBER >= 0x2090000fL
24 #  define EXIM_HAVE_ASN1_MACROS
25 # endif
26 #else                           /* OpenSSL */
27 # if OPENSSL_VERSION_NUMBER >= 0x10100000L
28 #  define EXIM_HAVE_ASN1_MACROS
29 # endif
30 #endif
31
32 #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
33 # define ASN1_STRING_get0_data ASN1_STRING_data
34 #endif
35
36 /*****************************************************
37 *  Export/import a certificate, binary/printable
38 ******************************************************
39 Return booolean success
40 */
41 BOOL
42 tls_export_cert(uschar * buf, size_t buflen, void * cert)
43 {
44 BIO * bp = BIO_new(BIO_s_mem());
45 BOOL fail;
46
47 if ((fail = PEM_write_bio_X509(bp, (X509 *)cert) ? 0 : 1))
48   log_write(0, LOG_MAIN, "TLS error in certificate export: %s",
49     ERR_error_string(ERR_get_error(), NULL));
50 else
51   {
52   char * cp = CS buf;
53   int n;
54   buflen -= 2;
55   for(;;)
56     {
57     if ((n = BIO_gets(bp, cp, (int)buflen)) <= 0) break;
58     cp += n+1;
59     buflen -= n+1;
60     cp[-2] = '\\'; cp[-1] = 'n'; /* newline->"\n" */
61     }                            /* compat with string_printing() */
62   *cp = '\0';
63   }
64
65 BIO_free(bp);
66 return !fail;
67 }
68
69 /* On error, NULL out the destination */
70 BOOL
71 tls_import_cert(const uschar * buf, void ** cert)
72 {
73 rmark reset_point = store_mark();
74 const uschar * cp = string_unprinting(US buf);
75 BIO * bp;
76 X509 * x = *(X509 **)cert;
77
78 if (x) X509_free(x);
79
80 bp = BIO_new_mem_buf(US cp, -1);
81 if (!(x = PEM_read_bio_X509(bp, NULL, 0, NULL)))
82   log_write(0, LOG_MAIN, "TLS error in certificate import: %s",
83     ERR_error_string(ERR_get_error(), NULL));
84
85 *cert = (void *)x;
86 BIO_free(bp);
87 store_reset(reset_point);
88 return !!x;
89 }
90
91 void
92 tls_free_cert(void ** cert)
93 {
94 X509 * x = *(X509 **)cert;
95 if (x)
96   {
97   X509_free(x);
98   *cert = NULL;
99   }
100 }
101
102
103 /*****************************************************
104 *  Certificate field extraction routines
105 *****************************************************/
106
107 /* First, some internal service functions */
108
109 static uschar *
110 badalloc(void)
111 {
112 expand_string_message = US"allocation failure";
113 return NULL;
114 }
115
116 static uschar *
117 bio_string_copy(BIO * bp, int len)
118 {
119 uschar * cp = US"";
120 len = len > 0 ? (int) BIO_get_mem_data(bp, &cp) : 0;
121 cp = string_copyn(cp, len);
122 BIO_free(bp);
123 return cp;
124 }
125
126 static uschar *
127 asn1_time_copy(const ASN1_TIME * asntime, uschar * mod)
128 {
129 uschar * s = NULL;
130 BIO * bp = BIO_new(BIO_s_mem());
131 int len;
132
133 if (!bp)
134   return badalloc();
135 len = ASN1_TIME_print(bp, asntime);
136 len = len > 0 ? (int) BIO_get_mem_data(bp, CSS &s) : 0;
137
138 if (mod && Ustrcmp(mod, "raw") == 0)            /* native ASN */
139   s = string_copyn(s, len);
140 else
141   {
142   struct tm tm;
143   struct tm * tm_p = &tm;
144   BOOL mod_tz = TRUE;
145   uschar * tz = to_tz(US"GMT0");    /* need to call strptime with baseline TZ */
146
147   /* Parse OpenSSL ASN1_TIME_print output.  A shame there seems to
148   be no other interface for the times.
149   */
150
151   /*XXX %Z might be glibc-specific?  Solaris has it, at least*/
152   /*XXX should we switch to POSIX locale for this? */
153   tm.tm_isdst = 0;
154   if (!len || !strptime(CCS s, "%b %e %T %Y %Z", &tm))
155     expand_string_message = US"failed time conversion";
156
157   else
158     {
159     time_t t = mktime(&tm);     /* make the tm self-consistent */
160
161     if (mod && Ustrcmp(mod, "int") == 0)        /* seconds since epoch */
162       s = string_sprintf(TIME_T_FMT, t);
163
164     else
165       {
166       if (!f.timestamps_utc)    /* decoded string in local TZ */
167         {                               /* shift to local TZ */
168         restore_tz(tz);
169         mod_tz = FALSE;
170         tm_p = localtime(&t);
171         }
172       /* "utc" is default, and rfc5280 says cert times should be Zulu */
173
174       /* convert to string in our format */
175       len = 32;
176       s = store_get(len, GET_UNTAINTED);
177       strftime(CS s, (size_t)len, "%b %e %T %Y %z", tm_p);
178       }
179     }
180
181   if (mod_tz)
182     restore_tz(tz);
183   }
184 BIO_free(bp);
185 return s;
186 }
187
188 static uschar *
189 x509_name_copy(X509_NAME * name)
190 {
191 BIO * bp = BIO_new(BIO_s_mem());
192 int len_good;
193
194 if (!bp) return badalloc();
195
196 len_good =
197   X509_NAME_print_ex(bp, name, 0, XN_FLAG_RFC2253) >= 0
198   ? 1 : 0;
199 return bio_string_copy(bp, len_good);
200 }
201
202 /**/
203 /* Now the extractors, called from expand.c
204 Arguments:
205   cert          The certificate
206   mod           Optional modifiers for the operator
207
208 Return:
209   Allocated string with extracted value
210 */
211
212 uschar *
213 tls_cert_issuer(void * cert, uschar * mod)
214 {
215 uschar * cp = x509_name_copy(X509_get_issuer_name((X509 *)cert));
216 return mod ? tls_field_from_dn(cp, mod) : cp;
217 }
218
219 uschar *
220 tls_cert_not_before(void * cert, uschar * mod)
221 {
222 return asn1_time_copy(X509_get_notBefore((X509 *)cert), mod);
223 }
224
225 uschar *
226 tls_cert_not_after(void * cert, uschar * mod)
227 {
228 return asn1_time_copy(X509_get_notAfter((X509 *)cert), mod);
229 }
230
231 uschar *
232 tls_cert_serial_number(void * cert, uschar * mod)
233 {
234 uschar txt[256];
235 BIO * bp = BIO_new(BIO_s_mem());
236 int len;
237
238 if (!bp) return badalloc();
239
240 len = i2a_ASN1_INTEGER(bp, X509_get_serialNumber((X509 *)cert));
241 if (len < sizeof(txt))
242   BIO_read(bp, txt, len);
243 else
244   len = 0;
245 BIO_free(bp);
246 return string_copynlc(txt, len);        /* lowercase */
247 }
248
249 uschar *
250 tls_cert_signature(void * cert, uschar * mod)
251 {
252 uschar * cp = NULL;
253 BIO * bp = BIO_new(BIO_s_mem());
254
255 if (!bp) return badalloc();
256
257 if (X509_print_ex(bp, (X509 *)cert, 0,
258   X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION | X509_FLAG_NO_SERIAL |
259   X509_FLAG_NO_SIGNAME | X509_FLAG_NO_ISSUER | X509_FLAG_NO_VALIDITY |
260   X509_FLAG_NO_SUBJECT | X509_FLAG_NO_PUBKEY | X509_FLAG_NO_EXTENSIONS |
261   /* X509_FLAG_NO_SIGDUMP is the missing one */
262   X509_FLAG_NO_AUX) == 1)
263   {
264   long len = BIO_get_mem_data(bp, &cp);
265   gstring * g = NULL;
266
267   /* Strip leading "Signature Algorithm" line */
268   while (*cp && *cp != '\n') { cp++; len--; }
269   if (*cp) { cp++; len--; }
270
271   /* Strip possible leading "    Signature Value:\n" (seen with OpenSSL 3.0.5) */
272   if (Ustrncmp(cp, "    Signature Value:\n", 21) == 0) { cp += 21; len -= 21; }
273
274   /* Copy only hexchars and colon (different OpenSSL versions do different spacing) */
275   for ( ; len-- && *cp; cp++)
276     if (Ustrchr("0123456789abcdef:", *cp)) g = string_catn(g, cp, 1);
277   cp = string_from_gstring(g);
278   }
279 BIO_free(bp);
280 return cp;
281 }
282
283 uschar *
284 tls_cert_signature_algorithm(void * cert, uschar * mod)
285 {
286 uschar * cp = NULL;
287 BIO * bp = BIO_new(BIO_s_mem());
288
289 if (!bp) return badalloc();
290
291 if (X509_print_ex(bp, (X509 *)cert, 0,
292   X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION | X509_FLAG_NO_SERIAL |
293   /* X509_FLAG_NO_SIGNAME is the missing one */
294   X509_FLAG_NO_ISSUER | X509_FLAG_NO_VALIDITY |
295   X509_FLAG_NO_SUBJECT | X509_FLAG_NO_PUBKEY | X509_FLAG_NO_EXTENSIONS |
296   X509_FLAG_NO_SIGDUMP | X509_FLAG_NO_AUX) == 1)
297   {
298   long len = BIO_get_mem_data(bp, &cp);
299
300   /* Strip leading "    Signature Algorithm: " and trailing newline */
301   while (*cp && *cp != ':') { cp++; len--; }
302   do { cp++; len--; } while (*cp && *cp == ' ');
303   if (cp[len-1] == '\n') len--;
304
305   cp = string_copyn(cp, len);
306   }
307 BIO_free(bp);
308 return cp;
309 }
310
311 uschar *
312 tls_cert_subject(void * cert, uschar * mod)
313 {
314 uschar * cp = x509_name_copy(X509_get_subject_name((X509 *)cert));
315 return mod ? tls_field_from_dn(cp, mod) : cp;
316 }
317
318 uschar *
319 tls_cert_version(void * cert, uschar * mod)
320 {
321 return string_sprintf("%ld", X509_get_version((X509 *)cert));
322 }
323
324 uschar *
325 tls_cert_ext_by_oid(void * cert, uschar * oid, int idx)
326 {
327 int nid = OBJ_create(CS oid, "", "");
328 int nidx = X509_get_ext_by_NID((X509 *)cert, nid, idx);
329 X509_EXTENSION * ex = X509_get_ext((X509 *)cert, nidx);
330 ASN1_OCTET_STRING * adata = X509_EXTENSION_get_data(ex);
331 BIO * bp = BIO_new(BIO_s_mem());
332 long len;
333 uschar * cp1;
334 uschar * cp2;
335 uschar * cp3;
336
337 if (!bp) return badalloc();
338
339 #ifdef EXIM_HAVE_ASN1_MACROS
340 ASN1_STRING_print(bp, adata);
341 #else
342 M_ASN1_OCTET_STRING_print(bp, adata);
343 #endif
344
345 /* binary data, DER encoded */
346 /* just dump for now */
347 len = BIO_get_mem_data(bp, &cp1);
348 cp3 = cp2 = store_get(len*3+1, GET_TAINTED);
349
350 while(len)
351   {
352   cp2 += sprintf(CS cp2, "%.2x ", *cp1++);
353   len--;
354   }
355 cp2[-1] = '\0';
356
357 return cp3;
358 }
359
360 uschar *
361 tls_cert_subject_altname(void * cert, uschar * mod)
362 {
363 gstring * list = NULL;
364 STACK_OF(GENERAL_NAME) * san = (STACK_OF(GENERAL_NAME) *)
365   X509_get_ext_d2i((X509 *)cert, NID_subject_alt_name, NULL, NULL);
366 uschar osep = '\n';
367 uschar * tag = US"";
368 uschar * ele;
369 int match = -1;
370 int len;
371
372 if (!san) return NULL;
373
374 while (mod && *mod)
375   {
376   if (*mod == '>' && *++mod) osep = *mod++;
377   else if (Ustrncmp(mod,"dns",3)==0) { match = GEN_DNS; mod += 3; }
378   else if (Ustrncmp(mod,"uri",3)==0) { match = GEN_URI; mod += 3; }
379   else if (Ustrncmp(mod,"mail",4)==0) { match = GEN_EMAIL; mod += 4; }
380   else mod++;
381
382   if (*mod == ',') mod++;
383   }
384
385 while (sk_GENERAL_NAME_num(san) > 0)
386   {
387   GENERAL_NAME * namePart = sk_GENERAL_NAME_pop(san);
388   if (match != -1 && match != namePart->type)
389     continue;
390   switch (namePart->type)
391     {
392     case GEN_DNS:
393       tag = US"DNS";
394       ele = US ASN1_STRING_get0_data(namePart->d.dNSName);
395       len = ASN1_STRING_length(namePart->d.dNSName);
396       break;
397     case GEN_URI:
398       tag = US"URI";
399       ele = US ASN1_STRING_get0_data(namePart->d.uniformResourceIdentifier);
400       len = ASN1_STRING_length(namePart->d.uniformResourceIdentifier);
401       break;
402     case GEN_EMAIL:
403       tag = US"MAIL";
404       ele = US ASN1_STRING_get0_data(namePart->d.rfc822Name);
405       len = ASN1_STRING_length(namePart->d.rfc822Name);
406       break;
407     default:
408       continue; /* ignore unrecognised types */
409     }
410   if (ele[len]) /* not nul-terminated */
411     ele = string_copyn(ele, len);
412
413   if (Ustrlen(ele) == len)      /* ignore any with embedded nul */
414     list = string_append_listele(list, osep,
415           match == -1 ? string_sprintf("%s=%s", tag, ele) : ele);
416   }
417
418 sk_GENERAL_NAME_free(san);
419 return string_from_gstring(list);
420 }
421
422 uschar *
423 tls_cert_ocsp_uri(void * cert, uschar * mod)
424 {
425 STACK_OF(ACCESS_DESCRIPTION) * ads = (STACK_OF(ACCESS_DESCRIPTION) *)
426   X509_get_ext_d2i((X509 *)cert, NID_info_access, NULL, NULL);
427 int adsnum = sk_ACCESS_DESCRIPTION_num(ads);
428 uschar sep = '\n';
429 gstring * list = NULL;
430
431 if (mod)
432   if (*mod == '>' && *++mod) sep = *mod++;
433
434 for (int i = 0; i < adsnum; i++)
435   {
436   ACCESS_DESCRIPTION * ad = sk_ACCESS_DESCRIPTION_value(ads, i);
437
438   if (ad && OBJ_obj2nid(ad->method) == NID_ad_OCSP)
439     list = string_append_listele_n(list, sep,
440       US ASN1_STRING_get0_data(ad->location->d.ia5),
441       ASN1_STRING_length(ad->location->d.ia5));
442   }
443 sk_ACCESS_DESCRIPTION_free(ads);
444 return string_from_gstring(list);
445 }
446
447 uschar *
448 tls_cert_crl_uri(void * cert, uschar * mod)
449 {
450 STACK_OF(DIST_POINT) * dps = (STACK_OF(DIST_POINT) *)
451   X509_get_ext_d2i((X509 *)cert,  NID_crl_distribution_points,
452     NULL, NULL);
453 DIST_POINT * dp;
454 uschar sep = '\n';
455 gstring * list = NULL;
456
457 if (mod)
458   if (*mod == '>' && *++mod) sep = *mod++;
459
460 if (dps) for (int i = 0, dpsnum = sk_DIST_POINT_num(dps); i < dpsnum; i++)
461   if ((dp = sk_DIST_POINT_value(dps, i)))
462     {
463     STACK_OF(GENERAL_NAME) * names = dp->distpoint->name.fullname;
464     GENERAL_NAME * np;
465
466     for (int j = 0, nnum = sk_GENERAL_NAME_num(names); j < nnum; j++)
467       if (  (np = sk_GENERAL_NAME_value(names, j))
468          && np->type == GEN_URI
469          )
470         list = string_append_listele_n(list, sep,
471           US ASN1_STRING_get0_data(np->d.uniformResourceIdentifier),
472           ASN1_STRING_length(np->d.uniformResourceIdentifier));
473     }
474 sk_DIST_POINT_free(dps);
475 return string_from_gstring(list);
476 }
477
478
479
480 /*****************************************************
481 *  Certificate operator routines
482 *****************************************************/
483 uschar *
484 tls_cert_der_b64(void * cert)
485 {
486 BIO * bp = BIO_new(BIO_s_mem());
487 uschar * cp = NULL;
488
489 if (!i2d_X509_bio(bp, (X509 *)cert))
490   log_write(0, LOG_MAIN, "TLS error in certificate export: %s",
491     ERR_error_string(ERR_get_error(), NULL));
492 else
493   {
494   long len = BIO_get_mem_data(bp, &cp);
495   cp = b64encode(CUS cp, (int)len);
496   }
497
498 BIO_free(bp);
499 return cp;
500 }
501
502
503 static uschar *
504 fingerprint(X509 * cert, const EVP_MD * fdig)
505 {
506 unsigned int n;
507 uschar md[EVP_MAX_MD_SIZE];
508 uschar * cp;
509
510 if (!X509_digest(cert,fdig,md,&n))
511   {
512   expand_string_message = US"tls_cert_fprt: out of mem\n";
513   return NULL;
514   }
515 cp = store_get(n*2+1, GET_TAINTED);
516 for (int j = 0; j < (int)n; j++) sprintf(CS cp+2*j, "%02X", md[j]);
517 return(cp);
518 }
519
520 uschar *
521 tls_cert_fprt_md5(void * cert)
522 {
523 return fingerprint((X509 *)cert, EVP_md5());
524 }
525
526 uschar *
527 tls_cert_fprt_sha1(void * cert)
528 {
529 return fingerprint((X509 *)cert, EVP_sha1());
530 }
531
532 uschar *
533 tls_cert_fprt_sha256(void * cert)
534 {
535 return fingerprint((X509 *)cert, EVP_sha256());
536 }
537
538
539 /* vi: aw ai sw=2
540 */
541 /* End of tlscert-openssl.c */