非常教程

Ruby 2.4参考手册

OpenSSL

OpenSSL::SSL::SSLSocket

Parent:ObjectIncluded modules:OpenSSL::Buffering, OpenSSL::SSL::SocketForwarder

Attributes

contextR

The SSLContext object used in this connection.

ioR

The underlying IO object.

sync_closeRW

Whether to close the underlying socket as well, when the SSL/TLS connection is shut down. This defaults to false.

to_ioR

The underlying IO object.

Public Class Methods

new(io) → aSSLSocket Show source

new(io, ctx) → aSSLSocket

Creates a new SSL socket from io which must be a real IO object (not an IO-like object that responds to read/write).

If ctx is provided the SSL Sockets initial params will be taken from the context.

The OpenSSL::Buffering module provides additional IO methods.

This method will freeze the SSLContext if one is provided; however, session management is still allowed in the frozen SSLContext.

static VALUE
ossl_ssl_initialize(int argc, VALUE *argv, VALUE self)
{
    VALUE io, v_ctx, verify_cb;
    SSL *ssl;
    SSL_CTX *ctx;

    TypedData_Get_Struct(self, SSL, &ossl_ssl_type, ssl);
    if (ssl)
        ossl_raise(eSSLError, "SSL already initialized");

    if (rb_scan_args(argc, argv, "11", &io, &v_ctx) == 1)
        v_ctx = rb_funcall(cSSLContext, rb_intern("new"), 0);

    GetSSLCTX(v_ctx, ctx);
    rb_ivar_set(self, id_i_context, v_ctx);
    ossl_sslctx_setup(v_ctx);

    if (rb_respond_to(io, rb_intern("nonblock=")))
        rb_funcall(io, rb_intern("nonblock="), 1, Qtrue);
    rb_ivar_set(self, id_i_io, io);

    ssl = SSL_new(ctx);
    if (!ssl)
        ossl_raise(eSSLError, NULL);
    RTYPEDDATA_DATA(self) = ssl;

    SSL_set_ex_data(ssl, ossl_ssl_ex_ptr_idx, (void *)self);
    SSL_set_info_callback(ssl, ssl_info_cb);
    verify_cb = rb_attr_get(v_ctx, id_i_verify_callback);
    SSL_set_ex_data(ssl, ossl_ssl_ex_vcb_idx, (void *)verify_cb);

    rb_call_super(0, NULL);

    return self;
}

Public Instance Methods

accept → self Show source

Waits for a SSL/TLS client to initiate a handshake. The handshake may be started after unencrypted data has been sent over the socket.

static VALUE
ossl_ssl_accept(VALUE self)
{
    ossl_ssl_setup(self);

    return ossl_start_ssl(self, SSL_accept, "SSL_accept", Qfalse);
}

accept_nonblock(options) → self Show source

Initiates the SSL/TLS handshake as a server in non-blocking manner.

# emulates blocking accept
begin
  ssl.accept_nonblock
rescue IO::WaitReadable
  IO.select([s2])
  retry
rescue IO::WaitWritable
  IO.select(nil, [s2])
  retry
end

By specifying a keyword argument exception to false, you can indicate that #accept_nonblock should not raise an IO::WaitReadable or IO::WaitWritable exception, but return the symbol :wait_readable or :wait_writable instead.

static VALUE
ossl_ssl_accept_nonblock(int argc, VALUE *argv, VALUE self)
{
    VALUE opts;

    rb_scan_args(argc, argv, "0:", &opts);
    ossl_ssl_setup(self);

    return ossl_start_ssl(self, SSL_accept, "SSL_accept", opts);
}

alpn_protocol → String | nil Show source

Returns the ALPN protocol string that was finally selected by the server during the handshake.

static VALUE
ossl_ssl_alpn_protocol(VALUE self)
{
    SSL *ssl;
    const unsigned char *out;
    unsigned int outlen;

    GetSSL(self, ssl);

    SSL_get0_alpn_selected(ssl, &out, &outlen);
    if (!outlen)
        return Qnil;
    else
        return rb_str_new((const char *) out, outlen);
}

cert → cert or nil Show source

The X509 certificate for this socket endpoint.

static VALUE
ossl_ssl_get_cert(VALUE self)
{
    SSL *ssl;
    X509 *cert = NULL;

    GetSSL(self, ssl);

    /*
     * Is this OpenSSL bug? Should add a ref?
     * TODO: Ask for.
     */
    cert = SSL_get_certificate(ssl); /* NO DUPs => DON'T FREE. */

    if (!cert) {
        return Qnil;
    }
    return ossl_x509_new(cert);
}

