File: jwt_signer.cc

package info (click to toggle)
chromium 142.0.7444.175-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,295,352 kB
  • sloc: cpp: 35,488,378; ansic: 7,479,680; javascript: 4,259,373; python: 1,466,843; xml: 757,444; asm: 710,716; pascal: 187,980; sh: 89,247; perl: 88,690; objc: 79,984; sql: 56,984; cs: 42,192; fortran: 24,137; makefile: 22,913; tcl: 15,277; php: 14,018; yacc: 9,005; ruby: 7,553; awk: 3,720; lisp: 3,096; lex: 1,330; ada: 727; jsp: 228; sed: 36
file content (216 lines) | stat: -rw-r--r-- 6,239 bytes parent folder | download | duplicates (4)
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
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/webid/delegation/jwt_signer.h"

#include <map>

#include "base/base64.h"
#include "base/base64url.h"
#include "base/containers/span.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/values.h"
#include "content/browser/webid/delegation/sd_jwt.h"
#include "crypto/openssl_util.h"
#include "crypto/random.h"
#include "crypto/sign.h"
#include "third_party/boringssl/src/include/openssl/base.h"
#include "third_party/boringssl/src/include/openssl/bn.h"
#include "third_party/boringssl/src/include/openssl/bytestring.h"
#include "third_party/boringssl/src/include/openssl/ec.h"
#include "third_party/boringssl/src/include/openssl/ec_key.h"
#include "third_party/boringssl/src/include/openssl/ecdsa.h"
#include "third_party/boringssl/src/include/openssl/evp.h"
#include "third_party/boringssl/src/include/openssl/mem.h"
#include "third_party/boringssl/src/include/openssl/nid.h"
#include "third_party/boringssl/src/include/openssl/rsa.h"
#include "url/gurl.h"
#include "url/origin.h"

