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