cipher → name, version, bits, alg_bits()

The cipher being used for the current connection

static VALUE
ossl_ssl_get_cipher(VALUE self)
{
    SSL *ssl;
    SSL_CIPHER *cipher;

    GetSSL(self, ssl);

    cipher = (SSL_CIPHER *)SSL_get_current_cipher(ssl);

    return ossl_ssl_cipher_to_ary(cipher);
}

client_ca → x509name, ...()

Returns the list of client CAs. Please note that in contrast to OpenSSL::SSL::SSLContext#client_ca no array of X509::Certificate is returned but X509::Name instances of the CA's subject distinguished name.

In server mode, returns the list set by OpenSSL::SSL::SSLContext#client_ca. In client mode, returns the list of client CAs sent from the server.

static VALUE
ossl_ssl_get_client_ca_list(VALUE self)
{
    SSL *ssl;
    STACK_OF(X509_NAME) *ca;

    GetSSL(self, ssl);

    ca = SSL_get_client_CA_list(ssl);
    return ossl_x509name_sk2ary(ca);
}

connect → self Show source

Initiates an SSL/TLS handshake with a server. The handshake may be started after unencrypted data has been sent over the socket.

static VALUE
ossl_ssl_connect(VALUE self)
{
    ossl_ssl_setup(self);

    return ossl_start_ssl(self, SSL_connect, "SSL_connect", Qfalse);
}

connect_nonblock(options) → self Show source

Initiates the SSL/TLS handshake as a client in non-blocking manner.

# emulates blocking connect
begin
  ssl.connect_nonblock
rescue IO::WaitReadable
  IO.select([s2])
  retry
rescue IO::WaitWritable
  IO.select(nil, [s2])
  retry
end

By specifying a keyword argument exception to false, you can indicate that #connect_nonblock should not raise an IO::WaitReadable or IO::WaitWritable exception, but return the symbol :wait_readable or :wait_writable instead.

static VALUE
ossl_ssl_connect_nonblock(int argc, VALUE *argv, VALUE self)
{
    VALUE opts;
    rb_scan_args(argc, argv, "0:", &opts);

    ossl_ssl_setup(self);

    return ossl_start_ssl(self, SSL_connect, "SSL_connect", opts);
}

hostname = hostname → hostname Show source

Sets the server hostname used for SNI. This needs to be set before #connect.

static VALUE
ossl_ssl_set_hostname(VALUE self, VALUE arg)
{
    SSL *ssl;
    char *hostname = NULL;

    GetSSL(self, ssl);

    if (!NIL_P(arg))
        hostname = StringValueCStr(arg);

    if (!SSL_set_tlsext_host_name(ssl, hostname))
        ossl_raise(eSSLError, NULL);

    /* for SSLSocket#hostname */
    rb_ivar_set(self, id_i_hostname, arg);

    return arg;
}

npn_protocol → String | nil Show source

Returns the protocol string that was finally selected by the client during the handshake.

static VALUE
ossl_ssl_npn_protocol(VALUE self)
{
    SSL *ssl;
    const unsigned char *out;
    unsigned int outlen;

    GetSSL(self, ssl);

    SSL_get0_next_proto_negotiated(ssl, &out, &outlen);
    if (!outlen)
        return Qnil;
    else
        return rb_str_new((const char *) out, outlen);
}

peer_cert → cert or nil Show source

The X509 certificate for this socket's peer.

static VALUE
ossl_ssl_get_peer_cert(VALUE self)
{
    SSL *ssl;
    X509 *cert = NULL;
    VALUE obj;

    GetSSL(self, ssl);

    cert = SSL_get_peer_certificate(ssl); /* Adds a ref => Safe to FREE. */

    if (!cert) {
        return Qnil;
    }
    obj = ossl_x509_new(cert);
    X509_free(cert);

    return obj;
}

peer_cert_chain → cert, ... or nil Show source

The X509 certificate chain for this socket's peer.

static VALUE
ossl_ssl_get_peer_cert_chain(VALUE self)
{
    SSL *ssl;
    STACK_OF(X509) *chain;
    X509 *cert;
    VALUE ary;
    int i, num;

    GetSSL(self, ssl);

    chain = SSL_get_peer_cert_chain(ssl);
    if(!chain) return Qnil;
    num = sk_X509_num(chain);
    ary = rb_ary_new2(num);
    for (i = 0; i < num; i++){
        cert = sk_X509_value(chain, i);
        rb_ary_push(ary, ossl_x509_new(cert));
    }

    return ary;
}

