aboutsummaryrefslogtreecommitdiff
path: root/src/lib/tls/x509_nss.c
blob: 341bb571044e357dc3b00dc399371549365bac1c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/* Copyright (c) 2003, Roger Dingledine.
 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
 * Copyright (c) 2007-2020, The Tor Project, Inc. */
/* See LICENSE for licensing information */

/**
 * \file x509_nss.c
 * \brief Wrapper functions to present a consistent interface to
 * X.509 functions from NSS.
 **/

#define TOR_X509_PRIVATE
#include "lib/tls/x509.h"
#include "lib/tls/x509_internal.h"
#include "lib/tls/tortls.h"
#include "lib/crypt_ops/crypto_rand.h"
#include "lib/crypt_ops/crypto_util.h"
#include "lib/crypt_ops/crypto_nss_mgt.h"
#include "lib/log/util_bug.h"
#include "lib/encoding/time_fmt.h"
#include "lib/string/printf.h"

#include <pk11pub.h>
#include <cryptohi.h>
#include <cert.h>
#include <keyhi.h>
#include <time.h>

/* Units of PRTime per second.
 *
 * (PRTime is based in microseconds since the Unix
 * epoch.) */
#define PRTIME_PER_SEC (1000*1000)

static tor_x509_cert_impl_t *tor_x509_cert_decode_internal(
                      const uint8_t *certificate, int certificate_len);

static tor_x509_cert_impl_t *
tor_tls_create_certificate_internal(crypto_pk_t *rsa,
                                    crypto_pk_t *rsa_sign,
                                    CERTName *subject_dn,
                                    CERTName *issuer_dn,
                                    time_t start_time,
                                    time_t end_time)
{
  if (! crypto_pk_key_is_private(rsa_sign)) {
    return NULL;
  }

  const SECKEYPublicKey *subject_key = crypto_pk_get_nss_pubkey(rsa);
  const SECKEYPrivateKey *signing_key = crypto_pk_get_nss_privkey(rsa_sign);
  SECStatus s;

  CERTSubjectPublicKeyInfo *subject_spki = NULL;
  CERTCertificateRequest *request = NULL;
  CERTValidity *validity = NULL;
  CERTCertificate *cert = NULL;
  SECItem der = { .data = NULL, .len = 0 };
  SECItem signed_der = { .data = NULL, .len = 0 };

  CERTCertificate *result_cert = NULL;

  validity = CERT_CreateValidity(((PRTime)start_time) * PRTIME_PER_SEC,
                                 ((PRTime)end_time) * PRTIME_PER_SEC);
  if (BUG(! validity)) {
    /* LCOV_EXCL_START */
    crypto_nss_log_errors(LOG_WARN, "creating a validity object");
    goto err;
    /* LCOV_EXCL_STOP */
  }

  unsigned long serial_number;
  crypto_rand((char*)&serial_number, sizeof(serial_number));

  subject_spki = SECKEY_CreateSubjectPublicKeyInfo(subject_key);
  if (!subject_spki)
    goto err;

  /* Make a CSR ... */
  // XXX do we need to set any attributes?
  request = CERT_CreateCertificateRequest(subject_dn,
                                          subject_spki,
                                          NULL /* attributes */);
  if (!request)
    goto err;

  /* Put it into a certificate ... */
  cert = CERT_CreateCertificate(serial_number,
                                issuer_dn,
                                validity,
                                request);
  if (!cert)
    goto err;

  /* version 3 cert */
  *cert->version.data = 2; /* 2 means version 3. */
  cert->version.len = 1;

  // XXX do we need to set anything else on the cert?

  /* Sign it. */
  KeyType privkey_type = SECKEY_GetPrivateKeyType(signing_key);
  SECOidTag oid_tag = SEC_GetSignatureAlgorithmOidTag(privkey_type,
                                                      SEC_OID_SHA256);
  if (oid_tag == SEC_OID_UNKNOWN)
    goto err;
  s = SECOID_SetAlgorithmID(cert->arena, &cert->signature, oid_tag, NULL);
  if (s != SECSuccess)
    goto err;

  void *tmp;
  tmp = SEC_ASN1EncodeItem(cert->arena, &der, cert,
                           SEC_ASN1_GET(CERT_CertificateTemplate));
  if (!tmp)
    goto err;

#if 0
  s = SEC_DerSignDataWithAlgorithmID(cert->arena,
                                     &signed_der,
                                     der.data, der.len,
                                     (SECKEYPrivateKey *)signing_key,//const
                                     &cert->signature);
#else /* !(0) */
  s = SEC_DerSignData(cert->arena,
                      &signed_der,
                      der.data, der.len,
                      (SECKEYPrivateKey *)signing_key,//const
                      SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION);
#endif /* 0 */

  if (s != SECSuccess)
    goto err;

  /* Re-parse it, to make sure all the certificates we actually use
   * appear via being decoded. */
  result_cert = tor_x509_cert_decode_internal(signed_der.data, signed_der.len);

#if 1
  {
    // Can we check the cert we just signed?
    tor_assert(result_cert);
    SECKEYPublicKey *issuer_pk = (SECKEYPublicKey *)
      crypto_pk_get_nss_pubkey(rsa_sign);
    SECStatus cert_ok = CERT_VerifySignedDataWithPublicKey(
                               &result_cert->signatureWrap, issuer_pk, NULL);
    tor_assert(cert_ok == SECSuccess);
  }
#endif /* 1 */

 err:
  if (subject_spki)
    SECKEY_DestroySubjectPublicKeyInfo(subject_spki);
  if (request)
    CERT_DestroyCertificateRequest(request);
  if (validity)
    CERT_DestroyValidity(validity);

  // unnecessary, since these are allocated in the cert's arena.
  //SECITEM_FreeItem(&der, PR_FALSE);
  //SECITEM_FreeItem(&signed_der, PR_FALSE);
  if (cert)
    CERT_DestroyCertificate(cert);

  return result_cert;
}

