使用Ruby中的SSLServer验证客户端证书 [英] Verify client certificate using SSLServer in Ruby

查看:176
本文介绍了使用Ruby中的SSLServer验证客户端证书的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是我用来设置服务器的代码:

Heres the code I'm using to setup the server:

require 'socket'
require 'openssl'

socket = TCPServer.new('127.0.0.1', 4433)

ssl_context = OpenSSL::SSL::SSLContext.new()
ssl_context.cert = OpenSSL::X509::Certificate.new(File.open("ssl/server/server.crt"))
ssl_context.key = OpenSSL::PKey::RSA.new(File.open("ssl/server/server.key"))

ca_cert = OpenSSL::X509::Certificate.new(File.open("ssl/ca/ca.crt"))

ssl_socket = OpenSSL::SSL::SSLServer.new(socket, ssl_context)

Thread.start(ssl_socket.accept) do |s|
    puts "Connected to #{s.peeraddr.last}"

    if s.peer_cert.verify(ca_cert.public_key)
        puts "Certificate verified"
    else
        puts "Certificate invalid"
    end
end

client:

require 'socket'
require 'openssl'

socket = TCPSocket.new('127.0.0.1', 4433)

ssl_context = OpenSSL::SSL::SSLContext.new
ssl_context.cert = OpenSSL::X509::Certificate.new(File.open("ssl/client1/client1.crt"))
ssl_context.key = OpenSSL::PKey::RSA.new(File.open("ssl/client1/client1.key"))

ssl_socket = OpenSSL::SSL::SSLSocket.new(socket, ssl_context)

ca_cert = OpenSSL::X509::Certificate.new(File.open("ssl/ca/ca.crt"))

ssl_socket.connect

if ssl_socket.peer_cert.verify(ca_cert.public_key)
    puts "Certificate checks out"
else
    puts "Certificate not verified"
end

但是,服务器会抛出异常当它试图获得它找不到的peer_cert。有没有办法让SSLServer得到客户端证书?

However, the server throws an exception when it tries to get the peer_cert that it cannot find. Is there a way to get the SSLServer to expect a client certificate?

推荐答案

看看 test_client_auth OpenSSL :: SSL 测试中的/ruby/blob/trunk/test/openssl/utils.rb#L242 =nofollow> start_server

Have a look at test_client_auth and start_server in the tests for OpenSSL::SSL.

从我的头脑中,我在代码中看到的唯一的东西是你忘记明确要求在服务器端的客户端身份验证 - 重要的是设置标志组合

From the top of my head, the only thing I see missing in your code is that you forgot to explicitly require client authentication on the server side - it is important to set the flag combination

flags = OpenSSL::SSL::VERIFY_PEER|OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT
ctx.verify_mode = flags

,以便服务器实际上需要客户端认证,默默地接受未经身份验证的请求。如果您不设置这些,服务器将很快,而不请求客户端身份验证,因此也将没有可用的对等证书。

so that the server will actually require client authentication and not silently accept requests that come unauthenticated. If you don't set these, the server will be happy without requesting client authentication and as a result there will also be no peer certificate available.

这篇关于使用Ruby中的SSLServer验证客户端证书的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