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