Bump copyright date to 2019
[tor.git] / src / lib / tls / x509_openssl.c
blobcf276c4240cfd93a60ddecd4780a8d30a0cfa379
1 /* Copyright (c) 2003, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2019, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 /**
7 * \file x509_openssl.c
8 * \brief Wrapper functions to present a consistent interface to
9 * X.509 functions from OpenSSL.
10 **/
12 #define TOR_X509_PRIVATE
13 #include "lib/tls/x509.h"
14 #include "lib/tls/x509_internal.h"
15 #include "lib/tls/tortls.h"
16 #include "lib/crypt_ops/crypto_rand.h"
17 #include "lib/crypt_ops/crypto_util.h"
18 #include "lib/crypt_ops/compat_openssl.h"
20 /* Some versions of OpenSSL declare SSL_get_selected_srtp_profile twice in
21 * srtp.h. Suppress the GCC warning so we can build with -Wredundant-decl. */
22 DISABLE_GCC_WARNING(redundant-decls)
24 #include <openssl/opensslv.h>
26 #ifdef OPENSSL_NO_EC
27 #error "We require OpenSSL with ECC support"
28 #endif
30 #include <openssl/err.h>
31 #include <openssl/asn1.h>
32 #include <openssl/bio.h>
33 #include <openssl/bn.h>
34 #include <openssl/rsa.h>
36 ENABLE_GCC_WARNING(redundant-decls)
38 #include "lib/log/log.h"
39 #include "lib/log/util_bug.h"
40 #include "lib/ctime/di_ops.h"
41 #include "lib/encoding/time_fmt.h"
43 #include <stdlib.h>
44 #include <string.h>
46 #ifdef OPENSSL_1_1_API
47 #define X509_get_notBefore_const(cert) \
48 X509_get0_notBefore(cert)
49 #define X509_get_notAfter_const(cert) \
50 X509_get0_notAfter(cert)
51 #ifndef X509_get_notBefore
52 #define X509_get_notBefore(cert) \
53 X509_getm_notBefore(cert)
54 #endif
55 #ifndef X509_get_notAfter
56 #define X509_get_notAfter(cert) \
57 X509_getm_notAfter(cert)
58 #endif
59 #else /* ! OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,0) */
60 #define X509_get_notBefore_const(cert) \
61 ((const ASN1_TIME*) X509_get_notBefore((X509 *)cert))
62 #define X509_get_notAfter_const(cert) \
63 ((const ASN1_TIME*) X509_get_notAfter((X509 *)cert))
64 #endif
66 /** Return a newly allocated X509 name with commonName <b>cname</b>. */
67 static X509_NAME *
68 tor_x509_name_new(const char *cname)
70 int nid;
71 X509_NAME *name;
72 /* LCOV_EXCL_BR_START : these branches will only fail on OOM errors */
73 if (!(name = X509_NAME_new()))
74 return NULL;
75 if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
76 if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
77 (unsigned char*)cname, -1, -1, 0)))
78 goto error;
79 /* LCOV_EXCL_BR_STOP */
80 return name;
82 /* LCOV_EXCL_START : these lines will only execute on out of memory errors*/
83 error:
84 X509_NAME_free(name);
85 return NULL;
86 /* LCOV_EXCL_STOP */
89 /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
90 * signed by the private key <b>rsa_sign</b>. The commonName of the
91 * certificate will be <b>cname</b>; the commonName of the issuer will be
92 * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b>
93 * seconds, starting from some time in the past.
95 * Return a certificate on success, NULL on failure.
97 MOCK_IMPL(X509 *,
98 tor_tls_create_certificate,(crypto_pk_t *rsa,
99 crypto_pk_t *rsa_sign,
100 const char *cname,
101 const char *cname_sign,
102 unsigned int cert_lifetime))
104 /* OpenSSL generates self-signed certificates with random 64-bit serial
105 * numbers, so let's do that too. */
106 #define SERIAL_NUMBER_SIZE 8
108 time_t start_time, end_time;
109 BIGNUM *serial_number = NULL;
110 unsigned char serial_tmp[SERIAL_NUMBER_SIZE];
111 EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
112 X509 *x509 = NULL;
113 X509_NAME *name = NULL, *name_issuer=NULL;
115 tor_tls_init();
117 time_t now = time(NULL);
119 tor_tls_pick_certificate_lifetime(now, cert_lifetime,
120 &start_time, &end_time);
122 tor_assert(rsa);
123 tor_assert(cname);
124 tor_assert(rsa_sign);
125 tor_assert(cname_sign);
126 if (!(sign_pkey = crypto_pk_get_openssl_evp_pkey_(rsa_sign,1)))
127 goto error;
128 if (!(pkey = crypto_pk_get_openssl_evp_pkey_(rsa,0)))
129 goto error;
130 if (!(x509 = X509_new()))
131 goto error;
132 if (!(X509_set_version(x509, 2)))
133 goto error;
135 { /* our serial number is 8 random bytes. */
136 crypto_rand((char *)serial_tmp, sizeof(serial_tmp));
137 if (!(serial_number = BN_bin2bn(serial_tmp, sizeof(serial_tmp), NULL)))
138 goto error;
139 if (!(BN_to_ASN1_INTEGER(serial_number, X509_get_serialNumber(x509))))
140 goto error;
143 if (!(name = tor_x509_name_new(cname)))
144 goto error;
145 if (!(X509_set_subject_name(x509, name)))
146 goto error;
147 if (!(name_issuer = tor_x509_name_new(cname_sign)))
148 goto error;
149 if (!(X509_set_issuer_name(x509, name_issuer)))
150 goto error;
152 if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
153 goto error;
154 if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
155 goto error;
156 if (!X509_set_pubkey(x509, pkey))
157 goto error;
159 if (!X509_sign(x509, sign_pkey, EVP_sha256()))
160 goto error;
162 goto done;
163 error:
164 if (x509) {
165 X509_free(x509);
166 x509 = NULL;
168 done:
169 tls_log_errors(NULL, LOG_WARN, LD_NET, "generating certificate");
170 if (sign_pkey)
171 EVP_PKEY_free(sign_pkey);
172 if (pkey)
173 EVP_PKEY_free(pkey);
174 if (serial_number)
175 BN_clear_free(serial_number);
176 if (name)
177 X509_NAME_free(name);
178 if (name_issuer)
179 X509_NAME_free(name_issuer);
180 return x509;
182 #undef SERIAL_NUMBER_SIZE
185 /** Set the 'encoded' and 'encoded_len' fields of "cert" from cert->cert. */
187 tor_x509_cert_set_cached_der_encoding(tor_x509_cert_t *cert)
189 unsigned char *buf = NULL;
190 int length = i2d_X509(cert->cert, &buf);
192 if (length <= 0 || buf == NULL) {
193 return -1;
195 cert->encoded_len = (size_t) length;
196 cert->encoded = tor_malloc(length);
197 memcpy(cert->encoded, buf, length);
198 OPENSSL_free(buf);
199 return 0;
202 void
203 tor_x509_cert_impl_free_(tor_x509_cert_impl_t *cert)
205 if (cert)
206 X509_free(cert);
209 tor_x509_cert_impl_t *
210 tor_x509_cert_impl_dup_(tor_x509_cert_impl_t *cert)
212 if (cert)
213 return X509_dup(cert);
214 else
215 return NULL;
218 /** Set *<b>encoded_out</b> and *<b>size_out</b> to <b>cert</b>'s encoded DER
219 * representation and length, respectively. */
220 void
221 tor_x509_cert_get_der(const tor_x509_cert_t *cert,
222 const uint8_t **encoded_out, size_t *size_out)
224 tor_assert(cert);
225 tor_assert(encoded_out);
226 tor_assert(size_out);
227 *encoded_out = cert->encoded;
228 *size_out = cert->encoded_len;
231 /** Read a DER-encoded X509 cert, of length exactly <b>certificate_len</b>,
232 * from a <b>certificate</b>. Return a newly allocated tor_x509_cert_t on
233 * success and NULL on failure. */
234 tor_x509_cert_t *
235 tor_x509_cert_decode(const uint8_t *certificate, size_t certificate_len)
237 X509 *x509;
238 const unsigned char *cp = (const unsigned char *)certificate;
239 tor_x509_cert_t *newcert;
240 tor_assert(certificate);
241 check_no_tls_errors();
243 if (certificate_len > INT_MAX)
244 goto err;
246 x509 = d2i_X509(NULL, &cp, (int)certificate_len);
248 if (!x509)
249 goto err; /* Couldn't decode */
250 if (cp - certificate != (int)certificate_len) {
251 X509_free(x509);
252 goto err; /* Didn't use all the bytes */
254 newcert = tor_x509_cert_new(x509);
255 if (!newcert) {
256 goto err;
258 if (newcert->encoded_len != certificate_len ||
259 fast_memneq(newcert->encoded, certificate, certificate_len)) {
260 /* Cert wasn't in DER */
261 tor_x509_cert_free(newcert);
262 goto err;
264 return newcert;
265 err:
266 tls_log_errors(NULL, LOG_INFO, LD_CRYPTO, "decoding a certificate");
267 return NULL;
271 * Return a newly allocated copy of the public key that a certificate
272 * certifies. Watch out! This returns NULL if the cert's key is not RSA.
274 crypto_pk_t *
275 tor_tls_cert_get_key(tor_x509_cert_t *cert)
277 crypto_pk_t *result = NULL;
278 EVP_PKEY *pkey = X509_get_pubkey(cert->cert);
279 RSA *rsa;
280 if (!pkey)
281 return NULL;
282 rsa = EVP_PKEY_get1_RSA(pkey);
283 if (!rsa) {
284 EVP_PKEY_free(pkey);
285 return NULL;
287 result = crypto_new_pk_from_openssl_rsa_(rsa);
288 EVP_PKEY_free(pkey);
289 return result;
292 /** Check whether <b>cert</b> is well-formed, currently live, and correctly
293 * signed by the public key in <b>signing_cert</b>. If <b>check_rsa_1024</b>,
294 * make sure that it has an RSA key with 1024 bits; otherwise, just check that
295 * the key is long enough. Return 1 if the cert is good, and 0 if it's bad or
296 * we couldn't check it. */
298 tor_tls_cert_is_valid(int severity,
299 const tor_x509_cert_t *cert,
300 const tor_x509_cert_t *signing_cert,
301 time_t now,
302 int check_rsa_1024)
304 check_no_tls_errors();
305 EVP_PKEY *cert_key;
306 int r, key_ok = 0;
308 if (!signing_cert || !cert)
309 goto bad;
311 EVP_PKEY *signing_key = X509_get_pubkey(signing_cert->cert);
312 if (!signing_key)
313 goto bad;
314 r = X509_verify(cert->cert, signing_key);
315 EVP_PKEY_free(signing_key);
316 if (r <= 0)
317 goto bad;
319 /* okay, the signature checked out right. Now let's check the check the
320 * lifetime. */
321 if (tor_x509_check_cert_lifetime_internal(severity, cert->cert, now,
322 TOR_X509_PAST_SLOP,
323 TOR_X509_FUTURE_SLOP) < 0)
324 goto bad;
326 cert_key = X509_get_pubkey(cert->cert);
327 if (check_rsa_1024 && cert_key) {
328 RSA *rsa = EVP_PKEY_get1_RSA(cert_key);
329 #ifdef OPENSSL_1_1_API
330 if (rsa && RSA_bits(rsa) == 1024) {
331 #else
332 if (rsa && BN_num_bits(rsa->n) == 1024) {
333 #endif
334 key_ok = 1;
335 } else {
336 log_fn(severity, LD_CRYPTO, "Invalid certificate: Key is not RSA1024.");
339 if (rsa)
340 RSA_free(rsa);
341 } else if (cert_key) {
342 int min_bits = 1024;
343 #ifdef EVP_PKEY_EC
344 if (EVP_PKEY_base_id(cert_key) == EVP_PKEY_EC)
345 min_bits = 128;
346 #endif
347 if (EVP_PKEY_bits(cert_key) >= min_bits)
348 key_ok = 1;
350 EVP_PKEY_free(cert_key);
351 if (!key_ok)
352 goto bad;
354 /* XXXX compare DNs or anything? */
356 return 1;
357 bad:
358 tls_log_errors(NULL, LOG_INFO, LD_CRYPTO, "checking a certificate");
359 return 0;
362 /** Warn that a certificate lifetime extends through a certain range. */
363 static void
364 log_cert_lifetime(int severity, const X509 *cert, const char *problem,
365 time_t now)
367 BIO *bio = NULL;
368 BUF_MEM *buf;
369 char *s1=NULL, *s2=NULL;
370 char mytime[33];
371 struct tm tm;
372 size_t n;
374 if (problem)
375 tor_log(severity, LD_GENERAL,
376 "Certificate %s. Either their clock is set wrong, or your clock "
377 "is wrong.",
378 problem);
380 if (!(bio = BIO_new(BIO_s_mem()))) {
381 log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
383 if (!(ASN1_TIME_print(bio, X509_get_notBefore_const(cert)))) {
384 tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
385 goto end;
387 BIO_get_mem_ptr(bio, &buf);
388 s1 = tor_strndup(buf->data, buf->length);
390 (void)BIO_reset(bio);
391 if (!(ASN1_TIME_print(bio, X509_get_notAfter_const(cert)))) {
392 tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
393 goto end;
395 BIO_get_mem_ptr(bio, &buf);
396 s2 = tor_strndup(buf->data, buf->length);
398 n = strftime(mytime, 32, "%b %d %H:%M:%S %Y UTC", tor_gmtime_r(&now, &tm));
399 if (n > 0) {
400 tor_log(severity, LD_GENERAL,
401 "(certificate lifetime runs from %s through %s. Your time is %s.)",
402 s1,s2,mytime);
403 } else {
404 tor_log(severity, LD_GENERAL,
405 "(certificate lifetime runs from %s through %s. "
406 "Couldn't get your time.)",
407 s1, s2);
410 end:
411 /* Not expected to get invoked */
412 tls_log_errors(NULL, LOG_WARN, LD_NET, "getting certificate lifetime");
413 if (bio)
414 BIO_free(bio);
415 tor_free(s1);
416 tor_free(s2);
419 /** Helper: check whether <b>cert</b> is expired give or take
420 * <b>past_tolerance</b> seconds, or not-yet-valid give or take
421 * <b>future_tolerance</b> seconds. (Relative to the current time
422 * <b>now</b>.) If it is live, return 0. If it is not live, log a message
423 * and return -1. */
425 tor_x509_check_cert_lifetime_internal(int severity, const X509 *cert,
426 time_t now,
427 int past_tolerance, int future_tolerance)
429 time_t t;
431 t = now + future_tolerance;
432 if (X509_cmp_time(X509_get_notBefore_const(cert), &t) > 0) {
433 log_cert_lifetime(severity, cert, "not yet valid", now);
434 return -1;
436 t = now - past_tolerance;
437 if (X509_cmp_time(X509_get_notAfter_const(cert), &t) < 0) {
438 log_cert_lifetime(severity, cert, "already expired", now);
439 return -1;
442 return 0;
445 #ifdef TOR_UNIT_TESTS
446 /* Testing only: return a new x509 cert with the same contents as <b>inp</b>,
447 but with the expiration time <b>new_expiration_time</b>, signed with
448 <b>signing_key</b>. */
449 STATIC tor_x509_cert_t *
450 tor_x509_cert_replace_expiration(const tor_x509_cert_t *inp,
451 time_t new_expiration_time,
452 crypto_pk_t *signing_key)
454 X509 *newc = X509_dup(inp->cert);
455 X509_time_adj(X509_get_notAfter(newc), 0, &new_expiration_time);
456 EVP_PKEY *pk = crypto_pk_get_openssl_evp_pkey_(signing_key, 1);
457 tor_assert(X509_sign(newc, pk, EVP_sha256()));
458 EVP_PKEY_free(pk);
459 return tor_x509_cert_new(newc);
461 #endif /* defined(TOR_UNIT_TESTS) */