bullion 0.12.0 → 0.12.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,6 +7,10 @@ module Bullion
7
7
  module Ssl
8
8
  # Converts the incoming key data to an OpenSSL public key usable to verify JWT signatures
9
9
  def openssl_compat(key_data)
10
+ # An OpenSSL key (e.g. a certificate's public key) is already usable;
11
+ # JWK hashes are converted below
12
+ return key_data if key_data.is_a?(OpenSSL::PKey::PKey)
13
+
10
14
  case key_data["kty"]
11
15
  when "RSA"
12
16
  key_data_to_rsa(key_data)
@@ -34,7 +38,11 @@ module Bullion
34
38
  OpenSSL::PKey::RSA.new(outer_sequence.to_der)
35
39
  end
36
40
 
37
- def key_data_to_ecdsa(key_data)
41
+ # Maps a JWK "crv" name to an OpenSSL curve name. RFC 7518 requires
42
+ # that an unknown or unsupported curve be rejected as a bad public
43
+ # key, never as an unhandled exception.
44
+ # @see https://tools.ietf.org/html/rfc7518#page-30
45
+ def ec_curve_name(crv)
38
46
  crv_mapping = {
39
47
  "P-256" => "prime256v1",
40
48
  "secp256k1" => "secp256k1",
@@ -42,14 +50,21 @@ module Bullion
42
50
  "P-521" => "secp521r1"
43
51
  }
44
52
 
53
+ curve_name = crv_mapping[crv]
54
+ return curve_name if curve_name
55
+
56
+ raise Bullion::Acme::Errors::BadPublicKey,
57
+ "Unsupported EC curve: #{crv.inspect}; " \
58
+ "supported curves are #{crv_mapping.keys.join(", ")}"
59
+ end
60
+
61
+ def key_data_to_ecdsa(key_data)
45
62
  x = base64_to_octet(key_data["x"])
46
63
  y = base64_to_octet(key_data["y"])
47
- curve_name = crv_mapping[key_data["crv"]]
48
- raise "Unknown curve" unless curve_name
64
+ curve_name = ec_curve_name(key_data["crv"])
49
65
 
50
66
  key_group = OpenSSL::PKey::EC::Group.new(curve_name)
51
- key_bn = OpenSSL::BN.new("\x04#{x}#{y}", 2)
52
- key_point = OpenSSL::PKey::EC::Point.new(key_group, key_bn)
67
+ key_point = ec_point_from_jwk(key_group, x, y)
53
68
 
