httpclient 2.8.3 → 2.10.0

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.
@@ -238,7 +238,7 @@ module HTTP
238
238
  if defined?(Encoding::ASCII_8BIT)
239
239
  def set_body_encoding
240
240
  if type = self.content_type
241
- OpenURI::Meta.init(o = '')
241
+ OpenURI::Meta.init(o = ''.dup)
242
242
  o.meta_add_field('content-type', type)
243
243
  @body_encoding = o.encoding
244
244
  end
@@ -491,7 +491,7 @@ module HTTP
491
491
  # String.
492
492
  #
493
493
  # assert: @size is not nil
494
- def dump(header = '', dev = '')
494
+ def dump(header = '', dev = ''.dup)
495
495
  if @body.is_a?(Parts)
496
496
  dev << header
497
497
  @body.parts.each do |part|
@@ -521,7 +521,7 @@ module HTTP
521
521
  # reason. (header is dumped to dev, too)
522
522
  # If no dev (the second argument) given, this method returns a dumped
523
523
  # String.
524
- def dump_chunked(header = '', dev = '')
524
+ def dump_chunked(header = '', dev = ''.dup)
525
525
  dev << header
526
526
  if @body.is_a?(Parts)
527
527
  @body.parts.each do |part|
@@ -574,7 +574,7 @@ module HTTP
574
574
  end
575
575
 
576
576
  def dump_file(io, dev, sz)
577
- buf = ''
577
+ buf = ''.dup
578
578
  rest = sz
579
579
  while rest > 0
580
580
  n = io.read([rest, @chunk_size].min, buf)
@@ -585,7 +585,7 @@ module HTTP
585
585
  end
586
586
 
587
587
  def dump_chunks(io, dev)
588
- buf = ''
588
+ buf = ''.dup
589
589
  while !io.read(@chunk_size, buf).nil?
590
590
  dev << dump_chunk(buf)
591
591
  end
@@ -618,8 +618,8 @@ module HTTP
618
618
  if Message.file?(part)
619
619
  @as_stream = true
620
620
  @body << part
621
- if part.respond_to?(:lstat)
622
- sz = part.lstat.size
621
+ if part.respond_to?(:stat)
622
+ sz = part.stat.size
623
623
  add_size(part, sz)
624
624
  elsif part.respond_to?(:size)
625
625
  if sz = part.size
@@ -954,7 +954,7 @@ module HTTP
954
954
 
955
955
  # Dumps message (header and body) to given dev.
956
956
  # dev needs to respond to <<.
957
- def dump(dev = '')
957
+ def dump(dev = ''.dup)
958
958
  str = @http_header.dump + CRLF
959
959
  if @http_header.chunked
960
960
  dev = @http_body.dump_chunked(str, dev)
@@ -20,14 +20,18 @@ unless defined?(SSLSocket)
20
20
 
21
21
  BUF_SIZE = 1024 * 16
22
22
 
23
+ def self.normalize_timeout(timeout)
24
+ [Java::JavaLang::Integer::MAX_VALUE, timeout].min
25
+ end
26
+
23
27
  def self.connect(socket, site, opts = {})
24
28
  socket_addr = InetSocketAddress.new(site.host, site.port)
25
29
  if opts[:connect_timeout]
26
- socket.connect(socket_addr, opts[:connect_timeout])
30
+ socket.connect(socket_addr, normalize_timeout(opts[:connect_timeout]))
27
31
  else
28
32
  socket.connect(socket_addr)
29
33
  end
30
- socket.setSoTimeout(opts[:so_timeout]) if opts[:so_timeout]
34
+ socket.setSoTimeout(normalize_timeout(opts[:so_timeout])) if opts[:so_timeout]
31
35
  socket.setKeepAlive(true) if opts[:tcp_keepalive]
32
36
  socket
33
37
  end
@@ -124,6 +128,8 @@ unless defined?(SSLSocket)
124
128
  @bufstr << String.from_java_bytes(@buf, Encoding::BINARY)[0, size]
125
129
  end
126
130
  size
131
+ rescue java.net.SocketTimeoutException => e
132
+ raise HTTPClient::ReceiveTimeoutError.new(e.getMessage)
127
133
  rescue java.io.IOException => e
128
134
  raise OpenSSL::SSL::SSLError.new("#{e.class}: #{e.getMessage}")
129
135
  end