MOCK_IMPL(tor_x509_cert_impl_t *,
tor_tls_create_certificate,(crypto_pk_t *rsa,
                            crypto_pk_t *rsa_sign,
                            const char *cname,
                            const char *cname_sign,
                            unsigned int cert_lifetime))
{
  tor_assert(rsa);
  tor_assert(rsa_sign);
  tor_assert(cname);
  tor_assert(cname_sign);

  char *cname_rfc_1485 = NULL, *cname_sign_rfc_1485 = NULL;
  CERTName *subject_dn = NULL, *issuer_dn = NULL;
  time_t start_time;
  time_t end_time;
  CERTCertificate *result = NULL;

  tor_asprintf(&cname_rfc_1485, "CN=%s", cname);
  tor_asprintf(&cname_sign_rfc_1485, "CN=%s", cname_sign);

  subject_dn = CERT_AsciiToName(cname_rfc_1485);
  issuer_dn = CERT_AsciiToName(cname_sign_rfc_1485);
  if (!subject_dn || !issuer_dn)
    goto err;

  tor_tls_pick_certificate_lifetime(time(NULL), cert_lifetime,
                                    &start_time, &end_time);

  result = tor_tls_create_certificate_internal(rsa,
                                               rsa_sign,
                                               subject_dn,
                                               issuer_dn,
                                               start_time,
                                               end_time);
 err:
  tor_free(cname_rfc_1485);
  tor_free(cname_sign_rfc_1485);
  if (subject_dn)
    CERT_DestroyName(subject_dn);
  if (issuer_dn)
    CERT_DestroyName(issuer_dn);

  return result;
}

/** Set *<b>encoded_out</b> and *<b>size_out</b> to <b>cert</b>'s encoded DER
 * representation and length, respectively. */