54
69
  pk_sequence = OpenSSL::ASN1::Sequence.new(
55
70
  [OpenSSL::ASN1::ObjectId("id-ecPublicKey"), OpenSSL::ASN1::ObjectId(curve_name)]
@@ -61,6 +76,18 @@ module Bullion
61
76
  OpenSSL::PKey::EC.new(outer_sequence.to_der)
62
77
  end
63
78
 
79
+ # Builds an EC point from JWK coordinate octets. RFC 7518 requires
80
+ # fixed-width coordinates, and OpenSSL rejects anything else — a
81
+ # malformed or off-curve encoding must surface as an ACME
82
+ # "malformed" request error (RFC 8555 section 6.4), never as an
83
+ # unhandled exception.
84
+ # @see https://tools.ietf.org/html/rfc7518#section-6.2.1
85
+ def ec_point_from_jwk(group, x_octets, y_octets)
86
+ OpenSSL::PKey::EC::Point.new(group, OpenSSL::BN.new("\x04#{x_octets}#{y_octets}", 2))
87
+ rescue OpenSSL::PKey::EC::Point::Error => e
88
+ raise Bullion::Acme::Errors::Malformed, "Invalid EC public key: #{e.message}"
89
+ end
90
+
64
91
  def key_data_to_eddsa(key_data)
65
92
  curve = key_data["crv"]
66
93
  x = base64_to_octet(key_data["x"])
@@ -26,6 +26,22 @@ module Bullion
26
26
  self.expires ||= Time.now + (60 * 60)
27
27
  end
28
28
 
29
+ # Whether this authorization's lifetime has elapsed. The stored status
30
+ # is deliberately left untouched: clients still see the last persisted
31
+ # status, while issuance and revocation coverage consult
32
+ # #valid_for_issuance?.
33
+ def expired?
34
+ expires <= Time.now
35
+ end
36
+
37
+ # Whether this authorization still proves control of its identifier.
38
+ # RFC 8555 carries an "expires" timestamp precisely so a proof stops
39
+ # being honored after its lifetime, even though its stored status has
40
+ # not been rewritten.
41
+ def valid_for_issuance?
42
+ valid_status? && !expired?
43
+ end
44
+
29
45
  def prep_challenges!
30
46
  %w[http-01 dns-01].each do |type|
31
47
  chall = Challenge.new
@@ -13,7 +13,12 @@ module Bullion
13
13
  has_one :order
14
14
 
15
15
  def init_values
16
- self.serial ||= SecureRandom.hex(4).to_i(16)
16
+ # CABF Baseline Requirements require at least 64 bits of CSPRNG output
17
+ # in certificate serial numbers. Eight random bytes provide that, but
18
+ # the serial column is a signed BIGINT, so clear the top bit to keep
19
+ # the value positive and storable. Existing certificates keep their
20
+ # serials; this only affects new issuances.
21
+ self.serial ||= SecureRandom.hex(8).to_i(16) & 0x7FFF_FFFF_FFFF_FFFF
17
22
  end
18
23
 
19
24
  def fingerprint
@@ -29,6 +29,12 @@ module Bullion
29
29
  self.token ||= SecureRandom.alphanumeric(48)
30
30
  end
31
31
 
32
+ # Whether this challenge's lifetime has elapsed. An elapsed challenge
33
+ # must not be promoted to valid or advance its authorization.
34
+ def expired?
35
+ expires <= Time.now
36
+ end
37
+
32
38
  def thumbprint
33
39
  cipher = OpenSSL::Digest.new("SHA256")
34
40
  digest = cipher.digest(lexicographically_ordered_public_key.to_json)
@@ -4,6 +4,19 @@ module Bullion
4
4
  module Models
5
5
  # ACMEv2 Nonce model
6
6
  class Nonce < ActiveRecord::Base
7
+ # How long a minted nonce stays usable. RFC 8555 does not mandate a
8
+ # lifetime; fifteen minutes is comfortably longer than a client needs
9
+ # to use a freshly minted nonce while keeping stale rows short-lived.
10
+ TTL = 15 * 60
11
+
12
+ # Hard ceiling on outstanding nonce rows. A client that mints nonces
13
+ # without consuming them cannot grow the table past this bound.
14
+ MAX_OUTSTANDING = 10_000
15
+
16
+ # How often a mint performs the expiry sweep. Sweeping on every request
17
+ # would scan the table needlessly under normal load.
18
+ CLEANUP_INTERVAL = 60
19
+
7
20
  after_initialize :init_values, unless: :persisted?
8
21
 
9
22
  validates_uniqueness_of :token
@@ -12,11 +25,37 @@ module Bullion
12
25
  self.token ||= SecureRandom.alphanumeric
13
26
  end
14
27
 
15
- # Delete old nonces
16
- def self.clean_up!
17
- # nonces older than this can safely be deleted
18
- where("created_at < ?", Time.now - 86_400).delete_all
28
+ # Delete nonces that are older than {TTL}; they can no longer be used.
29
+ def self.clean_up!(now: Time.now)
30
+ where("created_at < ?", now - TTL).delete_all
31
+ end
32
+
33
+ # Keep at most +limit+ nonces, deleting the oldest first. This is the
34
+ # hard bound on table growth: once the cap is reached, each mint evicts
35
+ # the oldest outstanding nonce instead of accumulating indefinitely.
36
+ def self.prune!(limit: MAX_OUTSTANDING)
37
+ excess = count - limit
38
+ return unless excess.positive?
39
+
40
+ ids = order(:created_at).limit(excess).pluck(:id)
41
+ where(id: ids).delete_all
42
+ end
43
+
44
+ # Mint a nonce while keeping the table bounded.
45
+ def self.mint!
46
+ clean_up_if_due!
47
+ prune!
48
+ create.token
49
+ end
50
+
51
+ def self.clean_up_if_due!
52
+ now = Time.now
53
+ return if @last_cleanup_at && now - @last_cleanup_at < CLEANUP_INTERVAL
54
+
55
+ @last_cleanup_at = now
56
+ clean_up!(now:)
19
57
  end
58
+ private_class_method :clean_up_if_due!
20
59
  end
21
60
  end
22
61
  end
@@ -28,6 +28,19 @@ module Bullion
28
28
  self.not_after ||= Time.now + (60 * 60 * 24 * 90) # 90 days
29
29
  end
30
30
 
31
+ # Whether this order's lifetime has elapsed.
32
+ def expired?
33
+ expires <= Time.now
34
+ end
35
+
36
+ # Whether the order may be finalized: it must be ready, within its own
37
+ # lifetime, and every authorization must still prove control. An order
38
+ # already marked ready can outlive its authorizations, so readiness is
39
+ # re-checked here rather than trusted from the persisted status.
40
+ def ready_for_issuance?
41
+ ready_status? && !expired? && authorizations.all?(&:valid_for_issuance?)
42
+ end
43
+
31
44
  def prep_authorizations!
32
45
  identifiers.each do |identifier|
33
46
  authorization = Authorization.new
@@ -6,11 +6,15 @@ module Bullion
6
6
  class OrderCsr
7
7
  class << self
8
8
  def from_acme_request(order, raw_data)
9
- decoded_data = Base64.urlsafe_decode64(raw_data)
9
+ decoded_data = Base64.urlsafe_decode64(raw_data.to_s)
10
10
  reencoded_data = Base64.encode64(decoded_data)
11
11
  csr_string = openssl_compat_csr(reencoded_data)
12
12
 
13
13
  new(order, csr_string)
14
+ rescue ArgumentError, OpenSSL::X509::RequestError
15
+ # A payload that is not valid base64url or does not parse as a
16
+ # PKCS#10 request is an unacceptable CSR, not a server fault.
17
+ raise Bullion::Acme::Errors::BadCsr, "Unable to parse CSR from the request payload"
14
18
  end
15
19
 
16
20
  private
@@ -13,6 +13,10 @@ module Bullion
13
13
  set :logger, Bullion::LOGGER
14
14
  set :database, Bullion.config.db_url
15
15
  set :show_exceptions, false
16
+ # This service logs unhandled exceptions itself. Sinatra's dump_errors!
17
+ # renders the raw exception message and can raise on invalid bytes before
18
+ # our handler runs, so keep it off in every environment.
19
+ set :dump_errors, false
16
20
  end
17
21
 
18
22
  before do
@@ -22,16 +26,73 @@ module Bullion
22
26
  @json_body = JSON.parse(request.body.read, symbolize_names: true)
23
27
  end
24
28
  rescue StandardError => e
25
- halt(400, { error: "Request must be JSON: #{e.message}}" }.to_json)
29
+ write_service_log(
30
+ "WARN",
31
+ "Rejected malformed request body: #{e.class}: #{safe_exception_message(e)}"
32
+ )
33
+ content_type "application/problem+json"
34
+ halt(400, {
35
+ type: "urn:ietf:params:acme:error:malformed",
36
+ detail: "Request body must be JSON"
37
+ }.to_json)
26
38
  end
27
39
 
28
40
  error do
29
- content_type :json
30
-
31
41
  e = env["sinatra.error"]
32
- resp = { result: "error", message: e.message }
33
- resp[:trace] = e.full_message if settings.environment.to_s != "production"
34
- resp.to_json
42
+ log_unhandled_exception(e)
43
+
44
+ status 500
45
+ content_type "application/problem+json"
46
+ {
47
+ type: "urn:ietf:params:acme:error:serverInternal",
48
+ detail: "Internal server error"
49
+ }.to_json
50
+ end
51
+
52
+ private
53
+
54
+ # Writes the full exception detail (message, backtrace, and causes) to the
55
+ # server log. The text is force-encoded and scrubbed so an exception whose
56
+ # message contains invalid bytes cannot make the logger raise (which would
57
+ # turn the sanitized 500 into an empty response and lose the detail).
58
+ def log_unhandled_exception(exception)
59
+ detail = begin
60
+ exception.full_message(highlight: false)
61
+ rescue StandardError
62
+ "#{exception.class}: #{safe_exception_message(exception)}\n" \
63
+ "#{Array(exception.backtrace).join("\n")}"
64
+ end
65
+
66
+ write_exception_log(
67
+ "Unhandled exception while handling #{request.request_method} #{request.path}:\n#{detail}"
68
+ )
69
+ end
70
+
71
+ # Returns a valid UTF-8 exception message. Interpolating a binary message
72
+ # with invalid bytes into a UTF-8 string can itself raise, so normalize it
73
+ # before it reaches any string concatenation.
74
+ def safe_exception_message(exception)
75
+ exception.message.to_s.dup.force_encoding(Encoding::UTF_8).scrub("?")
76
+ end
77
+
78
+ def write_exception_log(text)
79
+ write_service_log("ERROR", text)
80
+ end
81
+
82
+ # Prefer Rack's error stream: Puma wires it to its own log pipeline, while
83
+ # a Logger captured at boot can point at a worker's closed/inherited stream.
84
+ def write_service_log(level, text)
85
+ message = text.dup.force_encoding(Encoding::UTF_8).scrub("?")
86
+ errors = env["rack.errors"]
87
+
88
+ if errors.respond_to?(:puts)
89
+ errors.puts("#{level} bullion: #{message}")
90
+ else
91
+ settings.logger.public_send(level.to_s.downcase.to_sym, message)
92
+ end
93
+ rescue StandardError
94
+ # A logging failure must never replace the sanitized client response.
95
+ nil
35
96
  end
36
97
  end
37
98
  end
@@ -9,8 +9,7 @@ module Bullion
9
9
  helpers Helpers::Ssl
10
10
 
11
11
  before do
12
- Models::Nonce.clean_up! if rand(5) > 2 # randomly clean up
13
- @new_nonce = Models::Nonce.create.token
12
+ @new_nonce = Models::Nonce.mint!
14
13
  end
15
14
 
16
15
  after do
@@ -133,7 +132,7 @@ module Bullion
133
132
  if @payload_data["onlyReturnExisting"]
134
133
  content_type "application/problem+json"
135
134
  unless user
136
- raise Bullion::Acme::Error::AccountDoesNotExist,
135
+ raise Bullion::Acme::Errors::AccountDoesNotExist,
137
136
  "onlyReturnExisting requested and account does not exist"
138
137
  end
139
138
  end
@@ -161,11 +160,10 @@ module Bullion
161
160
  post "/accounts/:id" do
162
161
  parse_acme_jwt
163
162
 
164
- unless params[:id] == @user.id
165
- content_type "application/json"
163
+ unless params[:id].to_i == @user.id
166
164
  add_acme_headers @new_nonce
167
-
168
- halt 403, { error: "Accounts can only view or update themselves" }.to_json
165
+ halt_acme_error(403, Bullion::Acme::Errors::Unauthorized,
166
+ "Accounts can only view or update themselves")
169
167
  end
170
168
 
171
169
  content_type "application/json"
@@ -180,11 +178,10 @@ module Bullion
180
178
  post "/accounts/:id/orders" do
181
179
  parse_acme_jwt
182
180
 
183
- unless params[:id] == @user.id
184
- content_type "application/json"
181
+ unless params[:id].to_i == @user.id
185
182
  add_acme_headers @new_nonce
186
-
187
- halt 403, { error: "Accounts can only view or update themselves" }.to_json
183
+ halt_acme_error(403, Bullion::Acme::Errors::Unauthorized,
184
+ "Accounts can only view or update themselves")
188
185
  end
189
186
 
190
187
  content_type "application/json"
@@ -192,7 +189,7 @@ module Bullion
192
189
 
193
190
  {
194
191
  orders: @user.orders.map { uri("/orders/#{it.id}") }
195
- }
192
+ }.to_json
196
193
  end
