module OpenSSL::OCSP

OpenSSL::OCSP 实现在线证书状态协议的请求和响应。

创建和发送 OCSP 请求需要一个主题证书,该证书在 authorityInfoAccess 扩展中包含 OCSP URL,以及该主题证书的颁发者证书。首先,加载颁发者和主题证书。

subject = OpenSSL::X509::Certificate.new subject_pem
issuer  = OpenSSL::X509::Certificate.new issuer_pem

为了创建请求,我们需要为主题证书创建一个证书 ID,以便 CA 知道我们正在查询哪个证书。

digest = OpenSSL::Digest.new('SHA1')
certificate_id =
  OpenSSL::OCSP::CertificateId.new subject, issuer, digest

然后创建一个请求并向其中添加证书 ID。

request = OpenSSL::OCSP::Request.new
request.add_certid certificate_id

向请求中添加 nonce 可以防止重放攻击,但并非所有 CA 都会处理 nonce。

request.add_nonce

为了将请求提交给 CA 进行验证,我们需要从主题证书中提取 OCSP URI

ocsp_uris = subject.ocsp_uris

require 'uri'

ocsp_uri = URI ocsp_uris[0]

为了提交请求,我们将按照 RFC 2560 的规定将请求 POST 到 OCSP URI。请注意,在此示例中,我们只处理 HTTP 请求,不处理任何重定向,因此这不足以满足严肃的使用需求。

require 'net/http'

http_response =
  Net::HTTP.start ocsp_uri.hostname, ocsp_uri.port do |http|
    http.post ocsp_uri.path, request.to_der,
              'content-type' => 'application/ocsp-request'
end

response = OpenSSL::OCSP::Response.new http_response.body
response_basic = response.basic

首先,我们检查响应是否具有有效的签名。没有有效签名,我们就无法信任它。如果在这里遇到失败,您可能缺少系统证书存储,或者缺少中间证书。

store = OpenSSL::X509::Store.new
store.set_default_paths

unless response_basic.verify [], store then
  raise 'response is not signed by a trusted certificate'
end

响应包含状态信息(成功/失败)。我们可以将状态显示为字符串。

puts response.status_string #=> successful

接下来,我们需要知道响应详细信息,以确定响应是否与我们的请求匹配。首先,我们检查 nonce。同样,并非所有 CA 都支持 nonce。有关返回值含义,请参阅 Request#check_nonce

p request.check_nonce basic_response #=> value from -1 to 3

然后从基本响应中提取证书的状态信息。

single_response = basic_response.find_response(certificate_id)

unless single_response
  raise 'basic_response does not have the status for the certificate'
end

然后检查有效性。必须拒绝在未来发布的有效性状态。

unless single_response.check_validity
  raise 'this_update is in the future or next_update time has passed'
end

case single_response.cert_status
when OpenSSL::OCSP::V_CERTSTATUS_GOOD
  puts 'certificate is still valid'
when OpenSSL::OCSP::V_CERTSTATUS_REVOKED
  puts "certificate has been revoked at #{single_response.revocation_time}"
when OpenSSL::OCSP::V_CERTSTATUS_UNKNOWN
  puts 'responder doesn't know about the certificate'
end