@@ -160,6 +166,10 @@ unless defined?(SSLSocket)
160
166
  @cert.getSubjectDN
161
167
  end
162
168
 
169
+ def public_key
170
+ @cert.getPublicKey
171
+ end
172
+
163
173
  def to_text
164
174
  @cert.toString
165
175
  end
@@ -491,6 +501,8 @@ unless defined?(SSLSocket)
491
501
  ssl_connect(dest.host)
492
502
  rescue java.security.GeneralSecurityException => e
493
503
  raise OpenSSL::SSL::SSLError.new(e.getMessage)
504
+ rescue java.net.SocketTimeoutException => e
505
+ raise HTTPClient::ConnectTimeoutError.new(e.getMessage)
494
506
  rescue java.io.IOException => e
495
507
  raise OpenSSL::SSL::SSLError.new("#{e.class}: #{e.getMessage}")
496
508
  end
@@ -546,13 +558,13 @@ unless defined?(SSLSocket)
546
558
  def create_ssl_socket(socket, dest, config, opts)
547
559
  ctx = create_ssl_context(config)
548
560
  factory = ctx.getSocketFactory
549
- if socket
550
- ssl_socket = factory.createSocket(socket, dest.host, dest.port, true)
551
- else
552
- ssl_socket = factory.createSocket
553
- JavaSocketWrap.connect(ssl_socket, dest, opts)
561
+ unless socket
562
+ # Create a plain socket first to set connection timeouts on,
563
+ # then wrap it in a SSL socket so that SNI gets setup on it.
564
+ socket = javax.net.SocketFactory.getDefault.createSocket
565
+ JavaSocketWrap.connect(socket, dest, opts)
554
566
  end
555
- ssl_socket
567
+ factory.createSocket(socket, dest.host, dest.port, true)
556
568
  end
557
569
 
558
570
  def peer_cert
@@ -564,6 +576,9 @@ unless defined?(SSLSocket)
564
576
  def ssl_connect(hostname)
565
577
  @ssl_socket.startHandshake
566
578
  ssl_session = @ssl_socket.getSession
579
+ if @config.verify? && !@config.verify_callback
580
+ @config.check_peer_certificates(ssl_session.getPeerCertificates)
581
+ end
567
582
  @peer_cert = JavaCertificate.new(ssl_session.getPeerCertificates.first)
568
583
  if $DEBUG
569
584
  warn("Protocol version: #{ssl_session.getProtocol}")
@@ -21,7 +21,7 @@ require 'zlib'
21
21
  require 'httpclient/timeout' # TODO: remove this once we drop 1.8 support
22
22
  require 'httpclient/ssl_config'
23
23
  require 'httpclient/http'
24
- if RUBY_ENGINE == 'jruby'
24
+ if defined? JRUBY_VERSION
25
25
  require 'httpclient/jruby_ssl_socket'
26
26
  else
27
27
  require 'httpclient/ssl_socket'
@@ -950,7 +950,7 @@ class HTTPClient
950
950
  end
951
951
 
952
952
  def empty_bin_str
953
- str = ''
953
+ str = ''.dup
954
954
  str.force_encoding('BINARY') if str.respond_to?(:force_encoding)
955
955
  str
956
956
  end
@@ -32,33 +32,63 @@ class HTTPClient
32
32
  #
33
33
  # HTTPClient.new { self.ssl_config.load_trust_ca }.get("https://...")
34
34
  #
35
+ # Secure operation on JRuby depends on keeping the JVM and its CA certificates
36
+ # up to date.
37
+ #
35
38
  # You may want to change trust anchor by yourself. Call clear_cert_store
36
39
  # then add_trust_ca for that purpose.
40
+ #
41
+ # == TLS certificate restrictions
42
+ #
43
+ # Blocked public keys are identified by their SPKI SHA-256 hashes in
44
+ # BLOCKED_SPKI_SHA256. The list covers eight eMudhra intermediate CA public
45
+ # keys whose corresponding private keys were compromised.
46
+ #
47
+ # With peer verification enabled and no custom verify_callback, HTTPClient
48
+ # rejects a connection before sending an HTTP request if any certificate
49
+ # supplied by the server contains a blocked eMudhra public key. This includes
50
+ # cross-signed certificates and extra certificates that are not used in the
51
+ # verification path, even when another valid path exists.
52
+ #
53
+ # Setting verify_mode to OpenSSL::SSL::VERIFY_NONE or nil disables this check.
54
+ # A custom verify_callback replaces the default verification policy, including
55
+ # the blocked public key check. The callback receives the underlying verifier's
56
+ # result and context. With peer verification enabled, its return value controls
57
+ # certificate verification.
58
+ # The caller is responsible for the custom callback's validation policy.
59
+ # Hostname verification is unchanged.
60
+ #
61
+ # On JRuby, this additional check may not detect blocked intermediates found
62
+ # only in a local trust store or obtained through JVM issuer retrieval (such as
63
+ # AIA when enabled). These paths depend on the JVM's certificate validation.
64
+ # See https://github.com/nahi/httpclient/issues/480 for background.
37
65
  class SSLConfig
