aboutsummaryrefslogtreecommitdiff
path: root/util/crypto/certificate_utils.cc
blob: 2e90321da801bc39567f3177f40c9fee582da6b0 (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
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "util/crypto/certificate_utils.h"

#include <openssl/asn1.h>
#include <openssl/bio.h>
#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/rsa.h>
#include <openssl/ssl.h>
#include <time.h>

#include <atomic>
#include <string>

#include "util/crypto/openssl_util.h"
#include "util/crypto/sha2.h"

namespace openscreen {

namespace {

// Returns whether or not the certificate field successfully was added.
bool AddCertificateField(X509_NAME* certificate_name,
                         absl::string_view field,
                         absl::string_view value) {
  return X509_NAME_add_entry_by_txt(
             certificate_name, std::string(field).c_str(), MBSTRING_ASC,
             reinterpret_cast<const unsigned char*>(value.data()),
             value.length(), -1, 0) == 1;
}

bssl::UniquePtr<ASN1_TIME> ToAsn1Time(std::chrono::seconds time_since_epoch) {
  return bssl::UniquePtr<ASN1_TIME>(
      ASN1_TIME_set(nullptr, time_since_epoch.count()));
}

bssl::UniquePtr<X509> CreateCertificateInternal(
    absl::string_view name,
    std::chrono::seconds certificate_duration,
    EVP_PKEY key_pair,
    std::chrono::seconds time_since_unix_epoch) {
  bssl::UniquePtr<X509> certificate(X509_new());

  // Serial numbers must be unique for this session. As a pretend CA, we should
  // not issue certificates with the same serial number in the same session.
  static std::atomic_int serial_number(1);
  if (ASN1_INTEGER_set(X509_get_serialNumber(certificate.get()),
                       serial_number++) != 1) {
    return nullptr;
  }

  const bssl::UniquePtr<ASN1_TIME> now(ToAsn1Time(time_since_unix_epoch));
  const bssl::UniquePtr<ASN1_TIME> expiration_time(
      ToAsn1Time(time_since_unix_epoch + certificate_duration));

  if ((X509_set_notBefore(certificate.get(), now.get()) != 1) ||
      (X509_set_notAfter(certificate.get(), expiration_time.get()) != 1)) {
    return nullptr;
  }

  X509_NAME* certificate_name = X509_get_subject_name(certificate.get());
  if (!AddCertificateField(certificate_name, "CN", name)) {
    return nullptr;
  }

  if ((X509_set_issuer_name(certificate.get(), certificate_name) != 1) ||
      (X509_set_pubkey(certificate.get(), &key_pair) != 1) ||
      // Unlike all of the other BoringSSL methods here, X509_sign returns
      // the size of the signature in bytes.
      (X509_sign(certificate.get(), &key_pair, EVP_sha256()) <= 0) ||
      (X509_verify(certificate.get(), &key_pair) != 1)) {
    return nullptr;
  }

  return certificate;
}

}  // namespace

ErrorOr<bssl::UniquePtr<X509>> CreateCertificate(
    absl::string_view name,
    std::chrono::seconds duration,
    const EVP_PKEY& key_pair,
    std::chrono::seconds time_since_unix_epoch) {
  bssl::UniquePtr<X509> certificate = CreateCertificateInternal(
      name, duration, key_pair, time_since_unix_epoch);
  if (!certificate) {
    return Error::Code::kCertificateCreationError;
  }
  return certificate;
}

ErrorOr<std::vector<uint8_t>> ExportCertificate(const X509& certificate) {
  unsigned char* buffer = nullptr;
  // Casting-away the const because the legacy i2d_X509() function is not
  // const-correct.
  X509* const certificate_ptr = const_cast<X509*>(&certificate);
  const int len = i2d_X509(certificate_ptr, &buffer);
  if (len <= 0) {
    return Error::Code::kCertificateValidationError;
  }
  std::vector<uint8_t> raw_der_certificate(buffer, buffer + len);
  // BoringSSL doesn't free the temporary buffer.
  OPENSSL_free(buffer);
  return raw_der_certificate;
}

ErrorOr<bssl::UniquePtr<X509>> ImportCertificate(const uint8_t* der_x509_cert,
                                                 int der_x509_cert_length) {
  if (!der_x509_cert) {
    return Error::Code::kErrCertsMissing;
  }
  bssl::UniquePtr<X509> certificate(
      d2i_X509(nullptr, &der_x509_cert, der_x509_cert_length));
  if (!certificate) {
    return Error::Code::kCertificateValidationError;
  }
  return certificate;
}

std::string GetSpkiTlv(X509* cert) {
  int len = i2d_X509_PUBKEY(cert->cert_info->key, nullptr);
  if (len <= 0) {
    return {};
  }
  std::string x(len, 0);
  uint8_t* data = reinterpret_cast<uint8_t*>(&x[0]);
  if (!i2d_X509_PUBKEY(cert->cert_info->key, &data)) {
    return {};
  }
  return x;
}

ErrorOr<uint64_t> ParseDerUint64(ASN1_INTEGER* asn1int) {
  if (asn1int->length > 8 || asn1int->length == 0) {
    return Error::Code::kParameterInvalid;
  }
  uint64_t result = 0;
  for (int i = 0; i < asn1int->length; ++i) {
    result = (result << 8) | asn1int->data[i];
  }
  return result;
}

}  // namespace openscreen