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