pending → Integer Show source

The number of bytes that are immediately available for reading.

static VALUE
ossl_ssl_pending(VALUE self)
{
    SSL *ssl;

    GetSSL(self, ssl);

    return INT2NUM(SSL_pending(ssl));
}

post_connection_check(hostname) → true Show source

Perform hostname verification following RFC 6125.

This method MUST be called after calling connect to ensure that the hostname of a remote peer has been verified.

# File ext/openssl/lib/openssl/ssl.rb, line 279
def post_connection_check(hostname)
  if peer_cert.nil?
    msg = "Peer verification enabled, but no certificate received."
    if using_anon_cipher?
      msg += " Anonymous cipher suite #{cipher[0]} was negotiated. "                     "Anonymous suites must be disabled to use peer verification."
    end
    raise SSLError, msg
  end

  unless OpenSSL::SSL.verify_certificate_identity(peer_cert, hostname)
    raise SSLError, "hostname \"#{hostname}\" does not match the server certificate"
  end
  return true
end

session → aSession Show source

Returns the SSLSession object currently used, or nil if the session is not established.

# File ext/openssl/lib/openssl/ssl.rb, line 300
def session
  SSL::Session.new(self)
rescue SSL::Session::SessionError
  nil
end

session = session → session Show source

Sets the Session to be used when the connection is established.

static VALUE
ossl_ssl_set_session(VALUE self, VALUE arg1)
{
    SSL *ssl;
    SSL_SESSION *sess;

    GetSSL(self, ssl);
    SafeGetSSLSession(arg1, sess);

    if (SSL_set_session(ssl, sess) != 1)
        ossl_raise(eSSLError, "SSL_set_session");

    return arg1;
}

session_reused? → true | false Show source

Returns true if a reused session was negotiated during the handshake.

static VALUE
ossl_ssl_session_reused(VALUE self)
{
    SSL *ssl;

    GetSSL(self, ssl);

    return SSL_session_reused(ssl) ? Qtrue : Qfalse;
}

ssl_version → String Show source

Returns a String representing the SSL/TLS version that was negotiated for the connection, for example “TLSv1.2”.

static VALUE
ossl_ssl_get_version(VALUE self)
{
    SSL *ssl;

    GetSSL(self, ssl);

    return rb_str_new2(SSL_get_version(ssl));
}

state → string Show source

A description of the current connection state. This is for diagnostic purposes only.

static VALUE
ossl_ssl_get_state(VALUE self)
{
    SSL *ssl;
    VALUE ret;

    GetSSL(self, ssl);

    ret = rb_str_new2(SSL_state_string(ssl));
    if (ruby_verbose) {
        rb_str_cat2(ret, ": ");
        rb_str_cat2(ret, SSL_state_string_long(ssl));
    }
    return ret;
}

sysclose → nil Show source

Sends “close notify” to the peer and tries to shut down the SSL connection gracefully.

If #sync_close is set to true, the underlying IO is also closed.

# File ext/openssl/lib/openssl/ssl.rb, line 266
def sysclose
  return if closed?
  stop
  io.close if sync_close
end

sysread(length) → string Show source

sysread(length, buffer) → buffer

Reads length bytes from the SSL connection. If a pre-allocated buffer is provided the data will be written into it.

static VALUE
ossl_ssl_read(int argc, VALUE *argv, VALUE self)
{
    return ossl_ssl_read_internal(argc, argv, self, 0);
}

syswrite(string) → Integer Show source

Writes string to the SSL connection.

static VALUE
ossl_ssl_write(VALUE self, VALUE str)
{
    return ossl_ssl_write_internal(self, str, Qfalse);
}

tmp_key → PKey or nil Show source

Returns the ephemeral key used in case of forward secrecy cipher.

static VALUE
ossl_ssl_tmp_key(VALUE self)
{
    SSL *ssl;
    EVP_PKEY *key;

    GetSSL(self, ssl);
    if (!SSL_get_server_tmp_key(ssl, &key))
        return Qnil;
    return ossl_pkey_new(key);
}

verify_result → Integer Show source

Returns the result of the peer certificates verification. See verify(1) for error values and descriptions.

If no peer certificate was presented X509_V_OK is returned.

