Before importing a certificate, free any previous one. Bug 1648
[exim.git] / src / src / tlscert-openssl.c
1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
4
5 /* Copyright (c) Jeremy Harris 2014 - 2015 */
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
21 /*****************************************************
22 * Export/import a certificate, binary/printable
23 *****************************************************/
24 int
25 tls_export_cert(uschar * buf, size_t buflen, void * cert)
26 {
27 BIO * bp = BIO_new(BIO_s_mem());
28 int fail;
29
30 if ((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));
33 else
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
48 BIO_free(bp);
49 return fail;
50 }
51
52 int
53 tls_import_cert(const uschar * buf, void ** cert)
54 {
55 void * reset_point = store_get(0);
56 const uschar * cp = string_unprinting(US buf);
57 BIO * bp;
58 X509 * x = *(X509 **)cert;
59 int fail = 0;
60
61 if (x) X509_free(x);
62
63 bp = BIO_new_mem_buf(US cp, -1);
64 if (!(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));
68 fail = 1;
69 }
70 else
71 *cert = (void *)x;
72 BIO_free(bp);
73 store_reset(reset_point);
74 return fail;
75 }
76
77 void
78 tls_free_cert(void * cert)
79 {
80 X509_free((X509 *)cert);
81 }
82
83
84 /*****************************************************
85 * Certificate field extraction routines
86 *****************************************************/
87
88 /* First, some internal service functions */
89
90 static uschar *
91 badalloc(void)
92 {
93 expand_string_message = US"allocation failure";
94 return NULL;
95 }
96
97 static uschar *
98 bio_string_copy(BIO * bp, int len)
99 {
100 uschar * cp = US"";
101 len = len > 0 ? (int) BIO_get_mem_data(bp, &cp) : 0;
102 cp = string_copyn(cp, len);
103 BIO_free(bp);
104 return cp;
105 }
106
107 static uschar *
108 asn1_time_copy(const ASN1_TIME * asntime, uschar * mod)
109 {
110 uschar * s = NULL;
111 BIO * bp = BIO_new(BIO_s_mem());
112 int len;
113
114 if (!bp)
115 return badalloc();
116 len = ASN1_TIME_print(bp, asntime);
117 len = len > 0 ? (int) BIO_get_mem_data(bp, &s) : 0;
118
119 if (mod && Ustrcmp(mod, "raw") == 0) /* native ASN */
120 s = string_copyn(s, len);
121 else
122 {
123 struct tm tm;
124 struct tm * tm_p = &tm;
125 BOOL mod_tz;
126 uschar * tz = to_tz(US"GMT0"); /* need to call strptime with baseline TZ */
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 }
165 BIO_free(bp);
166 return s;
167 }
168
169 static uschar *
170 x509_name_copy(X509_NAME * name)
171 {
172 BIO * bp = BIO_new(BIO_s_mem());
173 int len_good;
174
175 if (!bp) return badalloc();
176
177 len_good =
178 X509_NAME_print_ex(bp, name, 0, XN_FLAG_RFC2253) >= 0
179 ? 1 : 0;
180 return bio_string_copy(bp, len_good);
181 }
182
183 /**/
184 /* Now the extractors, called from expand.c
185 Arguments:
186 cert The certificate
187 mod Optional modifiers for the operator
188
189 Return:
190 Allocated string with extracted value
191 */
192
193 uschar *
194 tls_cert_issuer(void * cert, uschar * mod)
195 {
196 uschar * cp = x509_name_copy(X509_get_issuer_name((X509 *)cert));
197 return mod ? tls_field_from_dn(cp, mod) : cp;
198 }
199
200 uschar *
201 tls_cert_not_before(void * cert, uschar * mod)
202 {
203 return asn1_time_copy(X509_get_notBefore((X509 *)cert), mod);
204 }
205
206 uschar *
207 tls_cert_not_after(void * cert, uschar * mod)
208 {
209 return asn1_time_copy(X509_get_notAfter((X509 *)cert), mod);
210 }
211
212 uschar *
213 tls_cert_serial_number(void * cert, uschar * mod)
214 {
215 uschar txt[256];
216 BIO * bp = BIO_new(BIO_s_mem());
217 int len;
218
219 if (!bp) return badalloc();
220
221 len = i2a_ASN1_INTEGER(bp, X509_get_serialNumber((X509 *)cert));
222 if (len < sizeof(txt))
223 BIO_read(bp, txt, len);
224 else
225 len = 0;
226 BIO_free(bp);
227 return string_copynlc(txt, len); /* lowercase */
228 }
229
230 uschar *
231 tls_cert_signature(void * cert, uschar * mod)
232 {
233 uschar * cp = NULL;
234 BIO * bp = BIO_new(BIO_s_mem());
235
236 if (!bp) return badalloc();
237
238 if (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);
246
247 /* Strip leading "Signature Algorithm" line */
248 while (*cp && *cp != '\n') { cp++; len--; }
249
250 cp = string_copyn(cp+1, len-1);
251 }
252 BIO_free(bp);
253 return cp;
254 }
255
256 uschar *
257 tls_cert_signature_algorithm(void * cert, uschar * mod)
258 {
259 uschar * cp = NULL;
260 BIO * bp = BIO_new(BIO_s_mem());
261
262 if (!bp) return badalloc();
263
264 if (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 }
280 BIO_free(bp);
281 return cp;
282 }
283
284 uschar *
285 tls_cert_subject(void * cert, uschar * mod)
286 {
287 uschar * cp = x509_name_copy(X509_get_subject_name((X509 *)cert));
288 return mod ? tls_field_from_dn(cp, mod) : cp;
289 }
290
291 uschar *
292 tls_cert_version(void * cert, uschar * mod)
293 {
294 return string_sprintf("%d", X509_get_version((X509 *)cert));
295 }
296
297 uschar *
298 tls_cert_ext_by_oid(void * cert, uschar * oid, int idx)
299 {
300 int nid = OBJ_create(CS oid, "", "");
301 int nidx = X509_get_ext_by_NID((X509 *)cert, nid, idx);
302 X509_EXTENSION * ex = X509_get_ext((X509 *)cert, nidx);
303 ASN1_OCTET_STRING * adata = X509_EXTENSION_get_data(ex);
304 BIO * bp = BIO_new(BIO_s_mem());
305 long len;
306 uschar * cp1;
307 uschar * cp2;
308 uschar * cp3;
309
310 if (!bp) return badalloc();
311
312 M_ASN1_OCTET_STRING_print(bp, adata);
313 /* binary data, DER encoded */
314
315 /* just dump for now */
316 len = BIO_get_mem_data(bp, &cp1);
317 cp3 = cp2 = store_get(len*3+1);
318
319 while(len)
320 {
321 sprintf(CS cp2, "%.2x ", *cp1++);
322 cp2 += 3;
323 len--;
324 }
325 cp2[-1] = '\0';
326
327 return cp3;
328 }
329
330 uschar *
331 tls_cert_subject_altname(void * cert, uschar * mod)
332 {
333 uschar * list = NULL;
334 STACK_OF(GENERAL_NAME) * san = (STACK_OF(GENERAL_NAME) *)
335 X509_get_ext_d2i((X509 *)cert, NID_subject_alt_name, NULL, NULL);
336 uschar osep = '\n';
337 uschar * tag = US"";
338 uschar * ele;
339 int match = -1;
340 int len;
341
342 if (!san) return NULL;
343
344 while (mod && *mod)
345 {
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++;
351
352 if (*mod == ',') mod++;
353 }
354
355 while (sk_GENERAL_NAME_num(san) > 0)
356 {
357 GENERAL_NAME * namePart = sk_GENERAL_NAME_pop(san);
358 if (match != -1 && match != namePart->type)
359 continue;
360 switch (namePart->type)
361 {
362 case GEN_DNS:
363 tag = US"DNS";
364 ele = ASN1_STRING_data(namePart->d.dNSName);
365 len = ASN1_STRING_length(namePart->d.dNSName);
366 break;
367 case GEN_URI:
368 tag = US"URI";
369 ele = ASN1_STRING_data(namePart->d.uniformResourceIdentifier);
370 len = ASN1_STRING_length(namePart->d.uniformResourceIdentifier);
371 break;
372 case GEN_EMAIL:
373 tag = US"MAIL";
374 ele = ASN1_STRING_data(namePart->d.rfc822Name);
375 len = ASN1_STRING_length(namePart->d.rfc822Name);
376 break;
377 default:
378 continue; /* ignore unrecognised types */
379 }
380 if (ele[len]) /* not nul-terminated */
381 ele = string_copyn(ele, len);
382
383 if (Ustrlen(ele) == len) /* ignore any with embedded nul */
384 list = string_append_listele(list, osep,
385 match == -1 ? string_sprintf("%s=%s", tag, ele) : ele);
386 }
387
388 sk_GENERAL_NAME_free(san);
389 return list;
390 }
391
392 uschar *
393 tls_cert_ocsp_uri(void * cert, uschar * mod)
394 {
395 STACK_OF(ACCESS_DESCRIPTION) * ads = (STACK_OF(ACCESS_DESCRIPTION) *)
396 X509_get_ext_d2i((X509 *)cert, NID_info_access, NULL, NULL);
397 int adsnum = sk_ACCESS_DESCRIPTION_num(ads);
398 int i;
399 uschar sep = '\n';
400 uschar * list = NULL;
401
402 if (mod)
403 if (*mod == '>' && *++mod) sep = *mod++;
404
405 for (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)
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 }
415 }
416 sk_ACCESS_DESCRIPTION_free(ads);
417 return list;
418 }
419
420 uschar *
421 tls_cert_crl_uri(void * cert, uschar * mod)
422 {
423 STACK_OF(DIST_POINT) * dps = (STACK_OF(DIST_POINT) *)
424 X509_get_ext_d2i((X509 *)cert, NID_crl_distribution_points,
425 NULL, NULL);
426 DIST_POINT * dp;
427 int dpsnum = sk_DIST_POINT_num(dps);
428 int i;
429 uschar sep = '\n';
430 uschar * list = NULL;
431
432 if (mod)
433 if (*mod == '>' && *++mod) sep = *mod++;
434
435 if (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 )
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 }
452 }
453 sk_DIST_POINT_free(dps);
454 return list;
455 }
456
457
458
459 /*****************************************************
460 * Certificate operator routines
461 *****************************************************/
462 static uschar *
463 fingerprint(X509 * cert, const EVP_MD * fdig)
464 {
465 int j;
466 unsigned int n;
467 uschar md[EVP_MAX_MD_SIZE];
468 uschar * cp;
469
470 if (!X509_digest(cert,fdig,md,&n))
471 {
472 expand_string_message = US"tls_cert_fprt: out of mem\n";
473 return NULL;
474 }
475 cp = store_get(n*2+1);
476 for (j = 0; j < (int)n; j++) sprintf(CS cp+2*j, "%02X", md[j]);
477 return(cp);
478 }
479
480 uschar *
481 tls_cert_fprt_md5(void * cert)
482 {
483 return fingerprint((X509 *)cert, EVP_md5());
484 }
485
486 uschar *
487 tls_cert_fprt_sha1(void * cert)
488 {
489 return fingerprint((X509 *)cert, EVP_sha1());
490 }
491
492 uschar *
493 tls_cert_fprt_sha256(void * cert)
494 {
495 return fingerprint((X509 *)cert, EVP_sha256());
496 }
497
498
499 /* vi: aw ai sw=2
500 */
501 /* End of tlscert-openssl.c */