Class: HTTPClient::SSLConfig

Inherits:
Object
  • Object
show all
Includes:
OpenSSL
Defined in:
lib/httpclient/ssl_config.rb

Overview

Represents SSL configuration for HTTPClient instance. The implementation depends on OpenSSL.

Trust Anchor Control

SSLConfig loads ‘httpclient/cacert.p7s’ as a trust anchor (trusted certificate(s)) with add_trust_ca in initialization time. This means that HTTPClient instance trusts some CA certificates by default, like Web browsers. ‘httpclient/cacert.p7s’ is created by the author and included in released package.

‘cacert.p7s’ is automatically generated from JDK 1.6. Regardless its filename extension (p7s), HTTPClient doesn’t verify the signature in it.

You may want to change trust anchor by yourself. Call clear_cert_store then add_trust_ca for that purpose.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client) ⇒ SSLConfig

Creates a SSLConfig.



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/httpclient/ssl_config.rb', line 78

def initialize(client)
  return unless SSLEnabled
  @client = client
  @cert_store = X509::Store.new
  @client_cert = @client_key = @client_ca = nil
  @verify_mode = SSL::VERIFY_PEER | SSL::VERIFY_FAIL_IF_NO_PEER_CERT
  @verify_depth = nil
  @verify_callback = nil
  @dest = nil
  @timeout = nil
  @ssl_version = nil
  @options = defined?(SSL::OP_ALL) ? SSL::OP_ALL | SSL::OP_NO_SSLv2 : nil
  # OpenSSL 0.9.8 default: "ALL:!ADH:!LOW:!EXP:!MD5:+SSLv2:@STRENGTH"
  @ciphers = "ALL:!aNULL:!eNULL:!SSLv2" # OpenSSL >1.0.0 default
  @cacerts_loaded = false
end

Instance Attribute Details

#cert_storeObject

OpenSSL::X509::X509::Store used for verification. You can reset the store with clear_cert_store and set the new store with cert_store=.



72
73
74
# File 'lib/httpclient/ssl_config.rb', line 72

def cert_store
  @cert_store
end

#ciphersObject

A String of OpenSSL’s cipher configuration. Default value is ALL:!ADH:!LOW:!EXP:!MD5:+SSLv2:@STRENGTH See ciphers(1) man in OpenSSL for more detail.



68
69
70
# File 'lib/httpclient/ssl_config.rb', line 68

def ciphers
  @ciphers
end

#client_caObject

For server side configuration. Ignore this.



75
76
77
# File 'lib/httpclient/ssl_config.rb', line 75

def client_ca
  @client_ca
end

#client_certObject

OpenSSL::X509::Certificate

certificate for SSL client authenticateion.

nil by default. (no client authenticateion)



43
44
45
# File 'lib/httpclient/ssl_config.rb', line 43

def client_cert
  @client_cert
end

#client_keyObject

OpenSSL::PKey::PKey

private key for SSL client authentication.

nil by default. (no client authenticateion)



46
47
48
# File 'lib/httpclient/ssl_config.rb', line 46

def client_key
  @client_key
end

#optionsObject

A number of OpenSSL’s SSL options. Default value is OpenSSL::SSL::OP_ALL | OpenSSL::SSL::OP_NO_SSLv2



64
65
66
# File 'lib/httpclient/ssl_config.rb', line 64

def options
  @options
end

#ssl_versionObject

String name of OpenSSL’s SSL version method name: TLSv1_2, TLSv1_1, TLSv1, SSLv2, SSLv23, SSLv3 or nil to allow version negotiation (default). See OpenSSL::SSL::SSLContext::METHODS.



40
41
42
# File 'lib/httpclient/ssl_config.rb', line 40

def ssl_version
  @ssl_version
end

#timeoutObject

SSL timeout in sec. nil by default.



61
62
63
# File 'lib/httpclient/ssl_config.rb', line 61

def timeout
  @timeout
end

#verify_callbackObject

A callback handler for custom certificate verification. nil by default. If the handler is set, handler.call is invoked just after general OpenSSL’s verification. handler.call is invoked with 2 arguments, ok and ctx; ok is a result of general OpenSSL’s verification. ctx is a OpenSSL::X509::StoreContext.



59
60
61
# File 'lib/httpclient/ssl_config.rb', line 59

def verify_callback
  @verify_callback
end

#verify_depthObject

A number of verify depth. Certification path which length is longer than this depth is not allowed.



53
54
55
# File 'lib/httpclient/ssl_config.rb', line 53