void
tor_x509_cert_get_der(const tor_x509_cert_t *cert,
                 const uint8_t **encoded_out, size_t *size_out)
{
  tor_assert(cert);
  tor_assert(cert->cert);
  tor_assert(encoded_out);
  tor_assert(size_out);

  const SECItem *item = &cert->cert->derCert;
  *encoded_out = item->data;
  *size_out = (size_t)item->len;
}

void
tor_x509_cert_impl_free_(tor_x509_cert_impl_t *cert)
{
  if (cert)
    CERT_DestroyCertificate(cert);
}

tor_x509_cert_impl_t *
tor_x509_cert_impl_dup_(tor_x509_cert_impl_t *cert)
{
  if (cert)
    return CERT_DupCertificate(cert);
  else
    return NULL;
}

/**
 * As tor_x509_cert_decode, but return the NSS certificate type
*/
static tor_x509_cert_impl_t *
tor_x509_cert_decode_internal(const uint8_t *certificate,
                              int certificate_len)
{
  tor_assert(certificate);
  if (certificate_len > INT_MAX)
    return NULL;

  SECItem der = { .type = siBuffer,
                  .data = (unsigned char *)certificate,
                  .len = certificate_len };
  CERTCertDBHandle *certdb = CERT_GetDefaultCertDB();
  tor_assert(certdb);
  return CERT_NewTempCertificate(certdb,
                                 &der,
                                 NULL /* nickname */,
                                 PR_FALSE, /* isPerm */
                                 PR_TRUE /* CopyDER */);
}

tor_x509_cert_t *
tor_x509_cert_decode(const uint8_t *certificate,
                     size_t certificate_len)
{
  CERTCertificate *cert = tor_x509_cert_decode_internal(certificate,
                                                        (int)certificate_len);
  if (! cert) {
    crypto_nss_log_errors(LOG_INFO, "decoding certificate");
    return NULL;
  }

  tor_x509_cert_t *newcert = tor_x509_cert_new(cert);

  return newcert;
}

crypto_pk_t *
tor_tls_cert_get_key(tor_x509_cert_t *cert)
{
  tor_assert(cert);
  CERTSubjectPublicKeyInfo *spki = &cert->cert->subjectPublicKeyInfo;
  SECKEYPublicKey *pub = SECKEY_ExtractPublicKey(spki); // we own this pointer
  if (pub == NULL)
    return NULL;

  if (SECKEY_GetPublicKeyType(pub) != rsaKey) {
    SECKEY_DestroyPublicKey(pub);
    return NULL;
  }

  return crypto_pk_new_from_nss_pubkey(pub);
}

int
tor_tls_cert_is_valid(int severity,
                      const tor_x509_cert_t *cert,
                      const tor_x509_cert_t *signing_cert,
                      time_t now,
                      int check_rsa_1024)
{
  int result = 0;

  tor_assert(cert);
  tor_assert(signing_cert);

  SECKEYPublicKey *pk = CERT_ExtractPublicKey(signing_cert->cert);
  if (pk == NULL) {
    log_fn(severity, LD_CRYPTO,
           "Invalid certificate: could not extract issuer key");
    goto fail;
  }

  SECStatus s = CERT_VerifySignedDataWithPublicKey(&cert->cert->signatureWrap,
                                                   pk, NULL);
  if (s != SECSuccess) {
    log_fn(severity, LD_CRYPTO,
           "Invalid certificate: could not validate signature.");
    goto fail;
  }

  if (tor_x509_check_cert_lifetime_internal(severity,
                                            cert->cert,
                                            now,
                                            TOR_X509_PAST_SLOP,
                                            TOR_X509_FUTURE_SLOP) < 0)
    goto fail;

  if (check_rsa_1024) {
    /* We require that this is a 1024-bit RSA key, for legacy reasons .:p */
    if (SECKEY_GetPublicKeyType(pk) != rsaKey ||
        SECKEY_PublicKeyStrengthInBits(pk) != 1024) {
      log_fn(severity, LD_CRYPTO, "Invalid certificate: Key is not RSA1024.");
      goto fail;
    }
  } else {
    /* We require that this key is at least minimally strong. */
    unsigned min_bits = (SECKEY_GetPublicKeyType(pk) == ecKey) ? 128: 1024;
    if (SECKEY_PublicKeyStrengthInBits(pk) < min_bits) {
      log_fn(severity, LD_CRYPTO, "Invalid certificate: Key is too weak.");
      goto fail;
    }
  }

  /* The certificate is valid. */
  result = 1;

 fail:
  if (pk)
    SECKEY_DestroyPublicKey(pk);
  return result;
}