static VALUE
ossl_ssl_get_verify_result(VALUE self)
{
    SSL *ssl;

    GetSSL(self, ssl);

    return INT2NUM(SSL_get_verify_result(ssl));
}

Private Instance Methods

client_cert_cb() Show source

# File ext/openssl/lib/openssl/ssl.rb, line 314
def client_cert_cb
  @context.client_cert_cb
end

session_get_cb() Show source

# File ext/openssl/lib/openssl/ssl.rb, line 330
def session_get_cb
  @context.session_get_cb
end

session_new_cb() Show source

# File ext/openssl/lib/openssl/ssl.rb, line 326
def session_new_cb
  @context.session_new_cb
end

stop → nil Show source

Sends “close notify” to the peer and tries to shut down the SSL connection gracefully.

static VALUE
ossl_ssl_stop(VALUE self)
{
    SSL *ssl;
    int ret;

    GetSSL(self, ssl);
    if (!ssl_started(ssl))
        return Qnil;
    ret = SSL_shutdown(ssl);
    if (ret == 1) /* Have already received close_notify */
        return Qnil;
    if (ret == 0) /* Sent close_notify, but we don't wait for reply */
        return Qnil;

    /*
     * XXX: Something happened. Possibly it failed because the underlying socket
     * is not writable/readable, since it is in non-blocking mode. We should do
     * some proper error handling using SSL_get_error() and maybe retry, but we
     * can't block here. Give up for now.
     */
    ossl_clear_error();
    return Qnil;
}

sysread_nonblock(length) → string Show source

sysread_nonblock(length, buffer) → buffer