def verify_depth
  @verify_depth
end

#verify_modeObject

A number which represents OpenSSL’s verify mode. Default value is OpenSSL::SSL::VERIFY_PEER | OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT.



50
51
52
# File 'lib/httpclient/ssl_config.rb', line 50

def verify_mode
  @verify_mode
end

Instance Method Details

#add_crl(crl) ⇒ Object Also known as: set_crl

Adds CRL for verification.

crl

a OpenSSL::X509::CRL or a filename of a PEM/DER formatted OpenSSL::X509::CRL.

Calling this method resets all existing sessions.



206
207
208
209
210
211
212
213
# File 'lib/httpclient/ssl_config.rb', line 206

def add_crl(crl)
  unless crl.is_a?(X509::CRL)
    crl = X509::CRL.new(File.open(crl) { |f| f.read })
  end
  @cert_store.add_crl(crl)
  @cert_store.flags = X509::V_FLAG_CRL_CHECK | X509::V_FLAG_CRL_CHECK_ALL
  change_notify
end

#add_trust_ca(trust_ca_file_or_hashed_dir) ⇒ Object Also known as: set_trust_ca

Sets trust anchor certificate(s) for verification.

trust_ca_file_or_hashed_dir

a filename of a PEM/DER formatted OpenSSL::X509::Certificate or a ‘c-rehash’eddirectory name which stores trusted certificate files.

Calling this method resets all existing sessions.



179
180
181
182
183
# File 'lib/httpclient/ssl_config.rb', line 179

def add_trust_ca(trust_ca_file_or_hashed_dir)
  @cacerts_loaded = true # avoid lazy override
  add_trust_ca_to_store(@cert_store, trust_ca_file_or_hashed_dir)
  change_notify
end

#add_trust_ca_to_store(cert_store, trust_ca_file_or_hashed_dir) ⇒ Object



186
187
188
189
190
191
192
# File 'lib/httpclient/ssl_config.rb', line 186

def add_trust_ca_to_store(cert_store, trust_ca_file_or_hashed_dir)
  if FileTest.directory?(trust_ca_file_or_hashed_dir)
    cert_store.add_path(trust_ca_file_or_hashed_dir)
  else
    cert_store.add_file(trust_ca_file_or_hashed_dir)
  end
end

#clear_cert_storeObject

Drops current certificate store (OpenSSL::X509::Store) for SSL and create new one for the next session.

Calling this method resets all existing sessions.



156
157
158
159
160
# File 'lib/httpclient/ssl_config.rb', line 156

def clear_cert_store
  @cacerts_loaded = true # avoid lazy override
  @cert_store = X509::Store.new
  change_notify
end

#default_verify_callback(is_ok, ctx) ⇒ Object

Default callback for verification: only dumps error.



321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# File 'lib/httpclient/ssl_config.rb', line 321

def default_verify_callback(is_ok, ctx)
  if $DEBUG
    if is_ok
      warn("ok: #{ctx.current_cert.subject.to_s.dump}")
    else
      warn("ng: #{ctx.current_cert.subject.to_s.dump} at depth #{ctx.error_depth} - #{ctx.error}: #{ctx.error_string} in #{ctx.chain.inspect}")
    end
    warn(ctx.current_cert.to_text)
    warn(ctx.current_cert.to_pem)
  end
  if !is_ok
    depth = ctx.error_depth
    code = ctx.error
    msg = ctx.error_string
    warn("at depth #{depth} - #{code}: #{msg}")
  end
  is_ok
end

#load_trust_caObject

Loads default trust anchors. Calling this method resets all existing sessions.



196
197
198
199
# File 'lib/httpclient/ssl_config.rb', line 196

def load_trust_ca
  load_cacerts(@cert_store)
  change_notify
end

#post_connection_check(peer_cert, hostname) ⇒ Object

post connection check proc for ruby < 1.8.5. this definition must match with the one in ext/openssl/lib/openssl/ssl.rb

Raises:

  • (SSL::SSLError)


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
# File 'lib/httpclient/ssl_config.rb', line 293

def post_connection_check(peer_cert, hostname) # :nodoc:
  check_common_name = true
  cert = peer_cert
  cert.extensions.each{|ext|
    next if ext.oid != "subjectAltName"
    ext.value.split(/,\s+/).each{|general_name|
      if /\ADNS:(.*)/ =~ general_name
        check_common_name = false
        reg = Regexp.escape($1).gsub(/\\\*/, "[^.]+")
        return true if /\A#{reg}\z/i =~ hostname
      elsif /\AIP Address:(.*)/ =~ general_name
        check_common_name = false
        return true if $1 == hostname
      end
    }
  }
  if check_common_name
    cert.subject.to_a.each{|oid, value|
      if oid == "CN"
        reg = Regexp.escape(value).gsub(/\\\*/, "[^.]+")
        return true if /\A#{reg}\z/i =~ hostname
      end
    }
  end
  raise SSL::SSLError, "hostname was not match with the server certificate"