38
66
  include HTTPClient::Util
39
67
  if SSLEnabled
40
68
  include OpenSSL
41
69
 
42
- module ::OpenSSL
43
- module X509
44
- class Store
45
- attr_reader :_httpclient_cert_store_items
70
+ if defined? JRUBY_VERSION
71
+ module ::OpenSSL
72
+ module X509
73
+ class Store
74
+ attr_reader :_httpclient_cert_store_items
46
75
 
47
- # TODO: use prepend instead when we drop JRuby + 1.9.x support
48
- wrapped = {}
76
+ # TODO: use prepend instead when we drop JRuby + 1.9.x support
77
+ wrapped = {}
49
78
 
50
- wrapped[:initialize] = instance_method(:initialize)
51
- define_method(:initialize) do |*args|
52
- wrapped[:initialize].bind(self).call(*args)
53
- @_httpclient_cert_store_items = [ENV['SSL_CERT_FILE'] || :default]
54
- end
79
+ wrapped[:initialize] = instance_method(:initialize)
80
+ define_method(:initialize) do |*args|
81
+ wrapped[:initialize].bind(self).call(*args)
82
+ @_httpclient_cert_store_items = [ENV['SSL_CERT_FILE'] || :default]
83
+ end
55
84
 
56
- [:add_cert, :add_file, :add_path].each do |m|
57
- wrapped[m] = instance_method(m)
58
- define_method(m) do |cert|
59
- res = wrapped[m].bind(self).call(cert)
60
- @_httpclient_cert_store_items << cert
61
- res
85
+ [:add_cert, :add_file, :add_path].each do |m|
86
+ wrapped[m] = instance_method(m)
87
+ define_method(m) do |cert|
88
+ res = wrapped[m].bind(self).call(cert)
89
+ @_httpclient_cert_store_items << cert
90
+ res
91
+ end
62
92
  end
63
93
  end
64
94
  end
@@ -87,6 +117,39 @@ class HTTPClient
87
117
 
88
118
  CIPHERS_DEFAULT = "ALL:!aNULL:!eNULL:!SSLv2" # OpenSSL >1.0.0 default
89
119
 
120
+ # Public keys whose SPKI SHA-256 hashes are listed below are considered blocked.
121
+ # The list covers eight eMudhra intermediate CA public keys whose corresponding
122
+ # private keys were compromised. Hashes use DER-encoded SubjectPublicKeyInfo,
123
+ # covering cross-signed variants.
124
+ # Includes six TLS keys and two code-signing keys.
125
+ # CA names are from CCADB's public intermediate certificate inventory:
126
+ # https://ccadb.my.salesforce-sites.com/mozilla/PublicAllIntermediateCertsWithPEMCSV
127
+ # Matches distrustedSPKIHashes in Go's crypto/x509 at:
128
+ # https://github.com/golang/go/blob/7f86f957633ee31a1c17a1eb8452ca7a3d9bc141/src/crypto/x509/verify.go
129
+ # Related Go mitigation: https://go.dev/issue/82345 (CVE-2026-111943).
130
+ BLOCKED_SPKI_SHA256 = [
131
+ # EM OV TLS CA - G3B
132
+ '43bffa19d6ef651451f6841e019931e96f6f2eaeff28ab4b6f1ce4576de2717b',
133
+ # EM DV TLS CA - G3C
134
+ '49dd353dc2b919a3770645117d0e60c16115e7d1bc259eefe734b00ea434fe5f',
135
+ # EM EV TLS CA - G3C
136
+ '5c0660a2b164910d8ff589c18e14552e9e0ec237dcefe2cb736d41a4811f81a0',
137
+ # EM OV TLS CA - G3C
138
+ '63ecefee431d49523bc1136c4e72d0206a477086caf606cd5cf025686c109cf8',
139
+ # EM OV CS CA - G3C
140
+ '92c063d67e8f14db71d288e11266ffdaf69cbf115f7bab14f3bc2f68d25e0e30',
141
+ # EM EV TLS CA - G3B
142
+ 'e0254c7fcdc265e2f0f8a428dabb75ab4ae039b4872d62f5ee57f0877d5a8a41',
143
+ # EM DV TLS CA - G3B
144
+ 'ebed6475c2c2d80fcb199f3fe8dd6e6b3ce60b77eb15d4e42c3dec0c6f5b5105',
145
+ # EM OV CS CA - G3B
146
+ 'ec4ffa1ad0ac88081314b7aaffef6a91f97cd57291bb5ba686c5415f5eb4f6b6',
147
+ ].map(&:freeze).freeze
148
+
149
+ def self.blocked_public_key?(public_key_der)
150
+ BLOCKED_SPKI_SHA256.include?(OpenSSL::Digest::SHA256.hexdigest(public_key_der))
151
+ end
152
+
90
153
  # Which TLS protocol version (also called method) will be used. Defaults