sysread_nonblock(length[, buffer , opts) → buffer

A non-blocking version of sysread. Raises an SSLError if reading would block. If “exception: false” is passed, this method returns a symbol of :wait_readable, :wait_writable, or nil, rather than raising an exception.

Reads length bytes from the SSL connection. If a pre-allocated buffer is provided the data will be written into it.

static VALUE
ossl_ssl_read_nonblock(int argc, VALUE *argv, VALUE self)
{
    return ossl_ssl_read_internal(argc, argv, self, 1);
}

syswrite_nonblock(string) → Integer Show source

Writes string to the SSL connection in a non-blocking manner. Raises an SSLError if writing would block.

static VALUE
ossl_ssl_write_nonblock(int argc, VALUE *argv, VALUE self)
{
    VALUE str, opts;

    rb_scan_args(argc, argv, "1:", &str, &opts);

    return ossl_ssl_write_internal(self, str, opts);
}

tmp_dh_callback() Show source

# File ext/openssl/lib/openssl/ssl.rb, line 318
def tmp_dh_callback
  @context.tmp_dh_callback || OpenSSL::PKey::DEFAULT_TMP_DH_CALLBACK
end

tmp_ecdh_callback() Show source

# File ext/openssl/lib/openssl/ssl.rb, line 322
def tmp_ecdh_callback
  @context.tmp_ecdh_callback
end

using_anon_cipher?() Show source

# File ext/openssl/lib/openssl/ssl.rb, line 308
def using_anon_cipher?
  ctx = OpenSSL::SSL::SSLContext.new
  ctx.ciphers = "aNULL"
  ctx.ciphers.include?(cipher)
end
 Ruby Core © 1993–2017 Yukihiro Matsumoto

Licensed under the Ruby License.

Ruby Standard Library © contributors

Licensed under their own licenses.

OpenSSL相关

1.OpenSSL::ASN1
2.OpenSSL::ASN1::ASN1Data
3.OpenSSL::ASN1::ASN1Error
4.OpenSSL::ASN1::Constructive
5.OpenSSL::ASN1::ObjectId
6.OpenSSL::ASN1::Primitive
7.OpenSSL::BN
8.OpenSSL::BNError
9.OpenSSL::Buffering
10.OpenSSL::Cipher
11.OpenSSL::Cipher::Cipher
12.OpenSSL::Config
13.OpenSSL::ConfigError
14.OpenSSL::Digest
15.OpenSSL::Digest::DigestError
16.OpenSSL::Engine
17.OpenSSL::Engine::EngineError
18.OpenSSL::ExtConfig
19.OpenSSL::HMAC
20.OpenSSL::HMACError
21.OpenSSL::Netscape
22.OpenSSL::Netscape::SPKI
23.OpenSSL::Netscape::SPKIError
24.OpenSSL::OCSP
25.OpenSSL::OCSP::BasicResponse
26.OpenSSL::OCSP::CertificateId
27.OpenSSL::OCSP::OCSPError
28.OpenSSL::OCSP::Request
29.OpenSSL::OCSP::Response
30.OpenSSL::OCSP::SingleResponse
31.OpenSSL::OpenSSLError
32.OpenSSL::PKCS12
33.OpenSSL::PKCS5
34.OpenSSL::PKCS5::PKCS5Error
35.OpenSSL::PKCS7
36.OpenSSL::PKCS7::RecipientInfo
37.OpenSSL::PKCS7::SignerInfo
38.OpenSSL::PKey
39.OpenSSL::PKey::DH
40.OpenSSL::PKey::DHError
41.OpenSSL::PKey::DSA
42.OpenSSL::PKey::DSAError
43.OpenSSL::PKey::EC
44.OpenSSL::PKey::EC::Group
45.OpenSSL::PKey::EC::Point
46.OpenSSL::PKey::PKey
47.OpenSSL::PKey::PKeyError
48.OpenSSL::PKey::RSA
49.OpenSSL::PKey::RSAError
50.OpenSSL::Random
51.OpenSSL::SSL
52.OpenSSL::SSL::Session
53.OpenSSL::SSL::SocketForwarder
54.OpenSSL::SSL::SSLContext
55.OpenSSL::SSL::SSLError
56.OpenSSL::SSL::SSLServer
57.OpenSSL::X509::Attribute
58.OpenSSL::X509::Certificate
59.OpenSSL::X509::CRL
60.OpenSSL::X509::Extension
61.OpenSSL::X509::ExtensionFactory
62.OpenSSL::X509::Name
63.OpenSSL::X509::Name::RFC2253DN
64.OpenSSL::X509::Request
65.OpenSSL::X509::Revoked
66.OpenSSL::X509::Store
67.OpenSSL::X509::StoreContext
Ruby 2.4

Ruby 是一种面向对象、命令式、函数式、动态的通用编程语言,是世界上最优美而巧妙的语言。

主页 https://www.ruby-lang.org/
源码 https://github.com/ruby/ruby
版本 2.4
发布版本 2.4.1

Ruby 2.4目录

1.缩略 | Abbrev
2.ARGF
3.数组 | Array
4.Base64
5.基本对象 | BasicObject
6.基准测试 | Benchmark
7.BigDecimal
8.绑定 | Binding
9.CGI
10.类 | Class
11.比较 | Comparable
12.负责 | Complex
13.计算续体 | Continuation
14.覆盖 | Coverage
15.CSV
16.日期 | Date
17.日期时间 | DateTime
18.DBM
19.代理 | Delegator
20.摘要 | Digest
21.Dir
22.DRb
23.编码 | Encoding
24.枚举 | Enumerable
25.枚举 | Enumerator
26.ENV
27.ERB
28.错误 | Errors
29.Etc
30.期望值 | Exception
31.错误类 | FalseClass
32.Fiber
33.Fiddle
34.文件 | File
35.文件实用程序 | FileUtils
36.查找 | Find
37.浮点 | Float
38.Forwardable
39.GC
40.GDBM
41.GetoptLong
42.Hash
43.Integer
44.IO
45.IPAddr
46.JSON
47.Kernel
48.语言 | 3Language
49.记录 | Logger
50.编排 | Marshal
51.MatchData
52.数学 | Math
53.矩阵 | Matrix
54.方法 | Method
55.模型 | Module
56.监控 | Monitor
57. 互斥 | Mutex
58.Net
59.Net::FTP
60.Net::HTTP
61.Net::IMAP
62.Net::SMTP
63.NilClass
64.数字 | Numeric
65.对象 | Object
66.ObjectSpace
67.Observable
68.Open3
69.OpenSSL
70.OpenStruct
71.OpenURI
72.OptionParser
73.路径名 | Pathname
74.完整输出 | PrettyPrint
75.Prime
76.Proc
77.过程 | Process
78.PStore
79.PTY
80.队列 | Queue
81.随机 | Random
82.范围 | Range
83.合理的 | Rational
84.Readline
85.Regexp
86.Resolv
87.Ripper
88.RubyVM
89.Scanf
90.SDBM
91.SecureRandom
92.Set
93.Shell
94.信号 | Signal
95.Singleton
96.套接字 | Socket
97.字符串 | String
98.StringIO
99.StringScanner
100.结构 | Struct