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