91
154
  # to :auto which means that OpenSSL decides (In my tests this resulted
92
155
  # with always the highest available protocol being used).
@@ -107,6 +170,7 @@ class HTTPClient
107
170
 
108
171
  # A number which represents OpenSSL's verify mode. Default value is
109
172
  # OpenSSL::SSL::VERIFY_PEER | OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT.
173
+ # VERIFY_NONE or nil disables the default blocked public key check.
110
174
  attr_config :verify_mode
111
175
  # A number of verify depth. Certification path which length is longer than
112
176
  # this depth is not allowed.
@@ -117,6 +181,9 @@ class HTTPClient
117
181
  # OpenSSL's verification. handler.call is invoked with 2 arguments,
118
182
  # ok and ctx; ok is a result of general OpenSSL's verification. ctx is a
119
183
  # OpenSSL::X509::StoreContext.
184
+ # Setting a handler replaces the default verification policy, including its
185
+ # blocked public key check. The caller is responsible for the
186
+ # handler's validation policy. Hostname verification is unchanged.
120
187
  attr_config :verify_callback
121
188
  # SSL timeout in sec. nil by default.
122
189
  attr_config :timeout
@@ -138,7 +205,9 @@ class HTTPClient
138
205
  attr_config :client_ca # :nodoc:
139
206
 
140
207
  # These array keeps original files/dirs that was added to @cert_store
141
- def cert_store_items; @cert_store._httpclient_cert_store_items; end
208
+ if defined? JRUBY_VERSION
209
+ def cert_store_items; @cert_store._httpclient_cert_store_items; end
210
+ end
142
211
  attr_reader :cert_store_crl_items
143
212
 
144
213
  # Creates a SSLConfig.
@@ -204,7 +273,9 @@ class HTTPClient
204
273
  def clear_cert_store
205
274
  @cacerts_loaded = true # avoid lazy override
206
275
  @cert_store = X509::Store.new
207
- @cert_store._httpclient_cert_store_items.clear
276
+ if defined? JRUBY_VERSION
277
+ @cert_store._httpclient_cert_store_items.clear
278
+ end
208
279
  change_notify
209
280
  end
210
281
 
@@ -305,6 +376,35 @@ class HTTPClient
305
376
  ctx.ssl_version = @ssl_version unless @ssl_version == :auto
306
377
  end
307
378
 
379
+ # Reject blocked public keys in the given certificate collection.
380
+ # Peer certificates are checked even when unused in the verification path.
381
+ def check_peer_certificates(certificates) # :nodoc:
382
+ certificates = certificates.to_a if certificates.respond_to?(:to_a)
383
+ certificates.each do |certificate|
384
+ public_key = if certificate.respond_to?(:public_key)
385
+ certificate.public_key
386
+ else
387
+ certificate.getPublicKey
388
+ end
389
+ public_key_der = if public_key.respond_to?(:getEncoded)
390
+ String.from_java_bytes(public_key.getEncoded)
391
+ elsif public_key.respond_to?(:public_to_der)
392
+ public_key.public_to_der
393
+ elsif public_key.respond_to?(:to_der)
394
+ public_key.to_der
395
+ else
396
+ # Older ruby-openssl cannot export generic PKey objects.
397
+ fields = OpenSSL::ASN1.decode(certificate.to_der).value[0].value
398
+ # The optional version field shifts SubjectPublicKeyInfo by one.
399
+ spki_index = fields[0].tag_class == :CONTEXT_SPECIFIC ? 6 : 5
400
+ fields[spki_index].to_der
401
+ end
402
+ if self.class.blocked_public_key?(public_key_der)
403
+ raise SSL::SSLError, 'certificate chain contains a blocked eMudhra public key'
404
+ end
405
+ end
406
+ end
407
+
308
408
  # post connection check proc for ruby < 1.8.5.
