Support optional server certificate name checking. Bug 1479
[exim.git] / src / src / tlscert-openssl.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) Jeremy Harris 2014 */
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
60 bp = BIO_new_mem_buf(US cp, -1);
61 x = PEM_read_bio_X509(bp, NULL, 0, NULL);
62 int fail = 0;
63 if (!x)
64   fail = 1;
65 else
66   *cert = (void *)x;
67 BIO_free(bp);
68 store_reset(reset_point);
69 return fail;
70 }
71
72 void
73 tls_free_cert(void * cert)
74 {
75 X509_free((X509 *)cert);
76 }
77
78 /*****************************************************
79 *  Certificate field extraction routines
80 *****************************************************/
81 static uschar *
82 bio_string_copy(BIO * bp, int len)
83 {
84 uschar * cp = US"";
85 len = len > 0 ? (int) BIO_get_mem_data(bp, &cp) : 0;
86 cp = string_copyn(cp, len);
87 BIO_free(bp);
88 return cp;
89 }
90
91 static uschar *
92 bio_string_time_to_int(BIO * bp, int len)
93 {
94 uschar * cp = US"";
95 struct tm t;
96 len = len > 0 ? (int) BIO_get_mem_data(bp, &cp) : 0;
97 /*XXX %Z might be glibc-specific? */
98 (void) strptime(CS cp, "%b%t%e%t%T%t%Y%t%Z", &t);
99 BIO_free(bp);
100 /*XXX timegm might not be portable? */
101 return string_sprintf("%u", (unsigned) timegm(&t));
102 }
103
104 static uschar *
105 asn1_time_copy(const ASN1_TIME * time, uschar * mod)
106 {
107 BIO * bp = BIO_new(BIO_s_mem());
108 int len = ASN1_TIME_print(bp, time);
109 return mod &&  Ustrcmp(mod, "int") == 0
110   ? bio_string_time_to_int(bp, len)
111   : bio_string_copy(bp, len);
112 }
113
114 static uschar *
115 x509_name_copy(X509_NAME * name)
116 {
117 BIO * bp = BIO_new(BIO_s_mem());
118 int len_good =
119   X509_NAME_print_ex(bp, name, 0, XN_FLAG_RFC2253) >= 0
120   ? 1 : 0;
121 return bio_string_copy(bp, len_good);
122 }
123
124 /**/
125
126 uschar *
127 tls_cert_issuer(void * cert, uschar * mod)
128 {
129 uschar * cp = x509_name_copy(X509_get_issuer_name((X509 *)cert));
130 return mod ? tls_field_from_dn(cp, mod) : cp;
131 }
132
133 uschar *
134 tls_cert_not_before(void * cert, uschar * mod)
135 {
136 return asn1_time_copy(X509_get_notBefore((X509 *)cert), mod);
137 }
138
139 uschar *
140 tls_cert_not_after(void * cert, uschar * mod)
141 {
142 return asn1_time_copy(X509_get_notAfter((X509 *)cert), mod);
143 }
144
145 uschar *
146 tls_cert_serial_number(void * cert, uschar * mod)
147 {
148 uschar txt[256];
149 BIO * bp = BIO_new(BIO_s_mem());
150 int len = i2a_ASN1_INTEGER(bp, X509_get_serialNumber((X509 *)cert));
151
152 if (len < sizeof(txt))
153   BIO_read(bp, txt, len);
154 else
155   len = 0;
156 BIO_free(bp);
157 return string_copynlc(txt, len);        /* lowercase */
158 }
159
160 uschar *
161 tls_cert_signature(void * cert, uschar * mod)
162 {
163 BIO * bp = BIO_new(BIO_s_mem());
164 uschar * cp = NULL;
165
166 if (X509_print_ex(bp, (X509 *)cert, 0,
167   X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION | X509_FLAG_NO_SERIAL | 
168   X509_FLAG_NO_SIGNAME | X509_FLAG_NO_ISSUER | X509_FLAG_NO_VALIDITY | 
169   X509_FLAG_NO_SUBJECT | X509_FLAG_NO_PUBKEY | X509_FLAG_NO_EXTENSIONS | 
170   /* X509_FLAG_NO_SIGDUMP is the missing one */
171   X509_FLAG_NO_AUX) == 1)
172   {
173   long len = BIO_get_mem_data(bp, &cp);
174   cp = string_copyn(cp, len);
175   }
176 BIO_free(bp);
177 return cp;
178 }
179
180 uschar *
181 tls_cert_signature_algorithm(void * cert, uschar * mod)
182 {
183 return string_copy(US OBJ_nid2ln(X509_get_signature_type((X509 *)cert)));
184 }
185
186 uschar *
187 tls_cert_subject(void * cert, uschar * mod)
188 {
189 uschar * cp = x509_name_copy(X509_get_subject_name((X509 *)cert));
190 return mod ? tls_field_from_dn(cp, mod) : cp;
191 }
192
193 uschar *
194 tls_cert_version(void * cert, uschar * mod)
195 {
196 return string_sprintf("%d", X509_get_version((X509 *)cert));
197 }
198
199 uschar *
200 tls_cert_ext_by_oid(void * cert, uschar * oid, int idx)
201 {
202 int nid = OBJ_create(CS oid, "", "");
203 int nidx = X509_get_ext_by_NID((X509 *)cert, nid, idx);
204 X509_EXTENSION * ex = X509_get_ext((X509 *)cert, nidx);
205 ASN1_OCTET_STRING * adata = X509_EXTENSION_get_data(ex);
206 BIO * bp = BIO_new(BIO_s_mem());
207 long len;
208 uschar * cp1;
209 uschar * cp2;
210 uschar * cp3;
211
212 M_ASN1_OCTET_STRING_print(bp, adata);
213 /* binary data, DER encoded */
214
215 /* just dump for now */
216 len = BIO_get_mem_data(bp, &cp1);
217 cp3 = cp2 = store_get(len*3+1);
218
219 while(len)
220   {
221   sprintf(CS cp2, "%.2x ", *cp1++);
222   cp2 += 3;
223   len--;
224   }
225 cp2[-1] = '\0';
226
227 return cp3;
228 }
229
230 uschar *
231 tls_cert_subject_altname(void * cert, uschar * mod)
232 {
233 uschar * list = NULL;
234 STACK_OF(GENERAL_NAME) * san = (STACK_OF(GENERAL_NAME) *)
235   X509_get_ext_d2i((X509 *)cert, NID_subject_alt_name, NULL, NULL);
236 uschar sep = '\n';
237 uschar * tag = US"";
238 uschar * ele;
239 int match = -1;
240 int len;
241
242 if (!san) return NULL;
243
244 while (mod)
245   {
246   if (*mod == '>' && *++mod) sep = *mod++;
247   else if (Ustrcmp(mod, "dns")==0) { match = GEN_DNS; mod += 3; }
248   else if (Ustrcmp(mod, "uri")==0) { match = GEN_URI; mod += 3; }
249   else if (Ustrcmp(mod, "mail")==0) { match = GEN_EMAIL; mod += 4; }
250   else continue;
251
252   if (*mod++ != ',')
253     break;
254   }
255
256 while (sk_GENERAL_NAME_num(san) > 0)
257   {
258   GENERAL_NAME * namePart = sk_GENERAL_NAME_pop(san);
259   if (match != -1 && match != namePart->type)
260     continue;
261   switch (namePart->type)
262     {
263     case GEN_DNS:
264       tag = US"DNS";
265       ele = ASN1_STRING_data(namePart->d.dNSName);
266       len = ASN1_STRING_length(namePart->d.dNSName);
267       break;
268     case GEN_URI:
269       tag = US"URI";
270       ele = ASN1_STRING_data(namePart->d.uniformResourceIdentifier);
271       len = ASN1_STRING_length(namePart->d.uniformResourceIdentifier);
272       break;
273     case GEN_EMAIL:
274       tag = US"MAIL";
275       ele = ASN1_STRING_data(namePart->d.rfc822Name);
276       len = ASN1_STRING_length(namePart->d.rfc822Name);
277       break;
278     default:
279       continue; /* ignore unrecognised types */
280     }
281   if (ele[len]) /* not nul-terminated */
282     ele = string_copyn(ele, len);
283
284   if (strnlen(CS ele, len) == len)      /* ignore any with embedded nul */
285     list = string_append_listele(list, sep,
286           match == -1 ? string_sprintf("%s=%s", tag, ele) : ele);
287   }
288
289 sk_GENERAL_NAME_free(san);
290 return list;
291 }
292
293 uschar *
294 tls_cert_ocsp_uri(void * cert, uschar * mod)
295 {
296 STACK_OF(ACCESS_DESCRIPTION) * ads = (STACK_OF(ACCESS_DESCRIPTION) *)
297   X509_get_ext_d2i((X509 *)cert, NID_info_access, NULL, NULL);
298 int adsnum = sk_ACCESS_DESCRIPTION_num(ads);
299 int i;
300 uschar sep = '\n';
301 uschar * list = NULL;
302
303 if (mod)
304   if (*mod == '>' && *++mod) sep = *mod++;
305
306 for (i = 0; i < adsnum; i++)
307   {
308   ACCESS_DESCRIPTION * ad = sk_ACCESS_DESCRIPTION_value(ads, i);
309
310   if (ad && OBJ_obj2nid(ad->method) == NID_ad_OCSP)
311     list = string_append_listele(list, sep,
312               ASN1_STRING_data(ad->location->d.ia5));
313   }
314 return list;
315 }
316
317 uschar *
318 tls_cert_crl_uri(void * cert, uschar * mod)
319 {
320 STACK_OF(DIST_POINT) * dps = (STACK_OF(DIST_POINT) *)
321   X509_get_ext_d2i((X509 *)cert,  NID_crl_distribution_points,
322     NULL, NULL);
323 DIST_POINT * dp;
324 int dpsnum = sk_DIST_POINT_num(dps);
325 int i;
326 uschar sep = '\n';
327 uschar * list = NULL;
328
329 if (mod)
330   if (*mod == '>' && *++mod) sep = *mod++;
331
332 if (dps) for (i = 0; i < dpsnum; i++)
333   if ((dp = sk_DIST_POINT_value(dps, i)))
334     {
335     STACK_OF(GENERAL_NAME) * names = dp->distpoint->name.fullname;
336     GENERAL_NAME * np;
337     int nnum = sk_GENERAL_NAME_num(names);
338     int j;
339
340     for (j = 0; j < nnum; j++)
341       if (  (np = sk_GENERAL_NAME_value(names, j))
342          && np->type == GEN_URI
343          )
344         list = string_append_listele(list, sep,
345                 ASN1_STRING_data(np->d.uniformResourceIdentifier));
346     }
347 return list;
348 }
349
350
351
352 /*****************************************************
353 *  Certificate operator routines
354 *****************************************************/
355 static uschar *
356 fingerprint(X509 * cert, const EVP_MD * fdig)
357 {
358 int j;
359 unsigned int n;
360 uschar md[EVP_MAX_MD_SIZE];
361 uschar * cp;
362
363 if (!X509_digest(cert,fdig,md,&n))
364   {
365   expand_string_message = US"tls_cert_fprt: out of mem\n";
366   return NULL;
367   }
368 cp = store_get(n*2+1);
369 for (j = 0; j < (int)n; j++) sprintf(CS cp+2*j, "%02X", md[j]);
370 return(cp);
371 }
372
373 uschar * 
374 tls_cert_fprt_md5(void * cert)
375 {
376 return fingerprint((X509 *)cert, EVP_md5());
377 }
378
379 uschar * 
380 tls_cert_fprt_sha1(void * cert)
381 {
382 return fingerprint((X509 *)cert, EVP_sha1());
383 }
384
385 uschar * 
386 tls_cert_fprt_sha256(void * cert)
387 {
388 return fingerprint((X509 *)cert, EVP_sha256());
389 }
390
391
392 /* vi: aw ai sw=2
393 */
394 /* End of tlscert-openssl.c */