SSL 上下文方法 - 通用与服务器/客户端

fel*_*pou 5 c ssl openssl network-programming

当您使用函数 SSL_CTX_new 创建 SSL_CTX 时,您需要按照文档传递一个方法作为参数:

https://www.openssl.org/docs/ssl/SSL_CTX_new.html

所有方法都具有三种变体:通用方法、客户端方法和服务器方法。

例如,您有 TLSv1_method、TLSv1_server_method、TLSv1_client_method。

我的问题是:我什么时候应该使用特定的(客户端/服务器)方法?它们有什么用?我总是可以用通用方法进行交换吗?

jww*_*jww 3

我什么时候应该使用特定的(客户端/服务器)方法?它们有什么用?

我不认为选择时有显着差异method。您可以对客户端和服务器使用通用方法。

我相信客户端和服务器方法为稍后在库中使用提供了提示。来自:struct ssl_stssl.h

/* Imagine that here's a boolean member "init" that is
 * switched as soon as SSL_set_{accept/connect}_state
 * is called for the first time, so that "state" and
 * "handshake_func" are properly initialized.  But as
 * handshake_func is == 0 until then, we use this
 * test instead of an "init" member.
 */

int server; /* are we the server side? - mostly used by SSL_clear*/
Run Code Online (Sandbox Code Playgroud)

有趣的是,只有一个通用宏可以处理它们(通用、客户端、服务器)。例如,SSLv23 方法:

$ grep -R IMPLEMENT_ssl23_meth_func *
ssl/s23_clnt.c:IMPLEMENT_ssl23_meth_func(SSLv23_client_method,
ssl/s23_meth.c:IMPLEMENT_ssl23_meth_func(SSLv23_method,
ssl/s23_srvr.c:IMPLEMENT_ssl23_meth_func(SSLv23_server_method,
ssl/ssl_locl.h:#define IMPLEMENT_ssl23_meth_func(func_name, s_accept, s_connect, s_get_meth) \
Run Code Online (Sandbox Code Playgroud)

然后,在ssl/ssl_locl.h

#define IMPLEMENT_ssl23_meth_func(func_name, s_accept, s_connect, s_get_meth) \
const SSL_METHOD *func_name(void)  \
    { \
    static const SSL_METHOD func_name##_data= { \
    TLS1_2_VERSION, \
    tls1_new, \
    tls1_clear, \
    tls1_free, \
    s_accept, \
    s_connect, \
    ssl23_read, \
    ssl23_peek, \
    ssl23_write, \
    ssl_undefined_function, \
    ssl_undefined_function, \
    ssl_ok, \
    ssl3_get_message, \
    ssl3_read_bytes, \
    ssl3_write_bytes, \
    ssl3_dispatch_alert, \
    ssl3_ctrl, \
    ssl3_ctx_ctrl, \
    ssl23_get_cipher_by_char, \
    ssl23_put_cipher_by_char, \
    ssl_undefined_const_function, \
    ssl23_num_ciphers, \
    ssl23_get_cipher, \
    s_get_meth, \
    ssl23_default_timeout, \
    &ssl3_undef_enc_method, \
    ssl_undefined_void_function, \
    ssl3_callback_ctrl, \
    ssl3_ctx_callback_ctrl, \
    }; \
    return &func_name##_data; \
    }
Run Code Online (Sandbox Code Playgroud)

您有 TLSv1_method、TLSv1_server_method、TLSv1_client_method。

通常,您需要类似以下内容来确保“TLS 1.0 及更高版本”,而不是选择特定方法:

const SSL_METHOD* method = SSLv23_method();
SSL_CTX* ctx = SSL_CTX_new(method);

const long flags = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION;
SSL_CTX_set_options(ctx, flags);
Run Code Online (Sandbox Code Playgroud)

库将做正确的事情并选择最高的协议(TLS 1.2、TLS 1.1 等)和最强的密码(放弃一些手)。

RFC 没有指定谁“选择”密码,OpenSSL 默认将其留给客户端。如果您正在运行服务器,那么您可以使用它SSL_OP_CIPHER_SERVER_PREFERENCE来确保服务器选择密码套件而不是采用客户端的第一选择。这很重要,因为有些客户端是脑残的,会选择 RSA 密钥传输、RC4 和 MD5(以及其他弱/受伤/损坏的配置)。

如果您使用SSL_OP_CIPHER_SERVER_PREFERENCE,那么您需要确保已选择适当的密码套件。我希望看到带有HIGH!ADH!RC4!MD5等的密码套件字符串。