309
409
  # this definition must match with the one in ext/openssl/lib/openssl/ssl.rb
310
410
  def post_connection_check(peer_cert, hostname) # :nodoc:
@@ -334,8 +434,13 @@ class HTTPClient
334
434
  raise SSL::SSLError, "hostname was not match with the server certificate"
335
435
  end
336
436
 
337
- # Default callback for verification: only dumps error.
437
+ # Default callback: reject blocked public keys and report verification errors.
338
438
  def default_verify_callback(is_ok, ctx)
439
+ begin
440
+ check_peer_certificates(ctx.chain) if verify?
441
+ rescue SSL::SSLError
442
+ return false
443
+ end
339
444
  if $DEBUG
340
445
  if is_ok
341
446
  warn("ok: #{ctx.current_cert.subject.to_s.dump}")
@@ -403,6 +508,9 @@ class HTTPClient
403
508
  return true
404
509
  end
405
510
 
511
+ if pathlen > 2
512
+ warn('pathlen > 2') if $DEBUG
513
+ end
406
514
  return false
407
515
  end
408
516
 
@@ -101,6 +101,9 @@ class HTTPClient
101
101
  @ssl_socket.hostname = hostname
102
102
  end
103
103
  @ssl_socket.connect
104
+ if @config.verify? && !@config.verify_callback
105
+ @config.check_peer_certificates(@ssl_socket.peer_cert_chain)
106
+ end
104
107
  if $DEBUG
105
108
  if @ssl_socket.respond_to?(:ssl_version)
106
109
  warn("Protocol version: #{@ssl_socket.ssl_version}")
@@ -64,7 +64,7 @@ class HTTPClient
64
64
  # Overwrites the original definition just for one line...
65
65
  def authority