197
194
 
198
195
  # Endpoint for creating new orders
@@ -200,11 +197,11 @@ module Bullion
200
197
  post "/orders" do
201
198
  parse_acme_jwt
202
199
 
200
+ order_valid?(@payload_data)
201
+
203
202
  # Only identifiers of type "dns" are supported
204
203
  identifiers = @payload_data["identifiers"].select { it["type"] == "dns" }
205
204
 
206
- order_valid?(@payload_data)
207
-
208
205
  order = @user.start_order(
209
206
  identifiers:,
210
207
  not_before: @payload_data["notBefore"],
@@ -224,11 +221,12 @@ module Bullion
224
221
  post "/orders/:id" do
225
222
  parse_acme_jwt
226
223
 
224
+ order = owned_order
225
+ halt_acme_not_found unless order
226
+
227
227
  content_type "application/json"
228
228
  add_acme_headers @new_nonce
229
229
 
230
- order = Models::Order.find(params[:id])
231
-
232
230
  order_data(order).to_json
233
231
  rescue Bullion::Acme::Error => e
234
232
  content_type "application/problem+json"
@@ -240,21 +238,25 @@ module Bullion
240
238
  post "/orders/:id/finalize" do
241
239
  parse_acme_jwt
242
240
 
243
- order = Models::Order.find(params[:id])
241
+ # Ownership is verified before the CSR is parsed or anything is
242
+ # signed: a foreign CSR must never be signed against another
243
+ # account's validated order.
244
+ order = owned_order
245
+ halt_acme_not_found unless order
244
246
 
245
247
  content_type "application/json"
246
248
  add_acme_headers @new_nonce, additional: { "Location" => uri("/orders/#{order.id}") }
247
249
 
248
250
  order_csr = Models::OrderCsr.from_acme_request(order, @payload_data["csr"])
249
251
 
250
- unless order.ready_status?
252
+ unless order.ready_for_issuance?
251
253
  # Finalize is idempotent for orders that have already been finalized
252
254
  halt 200, order_data(order).to_json if %w[processing valid].include?(order.status)
253
255
 
254
256
  content_type "application/problem+json"
255
257
  halt 403, {
256
258
  type: Bullion::Acme::Errors::OrderNotReady.new.acme_error,
257
- detail: "Order is not ready to be finalized"
259
+ detail: finalize_refusal_detail(order)
258
260
  }.to_json
259
261
  end
260
262
 
@@ -283,12 +285,12 @@ module Bullion
283
285
  post "/authorizations/:id" do
284
286
  parse_acme_jwt
285
287
 
288
+ authorization = owned_authorization
289
+ halt_acme_not_found unless authorization
290
+
286
291
  content_type "application/json"
287
292
  add_acme_headers @new_nonce
288
293
 
289
- authorization = Models::Authorization.find(params[:id])
290
- halt 404 unless authorization
291
-
292
294
  data = {
293
295
  status: authorization.status,
294
296
  expires: authorization.expires,
@@ -316,11 +318,14 @@ module Bullion
316
318
  post "/challenges/:id" do
317
319
  parse_acme_jwt
318
320
 
321
+ # Ownership is verified before triggering validation, so only the
322
+ # account that created an order can cause its challenges to run.
323
+ challenge = owned_challenge
324
+ halt_acme_not_found unless challenge
325
+
319
326
  content_type "application/json"
320
327
  add_acme_headers @new_nonce
321
328
 
322
- challenge = Models::Challenge.find(params[:id])
323
-
324
329
  # Oddly enough, cert-manager uses a GET request for retrieving Challenge info
325
330
  challenge.client.attempt unless @json_body && @json_body[:payload] == ""
326
331
 
@@ -336,10 +341,7 @@ module Bullion
336
341
 
337
342
  if challenge.valid_status?
338
343
  data[:validated] = challenge.validated
339
- authorization = challenge.authorization
340
- authorization.update!(status: "valid") unless authorization.valid_status?
341
- order = authorization.order
342
- order.update!(status: "ready") unless order.ready_status?
344
+ advance_validation!(challenge)
343
345
  end
344
346
 
345
347
  add_link_relation("up", uri("/authorizations/#{challenge.authorization.id}"))
@@ -356,7 +358,9 @@ module Bullion
356
358
  parse_acme_jwt
357
359
  add_acme_headers @new_nonce
358
360
 
359
- order = Models::Order.where(certificate_id: params[:id]).first
361
+ # The order is scoped to the authenticated account: a certificate
362
+ # from another account behaves exactly like a missing one.
363
+ order = Models::Order.find_by(certificate_id: params[:id], account_id: @user.id)
360
364
  if order&.valid_status?
361
365
  content_type "application/pem-certificate-chain"
362
366
 
@@ -364,21 +368,31 @@ module Bullion
364
368
 
365
369
  cert.data + Bullion.ca_cert_file
366
370
  else
367
- halt(422, { error: "Order not valid" }.to_json)
371
+ halt_acme_error(422, Bullion::Acme::Errors::OrderNotReady, "Order not valid")
368
372
  end
369
373
  end
370
374
 
371
375
  # Revokes a certificate
372
376
  # @see https://tools.ietf.org/html/rfc8555#section-7.6
373
377
  post "/revokecert" do
374
- parse_acme_jwt
375
- add_acme_headers @new_nonce
376
-
377
378
  # The certificate is base64url-encoded DER
378
- cert_der = Base64.urlsafe_decode64(@payload_data["certificate"])
379
- cert = OpenSSL::X509::Certificate.new(cert_der)
379
+ cert = begin
380
+ OpenSSL::X509::Certificate.new(
381
+ Base64.urlsafe_decode64(extract_payload_data["certificate"].to_s)
382
+ )
383
+ rescue ArgumentError, TypeError, OpenSSL::X509::CertificateError
384
+ raise Bullion::Acme::Errors::Malformed, "The certificate could not be decoded"
385
+ end
386
+
387
+ # RFC 8555 section 7.6: a revocation is accepted from the account
388
+ # that was issued the certificate, from an account holding valid
389
+ # authorizations for every identifier in the certificate, or when
390
+ # signed with the certificate's own private key (a "jwk" request).
391
+ authenticate_revocation!(cert)
380
392
 
381
- # Find the certificate in the database by matching the PEM data
393
+ add_acme_headers @new_nonce
394
+
395
+ # Find the certificate in the database by matching the serial
382
396
  record = Models::Certificate.find_by(serial: cert.serial.to_i)
383
397
 
384
398
  unless record
@@ -389,6 +403,11 @@ module Bullion
389
403
  }.to_json
390
404
  end
391
405
 
406
+ # kid-authenticated accounts still need a claim on the certificate;
407
+ # a jwk-authenticated request has already proven possession of the
408
+ # certificate's private key
409
+ halt_acme_not_found if @header_data["kid"] && !revocation_authorized?(@user, record)
410
+
392
411
  if record.revoked?
393
412
  content_type "application/problem+json"
394
413
  halt 400, {
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Bullion
4
- VERSION = "0.12.0"
4
+ VERSION = "0.12.2"
5
5
  end