end

#sample_verify_callback(is_ok, ctx) ⇒ Object

Sample callback method: CAUTION: does not check CRL/ARL.



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
# File 'lib/httpclient/ssl_config.rb', line 341

def sample_verify_callback(is_ok, ctx)
  unless is_ok
    depth = ctx.error_depth
    code = ctx.error
    msg = ctx.error_string
    warn("at depth #{depth} - #{code}: #{msg}") if $DEBUG
    return false
  end

  cert = ctx.current_cert
  self_signed = false
  ca = false
  pathlen = nil
  server_auth = true
  self_signed = (cert.subject.cmp(cert.issuer) == 0)

  # Check extensions whatever its criticality is. (sample)
  cert.extensions.each do |ex|
    case ex.oid
    when 'basicConstraints'
      /CA:(TRUE|FALSE), pathlen:(\d+)/ =~ ex.value
      ca = ($1 == 'TRUE')
      pathlen = $2.to_i
    when 'keyUsage'
      usage = ex.value.split(/\s*,\s*/)
      ca = usage.include?('Certificate Sign')
      server_auth = usage.include?('Key Encipherment')
    when 'extendedKeyUsage'
      usage = ex.value.split(/\s*,\s*/)
      server_auth = usage.include?('Netscape Server Gated Crypto')
    when 'nsCertType'
      usage = ex.value.split(/\s*,\s*/)
      ca = usage.include?('SSL CA')
      server_auth = usage.include?('SSL Server')
    end
  end

  if self_signed
    warn('self signing CA') if $DEBUG
    return true
  elsif ca
    warn('middle level CA') if $DEBUG
    return true
  elsif server_auth
    warn('for server authentication') if $DEBUG
    return true
  end

  return false
end

#set_client_cert_file(cert_file, key_file) ⇒ Object

Sets certificate and private key for SSL client authentication.

cert_file

must be a filename of PEM/DER formatted file.

key_file

must be a filename of PEM/DER formatted file. Key must be an RSA key. If you want to use other PKey algorithm, use client_key=.

Calling this method resets all existing sessions.



128
129
130
131
132
# File 'lib/httpclient/ssl_config.rb', line 128

def set_client_cert_file(cert_file, key_file)
  @client_cert = X509::Certificate.new(File.open(cert_file) { |f| f.read })
  @client_key = PKey::RSA.new(File.open(key_file) { |f| f.read })
  change_notify
end

#set_context(ctx) ⇒ Object

interfaces for SSLSocketWrap.



273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/httpclient/ssl_config.rb', line 273

def set_context(ctx) # :nodoc:
  load_trust_ca unless @cacerts_loaded
  @cacerts_loaded = true
  # Verification: Use Store#verify_callback instead of SSLContext#verify*?
  ctx.cert_store = @cert_store
  ctx.verify_mode = @verify_mode
  ctx.verify_depth = @verify_depth if @verify_depth
  ctx.verify_callback = @verify_callback || method(:default_verify_callback)
  # SSL config
  ctx.cert = @client_cert
  ctx.key = @client_key
  ctx.client_ca = @client_ca
  ctx.timeout = @timeout
  ctx.options = @options
  ctx.ciphers = @ciphers
  ctx.ssl_version = @ssl_version if @ssl_version
end

#set_default_pathsObject

Sets OpenSSL’s default trusted CA certificates. Generally, OpenSSL is configured to use OS’s trusted CA certificates located at /etc/pki/certs or /etc/ssl/certs. Unfortunately OpenSSL’s Windows build does not work with Windows Certificate Storage.

On Windows or when you build OpenSSL manually, you can set the CA certificates directory by SSL_CERT_DIR env variable at runtime.

SSL_CERT_DIR=/etc/ssl/certs ruby -rhttpclient -e "..."

Calling this method resets all existing sessions.



145
146
147
148
149
150
# File 'lib/httpclient/ssl_config.rb', line 145

def set_default_paths
  @cacerts_loaded = true # avoid lazy override
  @cert_store = X509::Store.new
  @cert_store.set_default_paths
  change_notify
end