namespace content::sdjwt {

namespace {

// Rounds a bit count (up) to the nearest byte count.
//
// This is mathematically equivalent to (x + 7) / 8, however has no
// possibility of integer overflow.
template <typename T>
T NumBitsToBytes(T x) {
  return (x / 8) + (7 + (x % 8)) / 8;
}

int GetGroupDegreeInBytes(EC_KEY* ec) {
  const EC_GROUP* group = EC_KEY_get0_group(ec);
  return NumBitsToBytes(EC_GROUP_get_degree(group));
}

std::optional<std::string> BIGNUMToPadded(const BIGNUM* value,
                                          size_t padded_length) {
  std::vector<uint8_t> padded_bytes(padded_length);
  if (!BN_bn2bin_padded(padded_bytes.data(), padded_bytes.size(), value)) {
    return std::nullopt;
  }

  std::string base64;
  base::Base64UrlEncode(base::as_byte_span(padded_bytes),
                        base::Base64UrlEncodePolicy::OMIT_PADDING, &base64);

  return base64;
}

std::optional<std::string> BIGNUMToBase64(const BIGNUM* value) {
  return BIGNUMToPadded(value, BN_num_bytes(value));
}

// Given a DER-encoded ECDSA-Sig-Value, unpack it into a raw ECDSA signature:
// (r, s) represented as two big-endian, zero-padded 256-bit integers. This
// function requires that the input be a valid ECDSA signature and that both r
// and s are <= 256 bits.
std::vector<uint8_t> UnpackDERSignature(base::span<const uint8_t> der_sig) {
  crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
  // Create ECDSA_SIG object from DER-encoded data.
  bssl::UniquePtr<ECDSA_SIG> ecdsa_sig(
      ECDSA_SIG_from_bytes(der_sig.data(), der_sig.size()));
  CHECK(ecdsa_sig.get());

  // The result is made of two 32-byte vectors.
  const size_t kMaxBytesPerBN = 32;
  std::vector<uint8_t> result(2 * kMaxBytesPerBN);

  CHECK(BN_bn2bin_padded(&result[0], kMaxBytesPerBN, ecdsa_sig->r));
  CHECK(
      BN_bn2bin_padded(&result[kMaxBytesPerBN], kMaxBytesPerBN, ecdsa_sig->s));

  return result;
}

std::optional<std::vector<uint8_t>> SignJwtEs256(
    crypto::keypair::PrivateKey private_key,
    const std::string_view& message) {
  // The signature unpacking step won't work if the key uses a curve other than
  // P-256.
  if (!private_key.IsEcP256()) {
    return std::nullopt;
  }

  const auto sig = crypto::sign::Sign(crypto::sign::SignatureKind::ECDSA_SHA256,
                                      private_key, base::as_byte_span(message));
  return UnpackDERSignature(sig);
}

std::optional<std::vector<uint8_t>> SignJwtRs256(
    crypto::keypair::PrivateKey private_key,
    const std::string_view& message) {
  if (!private_key.IsRsa()) {
    return std::nullopt;
  }

  return crypto::sign::Sign(crypto::sign::SignatureKind::RSA_PKCS1_SHA256,
                            private_key, base::as_byte_span(message));
}

std::optional<Jwk> ExportPublicKeyEs256(
    const crypto::keypair::PrivateKey& private_key) {
  Jwk jwk;

  jwk.kty = "EC";
  jwk.crv = "P-256";
  jwk.alg = "ES256";

  // Get public key
  bssl::UniquePtr<BIGNUM> x(BN_new());
  bssl::UniquePtr<BIGNUM> y(BN_new());

  EC_KEY* ec = EVP_PKEY_get0_EC_KEY(private_key.key());

  const EC_GROUP* group = EC_KEY_get0_group(ec);
  const EC_POINT* point = EC_KEY_get0_public_key(ec);

  if (!EC_POINT_get_affine_coordinates_GFp(group, point, x.get(), y.get(),
                                           nullptr)) {
    return std::nullopt;
  }

  int degree_bytes = GetGroupDegreeInBytes(ec);

  auto x_base64 = BIGNUMToPadded(x.get(), degree_bytes);
  if (!x_base64) {
    return std::nullopt;
  }

  jwk.x = *x_base64;

  auto y_base64 = BIGNUMToPadded(y.get(), degree_bytes);
  if (!y_base64) {
    return std::nullopt;
  }

  jwk.y = *y_base64;

  return jwk;
}

std::optional<Jwk> ExportPublicKeyRsa256(
    const crypto::keypair::PrivateKey& private_key) {
  Jwk jwk;

  RSA* rsa = EVP_PKEY_get0_RSA(private_key.key());

  jwk.kty = "RSA";
  jwk.alg = "RS256";

  const BIGNUM* n;
  const BIGNUM* e;
  RSA_get0_key(rsa, &n, &e, nullptr);

  auto n_base64 = BIGNUMToBase64(n);
  if (!n_base64) {
    return std::nullopt;
  }
  jwk.n = *n_base64;

  auto e_base64 = BIGNUMToBase64(e);
  if (!e_base64) {
    return std::nullopt;
  }
  jwk.e = *e_base64;

  return jwk;
}

}  // namespace

std::optional<Jwk> ExportPublicKey(
    const crypto::keypair::PrivateKey& private_key) {
  if (private_key.IsEcP256()) {
    return ExportPublicKeyEs256(private_key);
  }

  if (private_key.IsRsa()) {
    return ExportPublicKeyRsa256(private_key);
  }

  return std::nullopt;
}

Signer CreateJwtSigner(crypto::keypair::PrivateKey private_key) {
  switch (EVP_PKEY_base_id(private_key.key())) {
    case EVP_PKEY_EC:
      return base::BindOnce(&SignJwtEs256, std::move(private_key));
    case EVP_PKEY_RSA:
      return base::BindOnce(&SignJwtRs256, std::move(private_key));
    default:
      return base::BindOnce(
          [](const std::string_view&) -> std::optional<std::vector<uint8_t>> {
            return std::nullopt;
          });
  }
}

}  // namespace content::sdjwt