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