66
66
  self.host && @authority ||= (begin
67
- authority = ""
67
+ authority = "".dup
68
68
  if self.userinfo != nil
69
69
  authority << "#{self.userinfo}@"
70
70
  end
@@ -1,3 +1,3 @@
1
1
  class HTTPClient
2
- VERSION = '2.8.3'
2
+ VERSION = '2.10.0'
3
3
  end
data/lib/httpclient.rb CHANGED
@@ -753,6 +753,10 @@ class HTTPClient
753
753
  request(:patch, uri, new_args, &block)
754
754
  end
755
755
 
756
+ # :call-seq:
757
+ # post(uri, {query: query, body: body, header: header, follow_redirect: follow_redirect}) -> HTTP::Message
758
+ # post(uri, body, header, follow_redirect) -> HTTP::Message
759
+ #
756
760
  # Sends POST request to the specified URL. See request for arguments.
757
761
  # You should not depend on :follow_redirect => true for POST method. It
758
762
  # sends the same POST method to the new location which is prohibited in HTTP spec.
@@ -1236,7 +1240,7 @@ private
1236
1240
  conn.push(res)
1237
1241
  return res
1238
1242
  end
1239
- content = block ? nil : ''
1243
+ content = block ? nil : ''.dup
1240
1244
  res = HTTP::Message.new_response(content, req.header)
1241
1245
  @debug_dev << "= Request\n\n" if @debug_dev
1242
1246
  sess = @session_manager.query(req, proxy)
data/lib/jsonclient.rb CHANGED
@@ -2,7 +2,7 @@ require 'httpclient'
2
2
  require 'json'
3
3
 
4
4
  # JSONClient auto-converts Hash <-> JSON in request and response.
5
- # * For POST or PUT request, convert Hash body to JSON String with 'application/json; charset=utf-8' header.
5
+ # * For PATCH, POST or PUT request, convert Hash body to JSON String with 'application/json; charset=utf-8' header.
6
6
  # * For response, convert JSON String to Hash when content-type is '(application|text)/(x-)?json'
7
7
  class JSONClient < HTTPClient
8
8
  CONTENT_TYPE_JSON_REGEX = /(application|text)\/(x-)?json/i
@@ -17,6 +17,10 @@ class JSONClient < HTTPClient
17
17
  @content_type_json_response_regex = CONTENT_TYPE_JSON_REGEX
18
18
  end
19
19
 
20
+ def patch(uri, *args, &block)
21
+ request(:patch, uri, argument_to_hash_for_json(args), &block)
22
+ end
23
+
20
24
  def post(uri, *args, &block)
21
25
  request(:post, uri, argument_to_hash_for_json(args), &block)
22
26
  end
@@ -37,7 +41,7 @@ private
37
41
 
38
42
  def argument_to_hash_for_json(args)
39
43
  hash = argument_to_hash(args, :body, :header, :follow_redirect)
40
- if hash[:body].is_a?(Hash)
44
+ if hash[:body].is_a?(Hash) || hash[:body].is_a?(Array)
41
45
  hash[:header] = json_header(hash[:header])
42
46
  hash[:body] = JSON.generate(hash[:body])
43
47
  end
@@ -47,11 +51,10 @@ private
47
51
  def json_header(header)
48
52
  header ||= {}
49
53
  if header.is_a?(Hash)
50
- header['Content-Type'] = @content_type_json_request
54
+ header.merge('Content-Type' => @content_type_json_request)
51
55
  else
52
- header << ['Content-Type', @content_type_json_request]
56
+ header + [['Content-Type', @content_type_json_request]]
53
57
  end
54
- header
55
58
  end
56
59
 
57
60
  def wrap_json_response(original)
data/sample/auth.rb CHANGED
@@ -7,5 +7,5 @@ c.debug_dev = STDOUT
7
7
  #c.set_proxy_auth("admin", "admin")
8
8
 
9
9
  # for WWW authentication: supports Basic, Digest and Negotiate.
10
- c.set_auth("http://dev.ctor.org/http-access2/", "user", "user")
10
+ c.set_auth("http://dev.ctor.org/http-access2/", "username", "password")
11
11
  p c.get("http://dev.ctor.org/http-access2/login")
@@ -0,0 +1,99 @@
1
+ require "openssl"
2
+
3
+ def build_ca
4
+ root_key = OpenSSL::PKey::RSA.new 2048 # the CA's public/private key
5
+ root_ca = OpenSSL::X509::Certificate.new
6
+ root_ca.version = 2 # cf. RFC 5280 - to make it a "v3" certificate
7
+ root_ca.serial = 1
8
+ root_ca.subject = OpenSSL::X509::Name.parse "C=JP,O=JIN.GR.JP,OU=RRR,CN=CA"
9
+ root_ca.issuer = root_ca.subject # root CA's are "self-signed"
10
+ root_ca.public_key = root_key.public_key
11
+ root_ca.not_before = Time.now
12
+ root_ca.not_after = root_ca.not_before + 10 * 365 * 24 * 60 * 60 # 10 years validity
13
+ ef = OpenSSL::X509::ExtensionFactory.new
14
+ ef.subject_certificate = root_ca
15
+ ef.issuer_certificate = root_ca
16
+ root_ca.add_extension(ef.create_extension("basicConstraints","CA:TRUE",true))
17
+ root_ca.add_extension(ef.create_extension("keyUsage","keyCertSign, cRLSign", true))
18
+ root_ca.add_extension(ef.create_extension("subjectKeyIdentifier","hash",false))
19
+ root_ca.add_extension(ef.create_extension("authorityKeyIdentifier","keyid:always",false))
20
+ root_ca.sign(root_key, OpenSSL::Digest::SHA256.new)
21
+ [root_key, root_ca]
22
+ end
23
+
24
+ root_key, root_ca = build_ca
25
+
26
+ File.write("test/ca.cert", root_ca.to_s)
27
+ File.write("test/ca.key", root_key.to_s)
28
+
29
+ def sub_cert(root_key, root_ca, cn, intermediate: false)
30
+ key = OpenSSL::PKey::RSA.new 2048
31
+ cert = OpenSSL::X509::Certificate.new
32
+ cert.version = 2
33
+ cert.serial = 2
34
+ cert.subject = OpenSSL::X509::Name.parse "C=JP,O=JIN.GR.JP,OU=RRR,CN=#{cn}"
35
+ cert.issuer = root_ca.subject # root CA is the issuer
36
+ cert.public_key = key.public_key
37
+ cert.not_before = Time.now
38
+ cert.not_after = cert.not_before + 9 * 365 * 24 * 60 * 60 # 9 years validity
39
+ ef = OpenSSL::X509::ExtensionFactory.new
40
+ ef.subject_certificate = cert
41
+ ef.issuer_certificate = root_ca
42
+ cert.add_extension(ef.create_extension("subjectKeyIdentifier","hash",false))
43
+ if intermediate
44
+ cert.add_extension(ef.create_extension("keyUsage","keyCertSign, cRLSign", true))
45
+ cert.add_extension(ef.create_extension("basicConstraints","CA:TRUE",true))
46
+ else
47
+ cert.add_extension(ef.create_extension("keyUsage","digitalSignature, keyEncipherment", true))
48
+ cert.add_extension(ef.create_extension("extendedKeyUsage", "serverAuth"))
49
+ end
50
+ cert.sign(root_key, OpenSSL::Digest::SHA256.new)
51
+ [key, cert]
52
+ end
53
+
54
+ sub_key, sub_cert = sub_cert(root_key, root_ca, "SubCA", intermediate: true)
55
+ File.write("test/subca.cert", sub_cert.to_s)
56
+ File.write("test/subca.key", sub_key.to_s)
57
+
58
+ server_key, server_cert = sub_cert(sub_key, sub_cert, "localhost")
59
+ File.write("test/server.cert", server_cert.to_s)
60
+ File.write("test/server.key", server_key.to_s)
61
+
62
+ client_key, client_cert = sub_cert(root_key, root_ca, "localhost")
63
+ File.write("test/client.cert", client_cert.to_s)
64
+ File.write("test/client.key", client_key.to_s)
65
+
66
+ system(
67
+ "openssl", "rsa", "-aes256",
68
+ "-in", "test/client.key",
69
+ "-out", "test/client-pass.key",
70
+ "-passout", "pass:pass4key",
71
+ )
72
+
73
+ File.write("test/ca-chain.pem", root_ca.to_s + sub_cert.to_s)
74
+
75
+ verify_key = OpenSSL::PKey::RSA.new 2048
76
+ File.write("test/fixtures/verify.key", verify_key.to_s)
77
+
78
+ def build_self_signed(key, cn)
79
+ cert = OpenSSL::X509::Certificate.new
80
+ cert.version = 2
81
+ cert.serial = 2
82
+ cert.subject = OpenSSL::X509::Name.parse "C=JP,O=JIN.GR.JP,OU=RRR,CN=#{cn}"
83
+ cert.issuer = cert.subject
84
+ cert.public_key = key.public_key
85
+ cert.not_before = Time.now
86
+ cert.not_after = cert.not_before + 9 * 365 * 24 * 60 * 60 # 9 years validity
87
+ ef = OpenSSL::X509::ExtensionFactory.new
88
+ ef.subject_certificate = cert
89
+ ef.issuer_certificate = cert
90
+ cert.add_extension(ef.create_extension("subjectKeyIdentifier","hash",false))
91
+ cert.add_extension(ef.create_extension("keyUsage","digitalSignature, keyEncipherment", true))
92
+ cert.add_extension(ef.create_extension("extendedKeyUsage", "serverAuth"))
93
+ cert.sign(key, OpenSSL::Digest::SHA256.new)
94
+ cert
95
+ end
96
+
97
+ File.write("test/fixtures/verify.localhost.cert", build_self_signed(verify_key, "localhost").to_s)
98
+ File.write("test/fixtures/verify.foo.cert", build_self_signed(verify_key, "foo").to_s)
99
+ File.write("test/fixtures/verify.alt.cert", build_self_signed(verify_key, "alt").to_s)
data/test/ca-chain.pem CHANGED
@@ -1,44 +1,40 @@
1
1
  -----BEGIN CERTIFICATE-----
2
- MIID0DCCArigAwIBAgIBADANBgkqhkiG9w0BAQUFADA8MQswCQYDVQQGDAJKUDES
2
+ MIIDVjCCAj6gAwIBAgIBATANBgkqhkiG9w0BAQsFADA8MQswCQYDVQQGEwJKUDES
3
3
  MBAGA1UECgwJSklOLkdSLkpQMQwwCgYDVQQLDANSUlIxCzAJBgNVBAMMAkNBM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