static void
log_cert_lifetime(int severity,
                  const char *status,
                  time_t now,
                  PRTime notBefore,
                  PRTime notAfter)
{
  log_fn(severity, LD_GENERAL,
         "Certificate %s. Either their clock is set wrong, or your clock "
         "is incorrect.", status);

  char nowbuf[ISO_TIME_LEN+1];
  char nbbuf[ISO_TIME_LEN+1];
  char nabuf[ISO_TIME_LEN+1];

  format_iso_time(nowbuf, now);
  format_iso_time(nbbuf, notBefore / PRTIME_PER_SEC);
  format_iso_time(nabuf, notAfter / PRTIME_PER_SEC);

  log_fn(severity, LD_GENERAL,
         "(The certificate is valid from %s until %s. Your time is %s.)",
         nbbuf, nabuf, nowbuf);
}

int
tor_x509_check_cert_lifetime_internal(int severity,
                                      const tor_x509_cert_impl_t *cert,
                                      time_t now,
                                      int past_tolerance,
                                      int future_tolerance)
{
  tor_assert(cert);

  PRTime notBefore=0, notAfter=0;
  int64_t t;
  SECStatus r = CERT_GetCertTimes(cert, &notBefore, &notAfter);
  if (r != SECSuccess) {
    log_fn(severity, LD_CRYPTO,
           "Couldn't get validity times from certificate");
    return -1;
  }

  t = ((int64_t)now) + future_tolerance;
  t *= PRTIME_PER_SEC;
  if (notBefore > t) {
    log_cert_lifetime(severity, "not yet valid", now,
                      notBefore, notAfter);
    return -1;
  }

  t = ((int64_t)now) - past_tolerance;
  t *= PRTIME_PER_SEC;
  if (notAfter < t) {
    log_cert_lifetime(severity, "already expired", now,
                      notBefore, notAfter);
    return -1;
  }

  return 0;
}

#ifdef TOR_UNIT_TESTS
tor_x509_cert_t *
tor_x509_cert_replace_expiration(const tor_x509_cert_t *inp,
                                 time_t new_expiration_time,
                                 crypto_pk_t *signing_key)
{
  tor_assert(inp);
  tor_assert(signing_key);

  PRTime notBefore=0, notAfter=0;
  SECStatus r = CERT_GetCertTimes(inp->cert, &notBefore, &notAfter);
  if (r != SECSuccess)
    return NULL;

  time_t start_time = notBefore / PRTIME_PER_SEC;
  if (new_expiration_time < start_time) {
    /* This prevents an NSS error. */
    start_time = new_expiration_time - 10;
  }

  crypto_pk_t *subject_key = tor_tls_cert_get_key((tor_x509_cert_t *)inp);
  if (!subject_key)
    return NULL;

  CERTCertificate *newcert;

  newcert = tor_tls_create_certificate_internal(subject_key,
                                                signing_key,
                                                &inp->cert->subject,
                                                &inp->cert->issuer,
                                                start_time,
                                                new_expiration_time);

  crypto_pk_free(subject_key);

  return newcert ? tor_x509_cert_new(newcert) : NULL;
}
#endif /* defined(TOR_UNIT_TESTS) */