Ruby 2.7.6p219 (2022-04-12 revision c9c2245c0a25176072e02db9254f0e0c84c805cd)
ossl_ssl.c
Go to the documentation of this file.
1/*
2 * 'OpenSSL for Ruby' project
3 * Copyright (C) 2000-2002 GOTOU Yuuzou <gotoyuzo@notwork.org>
4 * Copyright (C) 2001-2002 Michal Rokos <m.rokos@sh.cvut.cz>
5 * Copyright (C) 2001-2007 Technorama Ltd. <oss-ruby@technorama.net>
6 * All rights reserved.
7 */
8/*
9 * This program is licensed under the same licence as Ruby.
10 * (See the file 'LICENCE'.)
11 */
12#include "ossl.h"
13
14#define numberof(ary) (int)(sizeof(ary)/sizeof((ary)[0]))
15
16#if !defined(TLS1_3_VERSION) && \
17 defined(LIBRESSL_VERSION_NUMBER) && \
18 LIBRESSL_VERSION_NUMBER >= 0x3020000fL
19# define TLS1_3_VERSION 0x0304
20#endif
21
22#ifdef _WIN32
23# define TO_SOCKET(s) _get_osfhandle(s)
24#else
25# define TO_SOCKET(s) (s)
26#endif
27
28#define GetSSLCTX(obj, ctx) do { \
29 TypedData_Get_Struct((obj), SSL_CTX, &ossl_sslctx_type, (ctx)); \
30} while (0)
31
33static VALUE mSSLExtConfig;
34static VALUE eSSLError;
37
38static VALUE eSSLErrorWaitReadable;
39static VALUE eSSLErrorWaitWritable;
40
41static ID id_call, ID_callback_state, id_tmp_dh_callback, id_tmp_ecdh_callback,
42 id_npn_protocols_encoded, id_each;
43static VALUE sym_exception, sym_wait_readable, sym_wait_writable;
44
45static ID id_i_cert_store, id_i_ca_file, id_i_ca_path, id_i_verify_mode,
46 id_i_verify_depth, id_i_verify_callback, id_i_client_ca,
47 id_i_renegotiation_cb, id_i_cert, id_i_key, id_i_extra_chain_cert,
48 id_i_client_cert_cb, id_i_tmp_ecdh_callback, id_i_timeout,
49 id_i_session_id_context, id_i_session_get_cb, id_i_session_new_cb,
50 id_i_session_remove_cb, id_i_npn_select_cb, id_i_npn_protocols,
51 id_i_alpn_select_cb, id_i_alpn_protocols, id_i_servername_cb,
52 id_i_verify_hostname;
53static ID id_i_io, id_i_context, id_i_hostname;
54
55static int ossl_ssl_ex_vcb_idx;
56static int ossl_ssl_ex_ptr_idx;
57static int ossl_sslctx_ex_ptr_idx;
58#if !defined(HAVE_X509_STORE_UP_REF)
59static int ossl_sslctx_ex_store_p;
60#endif
61
62static void
63ossl_sslctx_mark(void *ptr)
64{
65 SSL_CTX *ctx = ptr;
66 rb_gc_mark((VALUE)SSL_CTX_get_ex_data(ctx, ossl_sslctx_ex_ptr_idx));
67}
68
69static void
70ossl_sslctx_free(void *ptr)
71{
72 SSL_CTX *ctx = ptr;
73#if !defined(HAVE_X509_STORE_UP_REF)
74 if (ctx && SSL_CTX_get_ex_data(ctx, ossl_sslctx_ex_store_p))
75 ctx->cert_store = NULL;
76#endif
77 SSL_CTX_free(ctx);
78}
79
80static const rb_data_type_t ossl_sslctx_type = {
81 "OpenSSL/SSL/CTX",
82 {
83 ossl_sslctx_mark, ossl_sslctx_free,
84 },
86};
87
88static VALUE
89ossl_sslctx_s_alloc(VALUE klass)
90{
91 SSL_CTX *ctx;
92 long mode = 0 |
93 SSL_MODE_ENABLE_PARTIAL_WRITE |
94 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
95 SSL_MODE_RELEASE_BUFFERS;
96 VALUE obj;
97
98 obj = TypedData_Wrap_Struct(klass, &ossl_sslctx_type, 0);
99#if OPENSSL_VERSION_NUMBER >= 0x10100000 && !defined(LIBRESSL_VERSION_NUMBER)
100 ctx = SSL_CTX_new(TLS_method());
101#else
102 ctx = SSL_CTX_new(SSLv23_method());
103#endif
104 if (!ctx) {
105 ossl_raise(eSSLError, "SSL_CTX_new");
106 }
107 SSL_CTX_set_mode(ctx, mode);
108 RTYPEDDATA_DATA(obj) = ctx;
109 SSL_CTX_set_ex_data(ctx, ossl_sslctx_ex_ptr_idx, (void *)obj);
110
111#if !defined(OPENSSL_NO_EC) && defined(HAVE_SSL_CTX_SET_ECDH_AUTO)
112 /* We use SSL_CTX_set1_curves_list() to specify the curve used in ECDH. It
113 * allows to specify multiple curve names and OpenSSL will select
114 * automatically from them. In OpenSSL 1.0.2, the automatic selection has to
115 * be enabled explicitly. But OpenSSL 1.1.0 removed the knob and it is
116 * always enabled. To uniform the behavior, we enable the automatic
117 * selection also in 1.0.2. Users can still disable ECDH by removing ECDH
118 * cipher suites by SSLContext#ciphers=. */
119 if (!SSL_CTX_set_ecdh_auto(ctx, 1))
120 ossl_raise(eSSLError, "SSL_CTX_set_ecdh_auto");
121#endif
122
123 return obj;
124}
125
126static int
127parse_proto_version(VALUE str)
128{
129 int i;
130 static const struct {
131 const char *name;
132 int version;
133 } map[] = {
134 { "SSL2", SSL2_VERSION },
135 { "SSL3", SSL3_VERSION },
136 { "TLS1", TLS1_VERSION },
137 { "TLS1_1", TLS1_1_VERSION },
138 { "TLS1_2", TLS1_2_VERSION },
139#ifdef TLS1_3_VERSION
140 { "TLS1_3", TLS1_3_VERSION },
141#endif
142 };
143
144 if (NIL_P(str))
145 return 0;
147 return NUM2INT(str);
148
149 if (SYMBOL_P(str))
150 str = rb_sym2str(str);
152 for (i = 0; i < numberof(map); i++)
153 if (!strncmp(map[i].name, RSTRING_PTR(str), RSTRING_LEN(str)))
154 return map[i].version;
155 rb_raise(rb_eArgError, "unrecognized version %+"PRIsVALUE, str);
156}
157
158/*
159 * call-seq:
160 * ctx.set_minmax_proto_version(min, max) -> nil
161 *
162 * Sets the minimum and maximum supported protocol versions. See #min_version=
163 * and #max_version=.
164 */
165static VALUE
166ossl_sslctx_set_minmax_proto_version(VALUE self, VALUE min_v, VALUE max_v)
167{
168 SSL_CTX *ctx;
169 int min, max;
170
171 GetSSLCTX(self, ctx);
172 min = parse_proto_version(min_v);
173 max = parse_proto_version(max_v);
174
175#ifdef HAVE_SSL_CTX_SET_MIN_PROTO_VERSION
176 if (!SSL_CTX_set_min_proto_version(ctx, min))
177 ossl_raise(eSSLError, "SSL_CTX_set_min_proto_version");
178 if (!SSL_CTX_set_max_proto_version(ctx, max))
179 ossl_raise(eSSLError, "SSL_CTX_set_max_proto_version");
180#else
181 {
182 unsigned long sum = 0, opts = 0;
183 int i;
184 static const struct {
185 int ver;
186 unsigned long opts;
187 } options_map[] = {
188 { SSL2_VERSION, SSL_OP_NO_SSLv2 },
189 { SSL3_VERSION, SSL_OP_NO_SSLv3 },
190 { TLS1_VERSION, SSL_OP_NO_TLSv1 },
191 { TLS1_1_VERSION, SSL_OP_NO_TLSv1_1 },
192 { TLS1_2_VERSION, SSL_OP_NO_TLSv1_2 },
193# if defined(TLS1_3_VERSION)
194 { TLS1_3_VERSION, SSL_OP_NO_TLSv1_3 },
195# endif
196 };
197
198 for (i = 0; i < numberof(options_map); i++) {
199 sum |= options_map[i].opts;
200 if ((min && min > options_map[i].ver) ||
201 (max && max < options_map[i].ver)) {
202 opts |= options_map[i].opts;
203 }
204 }
205 SSL_CTX_clear_options(ctx, sum);
206 SSL_CTX_set_options(ctx, opts);
207 }
208#endif
209
210 return Qnil;
211}
212
213static VALUE
214ossl_call_client_cert_cb(VALUE obj)
215{
216 VALUE ctx_obj, cb, ary, cert, key;
217
218 ctx_obj = rb_attr_get(obj, id_i_context);
219 cb = rb_attr_get(ctx_obj, id_i_client_cert_cb);
220 if (NIL_P(cb))
221 return Qnil;
222
223 ary = rb_funcallv(cb, id_call, 1, &obj);
224 Check_Type(ary, T_ARRAY);
225 GetX509CertPtr(cert = rb_ary_entry(ary, 0));
227
228 return rb_ary_new3(2, cert, key);
229}
230
231static int
232ossl_client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
233{
234 VALUE obj, ret;
235
236 obj = (VALUE)SSL_get_ex_data(ssl, ossl_ssl_ex_ptr_idx);
237 ret = rb_protect(ossl_call_client_cert_cb, obj, NULL);
238 if (NIL_P(ret))
239 return 0;
240
241 *x509 = DupX509CertPtr(RARRAY_AREF(ret, 0));
242 *pkey = DupPKeyPtr(RARRAY_AREF(ret, 1));
243
244 return 1;
245}
246
247#if !defined(OPENSSL_NO_DH) || \
248 !defined(OPENSSL_NO_EC) && defined(HAVE_SSL_CTX_SET_TMP_ECDH_CALLBACK)
252 int type;
255};
256
257static EVP_PKEY *
258ossl_call_tmp_dh_callback(struct tmp_dh_callback_args *args)
259{
260 VALUE cb, dh;
261 EVP_PKEY *pkey;
262
263 cb = rb_funcall(args->ssl_obj, args->id, 0);
264 if (NIL_P(cb))
265 return NULL;
266 dh = rb_funcall(cb, id_call, 3, args->ssl_obj, INT2NUM(args->is_export),
267 INT2NUM(args->keylength));
268 pkey = GetPKeyPtr(dh);
269 if (EVP_PKEY_base_id(pkey) != args->type)
270 return NULL;
271
272 return pkey;
273}
274#endif
275
276#if !defined(OPENSSL_NO_DH)
277static DH *
278ossl_tmp_dh_callback(SSL *ssl, int is_export, int keylength)
279{
280 VALUE rb_ssl;
281 EVP_PKEY *pkey;
282 struct tmp_dh_callback_args args;
283 int state;
284
285 rb_ssl = (VALUE)SSL_get_ex_data(ssl, ossl_ssl_ex_ptr_idx);
286 args.ssl_obj = rb_ssl;
287 args.id = id_tmp_dh_callback;
288 args.is_export = is_export;
289 args.keylength = keylength;
290 args.type = EVP_PKEY_DH;
291
292 pkey = (EVP_PKEY *)rb_protect((VALUE (*)(VALUE))ossl_call_tmp_dh_callback,
293 (VALUE)&args, &state);
294 if (state) {
295 rb_ivar_set(rb_ssl, ID_callback_state, INT2NUM(state));
296 return NULL;
297 }
298 if (!pkey)
299 return NULL;
300
301 return EVP_PKEY_get0_DH(pkey);
302}
303#endif /* OPENSSL_NO_DH */
304
305#if !defined(OPENSSL_NO_EC) && defined(HAVE_SSL_CTX_SET_TMP_ECDH_CALLBACK)
306static EC_KEY *
307ossl_tmp_ecdh_callback(SSL *ssl, int is_export, int keylength)
308{
309 VALUE rb_ssl;
310 EVP_PKEY *pkey;
311 struct tmp_dh_callback_args args;
312 int state;
313
314 rb_ssl = (VALUE)SSL_get_ex_data(ssl, ossl_ssl_ex_ptr_idx);
315 args.ssl_obj = rb_ssl;
316 args.id = id_tmp_ecdh_callback;
317 args.is_export = is_export;
318 args.keylength = keylength;
319 args.type = EVP_PKEY_EC;
320
321 pkey = (EVP_PKEY *)rb_protect((VALUE (*)(VALUE))ossl_call_tmp_dh_callback,
322 (VALUE)&args, &state);
323 if (state) {
324 rb_ivar_set(rb_ssl, ID_callback_state, INT2NUM(state));
325 return NULL;
326 }
327 if (!pkey)
328 return NULL;
329
330 return EVP_PKEY_get0_EC_KEY(pkey);
331}
332#endif
333
334static VALUE
335call_verify_certificate_identity(VALUE ctx_v)
336{
337 X509_STORE_CTX *ctx = (X509_STORE_CTX *)ctx_v;
338 SSL *ssl;
339 VALUE ssl_obj, hostname, cert_obj;
340
341 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
342 ssl_obj = (VALUE)SSL_get_ex_data(ssl, ossl_ssl_ex_ptr_idx);
343 hostname = rb_attr_get(ssl_obj, id_i_hostname);
344
345 if (!RTEST(hostname)) {
346 rb_warning("verify_hostname requires hostname to be set");
347 return Qtrue;
348 }
349
350 cert_obj = ossl_x509_new(X509_STORE_CTX_get_current_cert(ctx));
351 return rb_funcall(mSSL, rb_intern("verify_certificate_identity"), 2,
352 cert_obj, hostname);
353}
354
355static int
356ossl_ssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
357{
358 VALUE cb, ssl_obj, sslctx_obj, verify_hostname, ret;
359 SSL *ssl;
360 int status;
361
362 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
363 cb = (VALUE)SSL_get_ex_data(ssl, ossl_ssl_ex_vcb_idx);
364 ssl_obj = (VALUE)SSL_get_ex_data(ssl, ossl_ssl_ex_ptr_idx);
365 sslctx_obj = rb_attr_get(ssl_obj, id_i_context);
366 verify_hostname = rb_attr_get(sslctx_obj, id_i_verify_hostname);
367
368 if (preverify_ok && RTEST(verify_hostname) && !SSL_is_server(ssl) &&
369 !X509_STORE_CTX_get_error_depth(ctx)) {
370 ret = rb_protect(call_verify_certificate_identity, (VALUE)ctx, &status);
371 if (status) {
372 rb_ivar_set(ssl_obj, ID_callback_state, INT2NUM(status));
373 return 0;
374 }
375 if (ret != Qtrue) {
376 preverify_ok = 0;
377#if defined(X509_V_ERR_HOSTNAME_MISMATCH)
378 X509_STORE_CTX_set_error(ctx, X509_V_ERR_HOSTNAME_MISMATCH);
379#else
380 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_REJECTED);
381#endif
382 }
383 }
384
385 return ossl_verify_cb_call(cb, preverify_ok, ctx);
386}
387
388static VALUE
389ossl_call_session_get_cb(VALUE ary)
390{
391 VALUE ssl_obj, cb;
392
393 Check_Type(ary, T_ARRAY);
394 ssl_obj = rb_ary_entry(ary, 0);
395
396 cb = rb_funcall(ssl_obj, rb_intern("session_get_cb"), 0);
397 if (NIL_P(cb)) return Qnil;
398
399 return rb_funcallv(cb, id_call, 1, &ary);
400}
401
402static SSL_SESSION *
403#if (!defined(LIBRESSL_VERSION_NUMBER) ? OPENSSL_VERSION_NUMBER >= 0x10100000 : LIBRESSL_VERSION_NUMBER >= 0x2080000f)
404ossl_sslctx_session_get_cb(SSL *ssl, const unsigned char *buf, int len, int *copy)
405#else
406ossl_sslctx_session_get_cb(SSL *ssl, unsigned char *buf, int len, int *copy)
407#endif
408{
409 VALUE ary, ssl_obj, ret_obj;
410 SSL_SESSION *sess;
411 int state = 0;
412
413 OSSL_Debug("SSL SESSION get callback entered");
414 ssl_obj = (VALUE)SSL_get_ex_data(ssl, ossl_ssl_ex_ptr_idx);
415 ary = rb_ary_new2(2);
416 rb_ary_push(ary, ssl_obj);
417 rb_ary_push(ary, rb_str_new((const char *)buf, len));
418
419 ret_obj = rb_protect(ossl_call_session_get_cb, ary, &state);
420 if (state) {
421 rb_ivar_set(ssl_obj, ID_callback_state, INT2NUM(state));
422 return NULL;
423 }
424 if (!rb_obj_is_instance_of(ret_obj, cSSLSession))
425 return NULL;
426
427 GetSSLSession(ret_obj, sess);
428 *copy = 1;
429
430 return sess;
431}
432
433static VALUE
434ossl_call_session_new_cb(VALUE ary)
435{
436 VALUE ssl_obj, cb;
437
438 Check_Type(ary, T_ARRAY);
439 ssl_obj = rb_ary_entry(ary, 0);
440
441 cb = rb_funcall(ssl_obj, rb_intern("session_new_cb"), 0);
442 if (NIL_P(cb)) return Qnil;
443
444 return rb_funcallv(cb, id_call, 1, &ary);
445}
446
447/* return 1 normal. return 0 removes the session */
448static int
449ossl_sslctx_session_new_cb(SSL *ssl, SSL_SESSION *sess)
450{
451 VALUE ary, ssl_obj, sess_obj;
452 int state = 0;
453
454 OSSL_Debug("SSL SESSION new callback entered");
455
456 ssl_obj = (VALUE)SSL_get_ex_data(ssl, ossl_ssl_ex_ptr_idx);
457 sess_obj = rb_obj_alloc(cSSLSession);
458 SSL_SESSION_up_ref(sess);
459 DATA_PTR(sess_obj) = sess;
460
461 ary = rb_ary_new2(2);
462 rb_ary_push(ary, ssl_obj);
463 rb_ary_push(ary, sess_obj);
464
465 rb_protect(ossl_call_session_new_cb, ary, &state);
466 if (state) {
467 rb_ivar_set(ssl_obj, ID_callback_state, INT2NUM(state));
468 }
469
470 /*
471 * return 0 which means to OpenSSL that the session is still
472 * valid (since we created Ruby Session object) and was not freed by us
473 * with SSL_SESSION_free(). Call SSLContext#remove_session(sess) in
474 * session_get_cb block if you don't want OpenSSL to cache the session
475 * internally.
476 */
477 return 0;
478}
479
480static VALUE
481ossl_call_session_remove_cb(VALUE ary)
482{
483 VALUE sslctx_obj, cb;
484
485 Check_Type(ary, T_ARRAY);
486 sslctx_obj = rb_ary_entry(ary, 0);
487
488 cb = rb_attr_get(sslctx_obj, id_i_session_remove_cb);
489 if (NIL_P(cb)) return Qnil;
490
491 return rb_funcallv(cb, id_call, 1, &ary);
492}
493
494static void
495ossl_sslctx_session_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
496{
497 VALUE ary, sslctx_obj, sess_obj;
498 int state = 0;
499
500 /*
501 * This callback is also called for all sessions in the internal store
502 * when SSL_CTX_free() is called.
503 */
504 if (rb_during_gc())
505 return;
506
507 OSSL_Debug("SSL SESSION remove callback entered");
508
509 sslctx_obj = (VALUE)SSL_CTX_get_ex_data(ctx, ossl_sslctx_ex_ptr_idx);
510 sess_obj = rb_obj_alloc(cSSLSession);
511 SSL_SESSION_up_ref(sess);
512 DATA_PTR(sess_obj) = sess;
513
514 ary = rb_ary_new2(2);
515 rb_ary_push(ary, sslctx_obj);
516 rb_ary_push(ary, sess_obj);
517
518 rb_protect(ossl_call_session_remove_cb, ary, &state);
519 if (state) {
520/*
521 the SSL_CTX is frozen, nowhere to save state.
522 there is no common accessor method to check it either.
523 rb_ivar_set(sslctx_obj, ID_callback_state, INT2NUM(state));
524*/
525 }
526}
527
528static VALUE
529ossl_sslctx_add_extra_chain_cert_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, arg))
530{
531 X509 *x509;
532 SSL_CTX *ctx;
533
534 GetSSLCTX(arg, ctx);
535 x509 = DupX509CertPtr(i);
536 if(!SSL_CTX_add_extra_chain_cert(ctx, x509)){
537 ossl_raise(eSSLError, NULL);
538 }
539
540 return i;
541}
542
543static VALUE ossl_sslctx_setup(VALUE self);
544
545static VALUE
546ossl_call_servername_cb(VALUE ary)
547{
548 VALUE ssl_obj, sslctx_obj, cb, ret_obj;
549
550 Check_Type(ary, T_ARRAY);
551 ssl_obj = rb_ary_entry(ary, 0);
552
553 sslctx_obj = rb_attr_get(ssl_obj, id_i_context);
554 cb = rb_attr_get(sslctx_obj, id_i_servername_cb);
555 if (NIL_P(cb)) return Qnil;
556
557 ret_obj = rb_funcallv(cb, id_call, 1, &ary);
558 if (rb_obj_is_kind_of(ret_obj, cSSLContext)) {
559 SSL *ssl;
560 SSL_CTX *ctx2;
561
562 ossl_sslctx_setup(ret_obj);
563 GetSSL(ssl_obj, ssl);
564 GetSSLCTX(ret_obj, ctx2);
565 SSL_set_SSL_CTX(ssl, ctx2);
566 rb_ivar_set(ssl_obj, id_i_context, ret_obj);
567 } else if (!NIL_P(ret_obj)) {
568 ossl_raise(rb_eArgError, "servername_cb must return an "
569 "OpenSSL::SSL::SSLContext object or nil");
570 }
571
572 return ret_obj;
573}
574
575static int
576ssl_servername_cb(SSL *ssl, int *ad, void *arg)
577{
578 VALUE ary, ssl_obj;
579 int state = 0;
580 const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
581
582 if (!servername)
583 return SSL_TLSEXT_ERR_OK;
584
585 ssl_obj = (VALUE)SSL_get_ex_data(ssl, ossl_ssl_ex_ptr_idx);
586 ary = rb_ary_new2(2);
587 rb_ary_push(ary, ssl_obj);
588 rb_ary_push(ary, rb_str_new2(servername));
589
590 rb_protect(ossl_call_servername_cb, ary, &state);
591 if (state) {
592 rb_ivar_set(ssl_obj, ID_callback_state, INT2NUM(state));
593 return SSL_TLSEXT_ERR_ALERT_FATAL;
594 }
595
596 return SSL_TLSEXT_ERR_OK;
597}
598
599static void
600ssl_renegotiation_cb(const SSL *ssl)
601{
602 VALUE ssl_obj, sslctx_obj, cb;
603
604 ssl_obj = (VALUE)SSL_get_ex_data(ssl, ossl_ssl_ex_ptr_idx);
605 sslctx_obj = rb_attr_get(ssl_obj, id_i_context);
606 cb = rb_attr_get(sslctx_obj, id_i_renegotiation_cb);
607 if (NIL_P(cb)) return;
608
609 rb_funcallv(cb, id_call, 1, &ssl_obj);
610}
611
612#if !defined(OPENSSL_NO_NEXTPROTONEG) || \
613 defined(HAVE_SSL_CTX_SET_ALPN_SELECT_CB)
614static VALUE
615ssl_npn_encode_protocol_i(RB_BLOCK_CALL_FUNC_ARGLIST(cur, encoded))
616{
617 int len = RSTRING_LENINT(cur);
618 char len_byte;
619 if (len < 1 || len > 255)
620 ossl_raise(eSSLError, "Advertised protocol must have length 1..255");
621 /* Encode the length byte */
622 len_byte = len;
623 rb_str_buf_cat(encoded, &len_byte, 1);
624 rb_str_buf_cat(encoded, RSTRING_PTR(cur), len);
625 return Qnil;
626}
627
628static VALUE
629ssl_encode_npn_protocols(VALUE protocols)
630{
631 VALUE encoded = rb_str_new(NULL, 0);
632 rb_block_call(protocols, id_each, 0, 0, ssl_npn_encode_protocol_i, encoded);
633 return encoded;
634}
635
638 const unsigned char *in;
639 unsigned inlen;
640};
641
642static VALUE
643npn_select_cb_common_i(VALUE tmp)
644{
645 struct npn_select_cb_common_args *args = (void *)tmp;
646 const unsigned char *in = args->in, *in_end = in + args->inlen;
647 unsigned char l;
648 long len;
649 VALUE selected, protocols = rb_ary_new();
650
651 /* assume OpenSSL verifies this format */
652 /* The format is len_1|proto_1|...|len_n|proto_n */
653 while (in < in_end) {
654 l = *in++;
655 rb_ary_push(protocols, rb_str_new((const char *)in, l));
656 in += l;
657 }
658
659 selected = rb_funcallv(args->cb, id_call, 1, &protocols);
660 StringValue(selected);
661 len = RSTRING_LEN(selected);
662 if (len < 1 || len >= 256) {
663 ossl_raise(eSSLError, "Selected protocol name must have length 1..255");
664 }
665
666 return selected;
667}
668
669static int
670ssl_npn_select_cb_common(SSL *ssl, VALUE cb, const unsigned char **out,
671 unsigned char *outlen, const unsigned char *in,
672 unsigned int inlen)
673{
674 VALUE selected;
675 int status;
676 struct npn_select_cb_common_args args;
677
678 args.cb = cb;
679 args.in = in;
680 args.inlen = inlen;
681
682 selected = rb_protect(npn_select_cb_common_i, (VALUE)&args, &status);
683 if (status) {
684 VALUE ssl_obj = (VALUE)SSL_get_ex_data(ssl, ossl_ssl_ex_ptr_idx);
685
686 rb_ivar_set(ssl_obj, ID_callback_state, INT2NUM(status));
687 return SSL_TLSEXT_ERR_ALERT_FATAL;
688 }
689
690 *out = (unsigned char *)RSTRING_PTR(selected);
691 *outlen = (unsigned char)RSTRING_LEN(selected);
692
693 return SSL_TLSEXT_ERR_OK;
694}
695#endif
696
697#ifndef OPENSSL_NO_NEXTPROTONEG
698static int
699ssl_npn_advertise_cb(SSL *ssl, const unsigned char **out, unsigned int *outlen,
700 void *arg)
701{
702 VALUE protocols = rb_attr_get((VALUE)arg, id_npn_protocols_encoded);
703
704 *out = (const unsigned char *) RSTRING_PTR(protocols);
705 *outlen = RSTRING_LENINT(protocols);
706
707 return SSL_TLSEXT_ERR_OK;
708}
709
710static int
711ssl_npn_select_cb(SSL *ssl, unsigned char **out, unsigned char *outlen,
712 const unsigned char *in, unsigned int inlen, void *arg)
713{
714 VALUE sslctx_obj, cb;
715
716 sslctx_obj = (VALUE) arg;
717 cb = rb_attr_get(sslctx_obj, id_i_npn_select_cb);
718
719 return ssl_npn_select_cb_common(ssl, cb, (const unsigned char **)out,
720 outlen, in, inlen);
721}
722#endif
723
724#ifdef HAVE_SSL_CTX_SET_ALPN_SELECT_CB
725static int
726ssl_alpn_select_cb(SSL *ssl, const unsigned char **out, unsigned char *outlen,
727 const unsigned char *in, unsigned int inlen, void *arg)
728{
729 VALUE sslctx_obj, cb;
730
731 sslctx_obj = (VALUE) arg;
732 cb = rb_attr_get(sslctx_obj, id_i_alpn_select_cb);
733
734 return ssl_npn_select_cb_common(ssl, cb, out, outlen, in, inlen);
735}
736#endif
737
738/* This function may serve as the entry point to support further callbacks. */
739static void
740ssl_info_cb(const SSL *ssl, int where, int val)
741{
742 int is_server = SSL_is_server((SSL *)ssl);
743
744 if (is_server && where & SSL_CB_HANDSHAKE_START) {
745 ssl_renegotiation_cb(ssl);
746 }
747}
748
749/*
750 * Gets various OpenSSL options.
751 */
752static VALUE
753ossl_sslctx_get_options(VALUE self)
754{
755 SSL_CTX *ctx;
756 GetSSLCTX(self, ctx);
757 /*
758 * Do explicit cast because SSL_CTX_get_options() returned (signed) long in
759 * OpenSSL before 1.1.0.
760 */
761 return ULONG2NUM((unsigned long)SSL_CTX_get_options(ctx));
762}
763
764/*
765 * Sets various OpenSSL options.
766 */
767static VALUE
768ossl_sslctx_set_options(VALUE self, VALUE options)
769{
770 SSL_CTX *ctx;
771
772 rb_check_frozen(self);
773 GetSSLCTX(self, ctx);
774
775 SSL_CTX_clear_options(ctx, SSL_CTX_get_options(ctx));
776
777 if (NIL_P(options)) {
778 SSL_CTX_set_options(ctx, SSL_OP_ALL);
779 } else {
780 SSL_CTX_set_options(ctx, NUM2ULONG(options));
781 }
782
783 return self;
784}
785
786/*
787 * call-seq:
788 * ctx.setup => Qtrue # first time
789 * ctx.setup => nil # thereafter
790 *
791 * This method is called automatically when a new SSLSocket is created.
792 * However, it is not thread-safe and must be called before creating
793 * SSLSocket objects in a multi-threaded program.
794 */
795static VALUE
796ossl_sslctx_setup(VALUE self)
797{
798 SSL_CTX *ctx;
799 X509 *cert = NULL, *client_ca = NULL;
800 EVP_PKEY *key = NULL;
801 char *ca_path = NULL, *ca_file = NULL;
802 int verify_mode;
803 long i;
804 VALUE val;
805
806 if(OBJ_FROZEN(self)) return Qnil;
807 GetSSLCTX(self, ctx);
808
809#if !defined(OPENSSL_NO_DH)
810 SSL_CTX_set_tmp_dh_callback(ctx, ossl_tmp_dh_callback);
811#endif
812
813#if !defined(OPENSSL_NO_EC)
814 /* We added SSLContext#tmp_ecdh_callback= in Ruby 2.3.0,
815 * but SSL_CTX_set_tmp_ecdh_callback() was removed in OpenSSL 1.1.0. */
816 if (RTEST(rb_attr_get(self, id_i_tmp_ecdh_callback))) {
817# if defined(HAVE_SSL_CTX_SET_TMP_ECDH_CALLBACK)
818 rb_warn("#tmp_ecdh_callback= is deprecated; use #ecdh_curves= instead");
819 SSL_CTX_set_tmp_ecdh_callback(ctx, ossl_tmp_ecdh_callback);
820# if defined(HAVE_SSL_CTX_SET_ECDH_AUTO)
821 /* tmp_ecdh_callback and ecdh_auto conflict; OpenSSL ignores
822 * tmp_ecdh_callback. So disable ecdh_auto. */
823 if (!SSL_CTX_set_ecdh_auto(ctx, 0))
824 ossl_raise(eSSLError, "SSL_CTX_set_ecdh_auto");
825# endif
826# else
827 ossl_raise(eSSLError, "OpenSSL does not support tmp_ecdh_callback; "
828 "use #ecdh_curves= instead");
829# endif
830 }
831#endif /* OPENSSL_NO_EC */
832
833 val = rb_attr_get(self, id_i_cert_store);
834 if (!NIL_P(val)) {
835 X509_STORE *store = GetX509StorePtr(val); /* NO NEED TO DUP */
836 SSL_CTX_set_cert_store(ctx, store);
837#if !defined(HAVE_X509_STORE_UP_REF)
838 /*
839 * WORKAROUND:
840 * X509_STORE can count references, but
841 * X509_STORE_free() doesn't care it.
842 * So we won't increment it but mark it by ex_data.
843 */
844 SSL_CTX_set_ex_data(ctx, ossl_sslctx_ex_store_p, ctx);
845#else /* Fixed in OpenSSL 1.0.2; bff9ce4db38b (master), 5b4b9ce976fc (1.0.2) */
846 X509_STORE_up_ref(store);
847#endif
848 }
849
850 val = rb_attr_get(self, id_i_extra_chain_cert);
851 if(!NIL_P(val)){
852 rb_block_call(val, rb_intern("each"), 0, 0, ossl_sslctx_add_extra_chain_cert_i, self);
853 }
854
855 /* private key may be bundled in certificate file. */
856 val = rb_attr_get(self, id_i_cert);
857 cert = NIL_P(val) ? NULL : GetX509CertPtr(val); /* NO DUP NEEDED */
858 val = rb_attr_get(self, id_i_key);
859 key = NIL_P(val) ? NULL : GetPrivPKeyPtr(val); /* NO DUP NEEDED */
860 if (cert && key) {
861 if (!SSL_CTX_use_certificate(ctx, cert)) {
862 /* Adds a ref => Safe to FREE */
863 ossl_raise(eSSLError, "SSL_CTX_use_certificate");
864 }
865 if (!SSL_CTX_use_PrivateKey(ctx, key)) {
866 /* Adds a ref => Safe to FREE */
867 ossl_raise(eSSLError, "SSL_CTX_use_PrivateKey");
868 }
869 if (!SSL_CTX_check_private_key(ctx)) {
870 ossl_raise(eSSLError, "SSL_CTX_check_private_key");
871 }
872 }
873
874 val = rb_attr_get(self, id_i_client_ca);
875 if(!NIL_P(val)){
876 if (RB_TYPE_P(val, T_ARRAY)) {
877 for(i = 0; i < RARRAY_LEN(val); i++){
878 client_ca = GetX509CertPtr(RARRAY_AREF(val, i));
879 if (!SSL_CTX_add_client_CA(ctx, client_ca)){
880 /* Copies X509_NAME => FREE it. */
881 ossl_raise(eSSLError, "SSL_CTX_add_client_CA");
882 }
883 }
884 }
885 else{
886 client_ca = GetX509CertPtr(val); /* NO DUP NEEDED. */
887 if (!SSL_CTX_add_client_CA(ctx, client_ca)){
888 /* Copies X509_NAME => FREE it. */
889 ossl_raise(eSSLError, "SSL_CTX_add_client_CA");
890 }
891 }
892 }
893
894 val = rb_attr_get(self, id_i_ca_file);
895 ca_file = NIL_P(val) ? NULL : StringValueCStr(val);
896 val = rb_attr_get(self, id_i_ca_path);
897 ca_path = NIL_P(val) ? NULL : StringValueCStr(val);
898 if(ca_file || ca_path){
899 if (!SSL_CTX_load_verify_locations(ctx, ca_file, ca_path))
900 rb_warning("can't set verify locations");
901 }
902
903 val = rb_attr_get(self, id_i_verify_mode);
904 verify_mode = NIL_P(val) ? SSL_VERIFY_NONE : NUM2INT(val);
905 SSL_CTX_set_verify(ctx, verify_mode, ossl_ssl_verify_callback);
906 if (RTEST(rb_attr_get(self, id_i_client_cert_cb)))
907 SSL_CTX_set_client_cert_cb(ctx, ossl_client_cert_cb);
908
909 val = rb_attr_get(self, id_i_timeout);
910 if(!NIL_P(val)) SSL_CTX_set_timeout(ctx, NUM2LONG(val));
911
912 val = rb_attr_get(self, id_i_verify_depth);
913 if(!NIL_P(val)) SSL_CTX_set_verify_depth(ctx, NUM2INT(val));
914
915#ifndef OPENSSL_NO_NEXTPROTONEG
916 val = rb_attr_get(self, id_i_npn_protocols);
917 if (!NIL_P(val)) {
918 VALUE encoded = ssl_encode_npn_protocols(val);
919 rb_ivar_set(self, id_npn_protocols_encoded, encoded);
920 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_npn_advertise_cb, (void *)self);
921 OSSL_Debug("SSL NPN advertise callback added");
922 }
923 if (RTEST(rb_attr_get(self, id_i_npn_select_cb))) {
924 SSL_CTX_set_next_proto_select_cb(ctx, ssl_npn_select_cb, (void *) self);
925 OSSL_Debug("SSL NPN select callback added");
926 }
927#endif
928
929#ifdef HAVE_SSL_CTX_SET_ALPN_SELECT_CB
930 val = rb_attr_get(self, id_i_alpn_protocols);
931 if (!NIL_P(val)) {
932 VALUE rprotos = ssl_encode_npn_protocols(val);
933
934 /* returns 0 on success */
935 if (SSL_CTX_set_alpn_protos(ctx, (unsigned char *)RSTRING_PTR(rprotos),
936 RSTRING_LENINT(rprotos)))
937 ossl_raise(eSSLError, "SSL_CTX_set_alpn_protos");
938 OSSL_Debug("SSL ALPN values added");
939 }
940 if (RTEST(rb_attr_get(self, id_i_alpn_select_cb))) {
941 SSL_CTX_set_alpn_select_cb(ctx, ssl_alpn_select_cb, (void *) self);
942 OSSL_Debug("SSL ALPN select callback added");
943 }
944#endif
945
946 rb_obj_freeze(self);
947
948 val = rb_attr_get(self, id_i_session_id_context);
949 if (!NIL_P(val)){
950 StringValue(val);
951 if (!SSL_CTX_set_session_id_context(ctx, (unsigned char *)RSTRING_PTR(val),
952 RSTRING_LENINT(val))){
953 ossl_raise(eSSLError, "SSL_CTX_set_session_id_context");
954 }
955 }
956
957 if (RTEST(rb_attr_get(self, id_i_session_get_cb))) {
958 SSL_CTX_sess_set_get_cb(ctx, ossl_sslctx_session_get_cb);
959 OSSL_Debug("SSL SESSION get callback added");
960 }
961 if (RTEST(rb_attr_get(self, id_i_session_new_cb))) {
962 SSL_CTX_sess_set_new_cb(ctx, ossl_sslctx_session_new_cb);
963 OSSL_Debug("SSL SESSION new callback added");
964 }
965 if (RTEST(rb_attr_get(self, id_i_session_remove_cb))) {
966 SSL_CTX_sess_set_remove_cb(ctx, ossl_sslctx_session_remove_cb);
967 OSSL_Debug("SSL SESSION remove callback added");
968 }
969
970 val = rb_attr_get(self, id_i_servername_cb);
971 if (!NIL_P(val)) {
972 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
973 OSSL_Debug("SSL TLSEXT servername callback added");
974 }
975
976 return Qtrue;
977}
978
979static VALUE
980ossl_ssl_cipher_to_ary(const SSL_CIPHER *cipher)
981{
982 VALUE ary;
983 int bits, alg_bits;
984
985 ary = rb_ary_new2(4);
986 rb_ary_push(ary, rb_str_new2(SSL_CIPHER_get_name(cipher)));
987 rb_ary_push(ary, rb_str_new2(SSL_CIPHER_get_version(cipher)));
988 bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
989 rb_ary_push(ary, INT2NUM(bits));
990 rb_ary_push(ary, INT2NUM(alg_bits));
991
992 return ary;
993}
994
995/*
996 * call-seq:
997 * ctx.ciphers => [[name, version, bits, alg_bits], ...]
998 *
999 * The list of cipher suites configured for this context.
1000 */
1001static VALUE
1002ossl_sslctx_get_ciphers(VALUE self)
1003{
1004 SSL_CTX *ctx;
1005 STACK_OF(SSL_CIPHER) *ciphers;
1006 const SSL_CIPHER *cipher;
1007 VALUE ary;
1008 int i, num;
1009
1010 GetSSLCTX(self, ctx);
1011 ciphers = SSL_CTX_get_ciphers(ctx);
1012 if (!ciphers)
1013 return rb_ary_new();
1014
1015 num = sk_SSL_CIPHER_num(ciphers);
1016 ary = rb_ary_new2(num);
1017 for(i = 0; i < num; i++){
1018 cipher = sk_SSL_CIPHER_value(ciphers, i);
1019 rb_ary_push(ary, ossl_ssl_cipher_to_ary(cipher));
1020 }
1021 return ary;
1022}
1023
1024/*
1025 * call-seq:
1026 * ctx.ciphers = "cipher1:cipher2:..."
1027 * ctx.ciphers = [name, ...]
1028 * ctx.ciphers = [[name, version, bits, alg_bits], ...]
1029 *
1030 * Sets the list of available cipher suites for this context. Note in a server
1031 * context some ciphers require the appropriate certificates. For example, an
1032 * RSA cipher suite can only be chosen when an RSA certificate is available.
1033 */
1034static VALUE
1035ossl_sslctx_set_ciphers(VALUE self, VALUE v)
1036{
1037 SSL_CTX *ctx;
1038 VALUE str, elem;
1039 int i;
1040
1041 rb_check_frozen(self);
1042 if (NIL_P(v))
1043 return v;
1044 else if (RB_TYPE_P(v, T_ARRAY)) {
1045 str = rb_str_new(0, 0);
1046 for (i = 0; i < RARRAY_LEN(v); i++) {
1047 elem = rb_ary_entry(v, i);
1048 if (RB_TYPE_P(elem, T_ARRAY)) elem = rb_ary_entry(elem, 0);
1049 elem = rb_String(elem);
1050 rb_str_append(str, elem);
1051 if (i < RARRAY_LEN(v)-1) rb_str_cat2(str, ":");
1052 }
1053 } else {
1054 str = v;
1056 }
1057
1058 GetSSLCTX(self, ctx);
1059 if (!SSL_CTX_set_cipher_list(ctx, StringValueCStr(str))) {
1060 ossl_raise(eSSLError, "SSL_CTX_set_cipher_list");
1061 }
1062
1063 return v;
1064}
1065
1066#if !defined(OPENSSL_NO_EC)
1067/*
1068 * call-seq:
1069 * ctx.ecdh_curves = curve_list -> curve_list
1070 *
1071 * Sets the list of "supported elliptic curves" for this context.
1072 *
1073 * For a TLS client, the list is directly used in the Supported Elliptic Curves
1074 * Extension. For a server, the list is used by OpenSSL to determine the set of
1075 * shared curves. OpenSSL will pick the most appropriate one from it.
1076 *
1077 * Note that this works differently with old OpenSSL (<= 1.0.1). Only one curve
1078 * can be set, and this has no effect for TLS clients.
1079 *
1080 * === Example
1081 * ctx1 = OpenSSL::SSL::SSLContext.new
1082 * ctx1.ecdh_curves = "X25519:P-256:P-224"
1083 * svr = OpenSSL::SSL::SSLServer.new(tcp_svr, ctx1)
1084 * Thread.new { svr.accept }
1085 *
1086 * ctx2 = OpenSSL::SSL::SSLContext.new
1087 * ctx2.ecdh_curves = "P-256"
1088 * cli = OpenSSL::SSL::SSLSocket.new(tcp_sock, ctx2)
1089 * cli.connect
1090 *
1091 * p cli.tmp_key.group.curve_name
1092 * # => "prime256v1" (is an alias for NIST P-256)
1093 */
1094static VALUE
1095ossl_sslctx_set_ecdh_curves(VALUE self, VALUE arg)
1096{
1097 SSL_CTX *ctx;
1098
1099 rb_check_frozen(self);
1100 GetSSLCTX(self, ctx);
1102
1103#if defined(HAVE_SSL_CTX_SET1_CURVES_LIST)
1104 if (!SSL_CTX_set1_curves_list(ctx, RSTRING_PTR(arg)))
1105 ossl_raise(eSSLError, NULL);
1106#else
1107 /* OpenSSL does not have SSL_CTX_set1_curves_list()... Fallback to
1108 * SSL_CTX_set_tmp_ecdh(). So only the first curve is used. */
1109 {
1110 VALUE curve, splitted;
1111 EC_KEY *ec;
1112 int nid;
1113
1114 splitted = rb_str_split(arg, ":");
1115 if (!RARRAY_LEN(splitted))
1116 ossl_raise(eSSLError, "invalid input format");
1117 curve = RARRAY_AREF(splitted, 0);
1118 StringValueCStr(curve);
1119
1120 /* SSL_CTX_set1_curves_list() accepts NIST names */
1122 if (nid == NID_undef)
1123 nid = OBJ_txt2nid(RSTRING_PTR(curve));
1124 if (nid == NID_undef)
1125 ossl_raise(eSSLError, "unknown curve name");
1126
1127 ec = EC_KEY_new_by_curve_name(nid);
1128 if (!ec)
1129 ossl_raise(eSSLError, NULL);
1130 EC_KEY_set_asn1_flag(ec, OPENSSL_EC_NAMED_CURVE);
1131 if (!SSL_CTX_set_tmp_ecdh(ctx, ec)) {
1132 EC_KEY_free(ec);
1133 ossl_raise(eSSLError, "SSL_CTX_set_tmp_ecdh");
1134 }
1135 EC_KEY_free(ec);
1136# if defined(HAVE_SSL_CTX_SET_ECDH_AUTO)
1137 /* tmp_ecdh and ecdh_auto conflict. tmp_ecdh is ignored when ecdh_auto
1138 * is enabled. So disable ecdh_auto. */
1139 if (!SSL_CTX_set_ecdh_auto(ctx, 0))
1140 ossl_raise(eSSLError, "SSL_CTX_set_ecdh_auto");
1141# endif
1142 }
1143#endif
1144
1145 return arg;
1146}
1147#else
1148#define ossl_sslctx_set_ecdh_curves rb_f_notimplement
1149#endif
1150
1151/*
1152 * call-seq:
1153 * ctx.security_level -> Integer
1154 *
1155 * Returns the security level for the context.
1156 *
1157 * See also OpenSSL::SSL::SSLContext#security_level=.
1158 */
1159static VALUE
1160ossl_sslctx_get_security_level(VALUE self)
1161{
1162 SSL_CTX *ctx;
1163
1164 GetSSLCTX(self, ctx);
1165
1166#if defined(HAVE_SSL_CTX_GET_SECURITY_LEVEL)
1167 return INT2NUM(SSL_CTX_get_security_level(ctx));
1168#else
1169 (void)ctx;
1170 return INT2FIX(0);
1171#endif
1172}
1173
1174/*
1175 * call-seq:
1176 * ctx.security_level = integer
1177 *
1178 * Sets the security level for the context. OpenSSL limits parameters according
1179 * to the level. The "parameters" include: ciphersuites, curves, key sizes,
1180 * certificate signature algorithms, protocol version and so on. For example,
1181 * level 1 rejects parameters offering below 80 bits of security, such as
1182 * ciphersuites using MD5 for the MAC or RSA keys shorter than 1024 bits.
1183 *
1184 * Note that attempts to set such parameters with insufficient security are
1185 * also blocked. You need to lower the level first.
1186 *
1187 * This feature is not supported in OpenSSL < 1.1.0, and setting the level to
1188 * other than 0 will raise NotImplementedError. Level 0 means everything is
1189 * permitted, the same behavior as previous versions of OpenSSL.
1190 *
1191 * See the manpage of SSL_CTX_set_security_level(3) for details.
1192 */
1193static VALUE
1194ossl_sslctx_set_security_level(VALUE self, VALUE value)
1195{
1196 SSL_CTX *ctx;
1197
1198 rb_check_frozen(self);
1199 GetSSLCTX(self, ctx);
1200
1201#if defined(HAVE_SSL_CTX_GET_SECURITY_LEVEL)
1202 SSL_CTX_set_security_level(ctx, NUM2INT(value));
1203#else
1204 (void)ctx;
1205 if (NUM2INT(value) != 0)
1206 ossl_raise(rb_eNotImpError, "setting security level to other than 0 is "
1207 "not supported in this version of OpenSSL");
1208#endif
1209
1210 return value;
1211}
1212
1213#ifdef SSL_MODE_SEND_FALLBACK_SCSV
1214/*
1215 * call-seq:
1216 * ctx.enable_fallback_scsv() => nil
1217 *
1218 * Activate TLS_FALLBACK_SCSV for this context.
1219 * See RFC 7507.
1220 */
1221static VALUE
1222ossl_sslctx_enable_fallback_scsv(VALUE self)
1223{
1224 SSL_CTX *ctx;
1225
1226 GetSSLCTX(self, ctx);
1227 SSL_CTX_set_mode(ctx, SSL_MODE_SEND_FALLBACK_SCSV);
1228
1229 return Qnil;
1230}
1231#endif
1232
1233/*
1234 * call-seq:
1235 * ctx.add_certificate(certiticate, pkey [, extra_certs]) -> self
1236 *
1237 * Adds a certificate to the context. _pkey_ must be a corresponding private
1238 * key with _certificate_.
1239 *
1240 * Multiple certificates with different public key type can be added by
1241 * repeated calls of this method, and OpenSSL will choose the most appropriate
1242 * certificate during the handshake.
1243 *
1244 * #cert=, #key=, and #extra_chain_cert= are old accessor methods for setting
1245 * certificate and internally call this method.
1246 *
1247 * === Parameters
1248 * _certificate_::
1249 * A certificate. An instance of OpenSSL::X509::Certificate.
1250 * _pkey_::
1251 * The private key for _certificate_. An instance of OpenSSL::PKey::PKey.
1252 * _extra_certs_::
1253 * Optional. An array of OpenSSL::X509::Certificate. When sending a
1254 * certificate chain, the certificates specified by this are sent following
1255 * _certificate_, in the order in the array.
1256 *
1257 * === Example
1258 * rsa_cert = OpenSSL::X509::Certificate.new(...)
1259 * rsa_pkey = OpenSSL::PKey.read(...)
1260 * ca_intermediate_cert = OpenSSL::X509::Certificate.new(...)
1261 * ctx.add_certificate(rsa_cert, rsa_pkey, [ca_intermediate_cert])
1262 *
1263 * ecdsa_cert = ...
1264 * ecdsa_pkey = ...
1265 * another_ca_cert = ...
1266 * ctx.add_certificate(ecdsa_cert, ecdsa_pkey, [another_ca_cert])
1267 *
1268 * === Note
1269 * OpenSSL before the version 1.0.2 could handle only one extra chain across
1270 * all key types. Calling this method discards the chain set previously.
1271 */
1272static VALUE
1273ossl_sslctx_add_certificate(int argc, VALUE *argv, VALUE self)
1274{
1275 VALUE cert, key, extra_chain_ary;
1276 SSL_CTX *ctx;
1277 X509 *x509;
1278 STACK_OF(X509) *extra_chain = NULL;
1279 EVP_PKEY *pkey, *pub_pkey;
1280
1281 GetSSLCTX(self, ctx);
1282 rb_scan_args(argc, argv, "21", &cert, &key, &extra_chain_ary);
1283 rb_check_frozen(self);
1284 x509 = GetX509CertPtr(cert);
1285 pkey = GetPrivPKeyPtr(key);
1286
1287 /*
1288 * The reference counter is bumped, and decremented immediately.
1289 * X509_get0_pubkey() is only available in OpenSSL >= 1.1.0.
1290 */
1291 pub_pkey = X509_get_pubkey(x509);
1292 EVP_PKEY_free(pub_pkey);
1293 if (!pub_pkey)
1294 rb_raise(rb_eArgError, "certificate does not contain public key");
1295 if (EVP_PKEY_cmp(pub_pkey, pkey) != 1)
1296 rb_raise(rb_eArgError, "public key mismatch");
1297
1298 if (argc >= 3)
1299 extra_chain = ossl_x509_ary2sk(extra_chain_ary);
1300
1301 if (!SSL_CTX_use_certificate(ctx, x509)) {
1302 sk_X509_pop_free(extra_chain, X509_free);
1303 ossl_raise(eSSLError, "SSL_CTX_use_certificate");
1304 }
1305 if (!SSL_CTX_use_PrivateKey(ctx, pkey)) {
1306 sk_X509_pop_free(extra_chain, X509_free);
1307 ossl_raise(eSSLError, "SSL_CTX_use_PrivateKey");
1308 }
1309
1310 if (extra_chain) {
1311#if OPENSSL_VERSION_NUMBER >= 0x10002000 && !defined(LIBRESSL_VERSION_NUMBER)
1312 if (!SSL_CTX_set0_chain(ctx, extra_chain)) {
1313 sk_X509_pop_free(extra_chain, X509_free);
1314 ossl_raise(eSSLError, "SSL_CTX_set0_chain");
1315 }
1316#else
1317 STACK_OF(X509) *orig_extra_chain;
1318 X509 *x509_tmp;
1319
1320 /* First, clear the existing chain */
1321 SSL_CTX_get_extra_chain_certs(ctx, &orig_extra_chain);
1322 if (orig_extra_chain && sk_X509_num(orig_extra_chain)) {
1323 rb_warning("SSL_CTX_set0_chain() is not available; " \
1324 "clearing previously set certificate chain");
1325 SSL_CTX_clear_extra_chain_certs(ctx);
1326 }
1327 while ((x509_tmp = sk_X509_shift(extra_chain))) {
1328 /* Transfers ownership */
1329 if (!SSL_CTX_add_extra_chain_cert(ctx, x509_tmp)) {
1330 X509_free(x509_tmp);
1331 sk_X509_pop_free(extra_chain, X509_free);
1332 ossl_raise(eSSLError, "SSL_CTX_add_extra_chain_cert");
1333 }
1334 }
1335 sk_X509_free(extra_chain);
1336#endif
1337 }
1338 return self;
1339}
1340
1341/*
1342 * call-seq:
1343 * ctx.session_add(session) -> true | false
1344 *
1345 * Adds _session_ to the session cache.
1346 */
1347static VALUE
1348ossl_sslctx_session_add(VALUE self, VALUE arg)
1349{
1350 SSL_CTX *ctx;
1351 SSL_SESSION *sess;
1352
1353 GetSSLCTX(self, ctx);
1354 GetSSLSession(arg, sess);
1355
1356 return SSL_CTX_add_session(ctx, sess) == 1 ? Qtrue : Qfalse;
1357}
1358
1359/*
1360 * call-seq:
1361 * ctx.session_remove(session) -> true | false
1362 *
1363 * Removes _session_ from the session cache.
1364 */
1365static VALUE
1366ossl_sslctx_session_remove(VALUE self, VALUE arg)
1367{
1368 SSL_CTX *ctx;
1369 SSL_SESSION *sess;
1370
1371 GetSSLCTX(self, ctx);
1372 GetSSLSession(arg, sess);
1373
1374 return SSL_CTX_remove_session(ctx, sess) == 1 ? Qtrue : Qfalse;
1375}
1376
1377/*
1378 * call-seq:
1379 * ctx.session_cache_mode -> Integer
1380 *
1381 * The current session cache mode.
1382 */
1383static VALUE
1384ossl_sslctx_get_session_cache_mode(VALUE self)
1385{
1386 SSL_CTX *ctx;
1387
1388 GetSSLCTX(self, ctx);
1389
1390 return LONG2NUM(SSL_CTX_get_session_cache_mode(ctx));
1391}
1392
1393/*
1394 * call-seq:
1395 * ctx.session_cache_mode=(integer) -> Integer
1396 *
1397 * Sets the SSL session cache mode. Bitwise-or together the desired
1398 * SESSION_CACHE_* constants to set. See SSL_CTX_set_session_cache_mode(3) for
1399 * details.
1400 */
1401static VALUE
1402ossl_sslctx_set_session_cache_mode(VALUE self, VALUE arg)
1403{
1404 SSL_CTX *ctx;
1405
1406 GetSSLCTX(self, ctx);
1407
1408 SSL_CTX_set_session_cache_mode(ctx, NUM2LONG(arg));
1409
1410 return arg;
1411}
1412
1413/*
1414 * call-seq:
1415 * ctx.session_cache_size -> Integer
1416 *
1417 * Returns the current session cache size. Zero is used to represent an
1418 * unlimited cache size.
1419 */
1420static VALUE
1421ossl_sslctx_get_session_cache_size(VALUE self)
1422{
1423 SSL_CTX *ctx;
1424
1425 GetSSLCTX(self, ctx);
1426
1427 return LONG2NUM(SSL_CTX_sess_get_cache_size(ctx));
1428}
1429
1430/*
1431 * call-seq:
1432 * ctx.session_cache_size=(integer) -> Integer
1433 *
1434 * Sets the session cache size. Returns the previously valid session cache
1435 * size. Zero is used to represent an unlimited session cache size.
1436 */
1437static VALUE
1438ossl_sslctx_set_session_cache_size(VALUE self, VALUE arg)
1439{
1440 SSL_CTX *ctx;
1441
1442 GetSSLCTX(self, ctx);
1443
1444 SSL_CTX_sess_set_cache_size(ctx, NUM2LONG(arg));
1445
1446 return arg;
1447}
1448
1449/*
1450 * call-seq:
1451 * ctx.session_cache_stats -> Hash
1452 *
1453 * Returns a Hash containing the following keys:
1454 *
1455 * :accept:: Number of started SSL/TLS handshakes in server mode
1456 * :accept_good:: Number of established SSL/TLS sessions in server mode
1457 * :accept_renegotiate:: Number of start renegotiations in server mode
1458 * :cache_full:: Number of sessions that were removed due to cache overflow
1459 * :cache_hits:: Number of successfully reused connections
1460 * :cache_misses:: Number of sessions proposed by clients that were not found
1461 * in the cache
1462 * :cache_num:: Number of sessions in the internal session cache
1463 * :cb_hits:: Number of sessions retrieved from the external cache in server
1464 * mode
1465 * :connect:: Number of started SSL/TLS handshakes in client mode
1466 * :connect_good:: Number of established SSL/TLS sessions in client mode
1467 * :connect_renegotiate:: Number of start renegotiations in client mode
1468 * :timeouts:: Number of sessions proposed by clients that were found in the
1469 * cache but had expired due to timeouts
1470 */
1471static VALUE
1472ossl_sslctx_get_session_cache_stats(VALUE self)
1473{
1474 SSL_CTX *ctx;
1475 VALUE hash;
1476
1477 GetSSLCTX(self, ctx);
1478
1479 hash = rb_hash_new();
1480 rb_hash_aset(hash, ID2SYM(rb_intern("cache_num")), LONG2NUM(SSL_CTX_sess_number(ctx)));
1481 rb_hash_aset(hash, ID2SYM(rb_intern("connect")), LONG2NUM(SSL_CTX_sess_connect(ctx)));
1482 rb_hash_aset(hash, ID2SYM(rb_intern("connect_good")), LONG2NUM(SSL_CTX_sess_connect_good(ctx)));
1483 rb_hash_aset(hash, ID2SYM(rb_intern("connect_renegotiate")), LONG2NUM(SSL_CTX_sess_connect_renegotiate(ctx)));
1484 rb_hash_aset(hash, ID2SYM(rb_intern("accept")), LONG2NUM(SSL_CTX_sess_accept(ctx)));
1485 rb_hash_aset(hash, ID2SYM(rb_intern("accept_good")), LONG2NUM(SSL_CTX_sess_accept_good(ctx)));
1486 rb_hash_aset(hash, ID2SYM(rb_intern("accept_renegotiate")), LONG2NUM(SSL_CTX_sess_accept_renegotiate(ctx)));
1487 rb_hash_aset(hash, ID2SYM(rb_intern("cache_hits")), LONG2NUM(SSL_CTX_sess_hits(ctx)));
1488 rb_hash_aset(hash, ID2SYM(rb_intern("cb_hits")), LONG2NUM(SSL_CTX_sess_cb_hits(ctx)));
1489 rb_hash_aset(hash, ID2SYM(rb_intern("cache_misses")), LONG2NUM(SSL_CTX_sess_misses(ctx)));
1490 rb_hash_aset(hash, ID2SYM(rb_intern("cache_full")), LONG2NUM(SSL_CTX_sess_cache_full(ctx)));
1491 rb_hash_aset(hash, ID2SYM(rb_intern("timeouts")), LONG2NUM(SSL_CTX_sess_timeouts(ctx)));
1492
1493 return hash;
1494}
1495
1496
1497/*
1498 * call-seq:
1499 * ctx.flush_sessions(time) -> self
1500 *
1501 * Removes sessions in the internal cache that have expired at _time_.
1502 */
1503static VALUE
1504ossl_sslctx_flush_sessions(int argc, VALUE *argv, VALUE self)
1505{
1506 VALUE arg1;
1507 SSL_CTX *ctx;
1508 time_t tm = 0;
1509
1510 rb_scan_args(argc, argv, "01", &arg1);
1511
1512 GetSSLCTX(self, ctx);
1513
1514 if (NIL_P(arg1)) {
1515 tm = time(0);
1516 } else if (rb_obj_is_instance_of(arg1, rb_cTime)) {
1517 tm = NUM2LONG(rb_funcall(arg1, rb_intern("to_i"), 0));
1518 } else {
1519 ossl_raise(rb_eArgError, "arg must be Time or nil");
1520 }
1521
1522 SSL_CTX_flush_sessions(ctx, (long)tm);
1523
1524 return self;
1525}
1526
1527/*
1528 * SSLSocket class
1529 */
1530#ifndef OPENSSL_NO_SOCK
1531static inline int
1532ssl_started(SSL *ssl)
1533{
1534 /* the FD is set in ossl_ssl_setup(), called by #connect or #accept */
1535 return SSL_get_fd(ssl) >= 0;
1536}
1537
1538static void
1539ossl_ssl_mark(void *ptr)
1540{
1541 SSL *ssl = ptr;
1542 rb_gc_mark((VALUE)SSL_get_ex_data(ssl, ossl_ssl_ex_ptr_idx));
1543 rb_gc_mark((VALUE)SSL_get_ex_data(ssl, ossl_ssl_ex_vcb_idx));
1544}
1545
1546static void
1547ossl_ssl_free(void *ssl)
1548{
1549 SSL_free(ssl);
1550}
1551
1553 "OpenSSL/SSL",
1554 {
1555 ossl_ssl_mark, ossl_ssl_free,
1556 },
1558};
1559
1560static VALUE
1561ossl_ssl_s_alloc(VALUE klass)
1562{
1564}
1565
1566/*
1567 * call-seq:
1568 * SSLSocket.new(io) => aSSLSocket
1569 * SSLSocket.new(io, ctx) => aSSLSocket
1570 *
1571 * Creates a new SSL socket from _io_ which must be a real IO object (not an
1572 * IO-like object that responds to read/write).
1573 *
1574 * If _ctx_ is provided the SSL Sockets initial params will be taken from
1575 * the context.
1576 *
1577 * The OpenSSL::Buffering module provides additional IO methods.
1578 *
1579 * This method will freeze the SSLContext if one is provided;
1580 * however, session management is still allowed in the frozen SSLContext.
1581 */
1582static VALUE
1583ossl_ssl_initialize(int argc, VALUE *argv, VALUE self)
1584{
1585 VALUE io, v_ctx, verify_cb;
1586 SSL *ssl;
1587 SSL_CTX *ctx;
1588
1589 TypedData_Get_Struct(self, SSL, &ossl_ssl_type, ssl);
1590 if (ssl)
1591 ossl_raise(eSSLError, "SSL already initialized");
1592
1593 if (rb_scan_args(argc, argv, "11", &io, &v_ctx) == 1)
1594 v_ctx = rb_funcall(cSSLContext, rb_intern("new"), 0);
1595
1596 GetSSLCTX(v_ctx, ctx);
1597 rb_ivar_set(self, id_i_context, v_ctx);
1598 ossl_sslctx_setup(v_ctx);
1599
1600 if (rb_respond_to(io, rb_intern("nonblock=")))
1601 rb_funcall(io, rb_intern("nonblock="), 1, Qtrue);
1602 rb_ivar_set(self, id_i_io, io);
1603
1604 ssl = SSL_new(ctx);
1605 if (!ssl)
1606 ossl_raise(eSSLError, NULL);
1607 RTYPEDDATA_DATA(self) = ssl;
1608
1609 SSL_set_ex_data(ssl, ossl_ssl_ex_ptr_idx, (void *)self);
1610 SSL_set_info_callback(ssl, ssl_info_cb);
1611 verify_cb = rb_attr_get(v_ctx, id_i_verify_callback);
1612 SSL_set_ex_data(ssl, ossl_ssl_ex_vcb_idx, (void *)verify_cb);
1613
1614 rb_call_super(0, NULL);
1615
1616 return self;
1617}
1618
1619static VALUE
1620ossl_ssl_setup(VALUE self)
1621{
1622 VALUE io;
1623 SSL *ssl;
1624 rb_io_t *fptr;
1625
1626 GetSSL(self, ssl);
1627 if (ssl_started(ssl))
1628 return Qtrue;
1629
1630 io = rb_attr_get(self, id_i_io);
1631 GetOpenFile(io, fptr);
1634 if (!SSL_set_fd(ssl, TO_SOCKET(fptr->fd)))
1635 ossl_raise(eSSLError, "SSL_set_fd");
1636
1637 return Qtrue;
1638}
1639
1640#ifdef _WIN32
1641#define ssl_get_error(ssl, ret) (errno = rb_w32_map_errno(WSAGetLastError()), SSL_get_error((ssl), (ret)))
1642#else
1643#define ssl_get_error(ssl, ret) SSL_get_error((ssl), (ret))
1644#endif
1645
1646static void
1647write_would_block(int nonblock)
1648{
1649 if (nonblock)
1650 ossl_raise(eSSLErrorWaitWritable, "write would block");
1651}
1652
1653static void
1654read_would_block(int nonblock)
1655{
1656 if (nonblock)
1657 ossl_raise(eSSLErrorWaitReadable, "read would block");
1658}
1659
1660static int
1662{
1663 if (RB_TYPE_P(opts, T_HASH) &&
1664 rb_hash_lookup2(opts, sym_exception, Qundef) == Qfalse)
1665 return 1;
1666 return 0;
1667}
1668
1669static VALUE
1670ossl_start_ssl(VALUE self, int (*func)(), const char *funcname, VALUE opts)
1671{
1672 SSL *ssl;
1673 rb_io_t *fptr;
1674 int ret, ret2;
1675 VALUE cb_state;
1676 int nonblock = opts != Qfalse;
1677#if defined(SSL_R_CERTIFICATE_VERIFY_FAILED)
1678 unsigned long err;
1679#endif
1680
1681 rb_ivar_set(self, ID_callback_state, Qnil);
1682
1683 GetSSL(self, ssl);
1684
1685 GetOpenFile(rb_attr_get(self, id_i_io), fptr);
1686 for(;;){
1687 ret = func(ssl);
1688
1689 cb_state = rb_attr_get(self, ID_callback_state);
1690 if (!NIL_P(cb_state)) {
1691 /* must cleanup OpenSSL error stack before re-raising */
1693 rb_jump_tag(NUM2INT(cb_state));
1694 }
1695
1696 if (ret > 0)
1697 break;
1698
1699 switch((ret2 = ssl_get_error(ssl, ret))){
1700 case SSL_ERROR_WANT_WRITE:
1701 if (no_exception_p(opts)) { return sym_wait_writable; }
1702 write_would_block(nonblock);
1703 rb_io_wait_writable(fptr->fd);
1704 continue;
1705 case SSL_ERROR_WANT_READ:
1706 if (no_exception_p(opts)) { return sym_wait_readable; }
1707 read_would_block(nonblock);
1708 rb_io_wait_readable(fptr->fd);
1709 continue;
1710 case SSL_ERROR_SYSCALL:
1711#ifdef __APPLE__
1712 /* See ossl_ssl_write_internal() */
1713 if (errno == EPROTOTYPE)
1714 continue;
1715#endif
1716 if (errno) rb_sys_fail(funcname);
1717 ossl_raise(eSSLError, "%s SYSCALL returned=%d errno=%d state=%s", funcname, ret2, errno, SSL_state_string_long(ssl));
1718#if defined(SSL_R_CERTIFICATE_VERIFY_FAILED)
1719 case SSL_ERROR_SSL:
1720 err = ERR_peek_last_error();
1721 if (ERR_GET_LIB(err) == ERR_LIB_SSL &&
1722 ERR_GET_REASON(err) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
1723 const char *err_msg = ERR_reason_error_string(err),
1724 *verify_msg = X509_verify_cert_error_string(SSL_get_verify_result(ssl));
1725 if (!err_msg)
1726 err_msg = "(null)";
1727 if (!verify_msg)
1728 verify_msg = "(null)";
1729 ossl_clear_error(); /* let ossl_raise() not append message */
1730 ossl_raise(eSSLError, "%s returned=%d errno=%d state=%s: %s (%s)",
1731 funcname, ret2, errno, SSL_state_string_long(ssl),
1732 err_msg, verify_msg);
1733 }
1734#endif
1735 default:
1736 ossl_raise(eSSLError, "%s returned=%d errno=%d state=%s", funcname, ret2, errno, SSL_state_string_long(ssl));
1737 }
1738 }
1739
1740 return self;
1741}
1742
1743/*
1744 * call-seq:
1745 * ssl.connect => self
1746 *
1747 * Initiates an SSL/TLS handshake with a server. The handshake may be started
1748 * after unencrypted data has been sent over the socket.
1749 */
1750static VALUE
1751ossl_ssl_connect(VALUE self)
1752{
1753 ossl_ssl_setup(self);
1754
1755 return ossl_start_ssl(self, SSL_connect, "SSL_connect", Qfalse);
1756}
1757
1758/*
1759 * call-seq:
1760 * ssl.connect_nonblock([options]) => self
1761 *
1762 * Initiates the SSL/TLS handshake as a client in non-blocking manner.
1763 *
1764 * # emulates blocking connect
1765 * begin
1766 * ssl.connect_nonblock
1767 * rescue IO::WaitReadable
1768 * IO.select([s2])
1769 * retry
1770 * rescue IO::WaitWritable
1771 * IO.select(nil, [s2])
1772 * retry
1773 * end
1774 *
1775 * By specifying a keyword argument _exception_ to +false+, you can indicate
1776 * that connect_nonblock should not raise an IO::WaitReadable or
1777 * IO::WaitWritable exception, but return the symbol +:wait_readable+ or
1778 * +:wait_writable+ instead.
1779 */
1780static VALUE
1781ossl_ssl_connect_nonblock(int argc, VALUE *argv, VALUE self)
1782{
1783 VALUE opts;
1784 rb_scan_args(argc, argv, "0:", &opts);
1785
1786 ossl_ssl_setup(self);
1787
1788 return ossl_start_ssl(self, SSL_connect, "SSL_connect", opts);
1789}
1790
1791/*
1792 * call-seq:
1793 * ssl.accept => self
1794 *
1795 * Waits for a SSL/TLS client to initiate a handshake. The handshake may be
1796 * started after unencrypted data has been sent over the socket.
1797 */
1798static VALUE
1799ossl_ssl_accept(VALUE self)
1800{
1801 ossl_ssl_setup(self);
1802
1803 return ossl_start_ssl(self, SSL_accept, "SSL_accept", Qfalse);
1804}
1805
1806/*
1807 * call-seq:
1808 * ssl.accept_nonblock([options]) => self
1809 *
1810 * Initiates the SSL/TLS handshake as a server in non-blocking manner.
1811 *
1812 * # emulates blocking accept
1813 * begin
1814 * ssl.accept_nonblock
1815 * rescue IO::WaitReadable
1816 * IO.select([s2])
1817 * retry
1818 * rescue IO::WaitWritable
1819 * IO.select(nil, [s2])
1820 * retry
1821 * end
1822 *
1823 * By specifying a keyword argument _exception_ to +false+, you can indicate
1824 * that accept_nonblock should not raise an IO::WaitReadable or
1825 * IO::WaitWritable exception, but return the symbol +:wait_readable+ or
1826 * +:wait_writable+ instead.
1827 */
1828static VALUE
1829ossl_ssl_accept_nonblock(int argc, VALUE *argv, VALUE self)
1830{
1831 VALUE opts;
1832
1833 rb_scan_args(argc, argv, "0:", &opts);
1834 ossl_ssl_setup(self);
1835
1836 return ossl_start_ssl(self, SSL_accept, "SSL_accept", opts);
1837}
1838
1839static VALUE
1840ossl_ssl_read_internal(int argc, VALUE *argv, VALUE self, int nonblock)
1841{
1842 SSL *ssl;
1843 int ilen, nread = 0;
1844 VALUE len, str;
1845 rb_io_t *fptr;
1846 VALUE io, opts = Qnil;
1847
1848 if (nonblock) {
1849 rb_scan_args(argc, argv, "11:", &len, &str, &opts);
1850 } else {
1851 rb_scan_args(argc, argv, "11", &len, &str);
1852 }
1853
1854 ilen = NUM2INT(len);
1855 if (NIL_P(str))
1856 str = rb_str_new(0, ilen);
1857 else {
1859 if (RSTRING_LEN(str) >= ilen)
1861 else
1863 }
1864 rb_str_set_len(str, 0);
1865 if (ilen == 0)
1866 return str;
1867
1868 GetSSL(self, ssl);
1869 io = rb_attr_get(self, id_i_io);
1870 GetOpenFile(io, fptr);
1871 if (ssl_started(ssl)) {
1873 for (;;) {
1874 nread = SSL_read(ssl, RSTRING_PTR(str), ilen);
1875 switch(ssl_get_error(ssl, nread)){
1876 case SSL_ERROR_NONE:
1878 goto end;
1879 case SSL_ERROR_ZERO_RETURN:
1881 if (no_exception_p(opts)) { return Qnil; }
1882 rb_eof_error();
1883 case SSL_ERROR_WANT_WRITE:
1884 if (nonblock) {
1886 if (no_exception_p(opts)) { return sym_wait_writable; }
1887 write_would_block(nonblock);
1888 }
1889 rb_io_wait_writable(fptr->fd);
1890 continue;
1891 case SSL_ERROR_WANT_READ:
1892 if (nonblock) {
1894 if (no_exception_p(opts)) { return sym_wait_readable; }
1895 read_would_block(nonblock);
1896 }
1897 rb_io_wait_readable(fptr->fd);
1898 continue;
1899 case SSL_ERROR_SYSCALL:
1900 if (!ERR_peek_error()) {
1902 if (errno)
1903 rb_sys_fail(0);
1904 else {
1905 /*
1906 * The underlying BIO returned 0. This is actually a
1907 * protocol error. But unfortunately, not all
1908 * implementations cleanly shutdown the TLS connection
1909 * but just shutdown/close the TCP connection. So report
1910 * EOF for now...
1911 */
1912 if (no_exception_p(opts)) { return Qnil; }
1913 rb_eof_error();
1914 }
1915 }
1916 /* fall through */
1917 default:
1919 ossl_raise(eSSLError, "SSL_read");
1920 }
1921 }
1922 }
1923 else {
1924 ID meth = nonblock ? rb_intern("read_nonblock") : rb_intern("sysread");
1925
1926 rb_warning("SSL session is not started yet.");
1927#if defined(RB_PASS_KEYWORDS)
1928 if (nonblock) {
1929 VALUE argv[3];
1930 argv[0] = len;
1931 argv[1] = str;
1932 argv[2] = opts;
1933 return rb_funcallv_kw(io, meth, 3, argv, RB_PASS_KEYWORDS);
1934 }
1935#else
1936 if (nonblock) {
1937 return rb_funcall(io, meth, 3, len, str, opts);
1938 }
1939#endif
1940 else
1941 return rb_funcall(io, meth, 2, len, str);
1942 }
1943
1944 end:
1945 rb_str_set_len(str, nread);
1946 return str;
1947}
1948
1949/*
1950 * call-seq:
1951 * ssl.sysread(length) => string
1952 * ssl.sysread(length, buffer) => buffer
1953 *
1954 * Reads _length_ bytes from the SSL connection. If a pre-allocated _buffer_
1955 * is provided the data will be written into it.
1956 */
1957static VALUE
1958ossl_ssl_read(int argc, VALUE *argv, VALUE self)
1959{
1960 return ossl_ssl_read_internal(argc, argv, self, 0);
1961}
1962
1963/*
1964 * call-seq:
1965 * ssl.sysread_nonblock(length) => string
1966 * ssl.sysread_nonblock(length, buffer) => buffer
1967 * ssl.sysread_nonblock(length[, buffer [, opts]) => buffer
1968 *
1969 * A non-blocking version of #sysread. Raises an SSLError if reading would
1970 * block. If "exception: false" is passed, this method returns a symbol of
1971 * :wait_readable, :wait_writable, or nil, rather than raising an exception.
1972 *
1973 * Reads _length_ bytes from the SSL connection. If a pre-allocated _buffer_
1974 * is provided the data will be written into it.
1975 */
1976static VALUE
1977ossl_ssl_read_nonblock(int argc, VALUE *argv, VALUE self)
1978{
1979 return ossl_ssl_read_internal(argc, argv, self, 1);
1980}
1981
1982static VALUE
1983ossl_ssl_write_internal(VALUE self, VALUE str, VALUE opts)
1984{
1985 SSL *ssl;
1986 int nwrite = 0;
1987 rb_io_t *fptr;
1988 int nonblock = opts != Qfalse;
1989 VALUE tmp, io;
1990
1992 GetSSL(self, ssl);
1993 io = rb_attr_get(self, id_i_io);
1994 GetOpenFile(io, fptr);
1995 if (ssl_started(ssl)) {
1996 for (;;) {
1997 int num = RSTRING_LENINT(tmp);
1998
1999 /* SSL_write(3ssl) manpage states num == 0 is undefined */
2000 if (num == 0)
2001 goto end;
2002
2003 nwrite = SSL_write(ssl, RSTRING_PTR(tmp), num);
2004 switch(ssl_get_error(ssl, nwrite)){
2005 case SSL_ERROR_NONE:
2006 goto end;
2007 case SSL_ERROR_WANT_WRITE:
2008 if (no_exception_p(opts)) { return sym_wait_writable; }
2009 write_would_block(nonblock);
2010 rb_io_wait_writable(fptr->fd);
2011 continue;
2012 case SSL_ERROR_WANT_READ:
2013 if (no_exception_p(opts)) { return sym_wait_readable; }
2014 read_would_block(nonblock);
2015 rb_io_wait_readable(fptr->fd);
2016 continue;
2017 case SSL_ERROR_SYSCALL:
2018#ifdef __APPLE__
2019 /*
2020 * It appears that send syscall can return EPROTOTYPE if the
2021 * socket is being torn down. Retry to get a proper errno to
2022 * make the error handling in line with the socket library.
2023 * [Bug #14713] https://bugs.ruby-lang.org/issues/14713
2024 */
2025 if (errno == EPROTOTYPE)
2026 continue;
2027#endif
2028 if (errno) rb_sys_fail(0);
2029 default:
2030 ossl_raise(eSSLError, "SSL_write");
2031 }
2032 }
2033 }
2034 else {
2035 ID meth = nonblock ?
2036 rb_intern("write_nonblock") : rb_intern("syswrite");
2037
2038 rb_warning("SSL session is not started yet.");
2039#if defined(RB_PASS_KEYWORDS)
2040 if (nonblock) {
2041 VALUE argv[2];
2042 argv[0] = str;
2043 argv[1] = opts;
2044 return rb_funcallv_kw(io, meth, 2, argv, RB_PASS_KEYWORDS);
2045 }
2046#else
2047 if (nonblock) {
2048 return rb_funcall(io, meth, 2, str, opts);
2049 }
2050#endif
2051 else
2052 return rb_funcall(io, meth, 1, str);
2053 }
2054
2055 end:
2056 return INT2NUM(nwrite);
2057}
2058
2059/*
2060 * call-seq:
2061 * ssl.syswrite(string) => Integer
2062 *
2063 * Writes _string_ to the SSL connection.
2064 */
2065static VALUE
2066ossl_ssl_write(VALUE self, VALUE str)
2067{
2068 return ossl_ssl_write_internal(self, str, Qfalse);
2069}
2070
2071/*
2072 * call-seq:
2073 * ssl.syswrite_nonblock(string) => Integer
2074 *
2075 * Writes _string_ to the SSL connection in a non-blocking manner. Raises an
2076 * SSLError if writing would block.
2077 */
2078static VALUE
2079ossl_ssl_write_nonblock(int argc, VALUE *argv, VALUE self)
2080{
2081 VALUE str, opts;
2082
2083 rb_scan_args(argc, argv, "1:", &str, &opts);
2084
2085 return ossl_ssl_write_internal(self, str, opts);
2086}
2087
2088/*
2089 * call-seq:
2090 * ssl.stop => nil
2091 *
2092 * Sends "close notify" to the peer and tries to shut down the SSL connection
2093 * gracefully.
2094 */
2095static VALUE
2096ossl_ssl_stop(VALUE self)
2097{
2098 SSL *ssl;
2099 int ret;
2100
2101 GetSSL(self, ssl);
2102 if (!ssl_started(ssl))
2103 return Qnil;
2104 ret = SSL_shutdown(ssl);
2105 if (ret == 1) /* Have already received close_notify */
2106 return Qnil;
2107 if (ret == 0) /* Sent close_notify, but we don't wait for reply */
2108 return Qnil;
2109
2110 /*
2111 * XXX: Something happened. Possibly it failed because the underlying socket
2112 * is not writable/readable, since it is in non-blocking mode. We should do
2113 * some proper error handling using SSL_get_error() and maybe retry, but we
2114 * can't block here. Give up for now.
2115 */
2117 return Qnil;
2118}
2119
2120/*
2121 * call-seq:
2122 * ssl.cert => cert or nil
2123 *
2124 * The X509 certificate for this socket endpoint.
2125 */
2126static VALUE
2127ossl_ssl_get_cert(VALUE self)
2128{
2129 SSL *ssl;
2130 X509 *cert = NULL;
2131
2132 GetSSL(self, ssl);
2133
2134 /*
2135 * Is this OpenSSL bug? Should add a ref?
2136 * TODO: Ask for.
2137 */
2138 cert = SSL_get_certificate(ssl); /* NO DUPs => DON'T FREE. */
2139
2140 if (!cert) {
2141 return Qnil;
2142 }
2143 return ossl_x509_new(cert);
2144}
2145
2146/*
2147 * call-seq:
2148 * ssl.peer_cert => cert or nil
2149 *
2150 * The X509 certificate for this socket's peer.
2151 */
2152static VALUE
2153ossl_ssl_get_peer_cert(VALUE self)
2154{
2155 SSL *ssl;
2156 X509 *cert = NULL;
2157 VALUE obj;
2158
2159 GetSSL(self, ssl);
2160
2161 cert = SSL_get_peer_certificate(ssl); /* Adds a ref => Safe to FREE. */
2162
2163 if (!cert) {
2164 return Qnil;
2165 }
2166 obj = ossl_x509_new(cert);
2167 X509_free(cert);
2168
2169 return obj;
2170}
2171
2172/*
2173 * call-seq:
2174 * ssl.peer_cert_chain => [cert, ...] or nil
2175 *
2176 * The X509 certificate chain for this socket's peer.
2177 */
2178static VALUE
2179ossl_ssl_get_peer_cert_chain(VALUE self)
2180{
2181 SSL *ssl;
2182 STACK_OF(X509) *chain;
2183 X509 *cert;
2184 VALUE ary;
2185 int i, num;
2186
2187 GetSSL(self, ssl);
2188
2189 chain = SSL_get_peer_cert_chain(ssl);
2190 if(!chain) return Qnil;
2191 num = sk_X509_num(chain);
2192 ary = rb_ary_new2(num);
2193 for (i = 0; i < num; i++){
2194 cert = sk_X509_value(chain, i);
2195 rb_ary_push(ary, ossl_x509_new(cert));
2196 }
2197
2198 return ary;
2199}
2200
2201/*
2202* call-seq:
2203* ssl.ssl_version => String
2204*
2205* Returns a String representing the SSL/TLS version that was negotiated
2206* for the connection, for example "TLSv1.2".
2207*/
2208static VALUE
2209ossl_ssl_get_version(VALUE self)
2210{
2211 SSL *ssl;
2212
2213 GetSSL(self, ssl);
2214
2215 return rb_str_new2(SSL_get_version(ssl));
2216}
2217
2218/*
2219 * call-seq:
2220 * ssl.cipher -> nil or [name, version, bits, alg_bits]
2221 *
2222 * Returns the cipher suite actually used in the current session, or nil if
2223 * no session has been established.
2224 */
2225static VALUE
2226ossl_ssl_get_cipher(VALUE self)
2227{
2228 SSL *ssl;
2229 const SSL_CIPHER *cipher;
2230
2231 GetSSL(self, ssl);
2232 cipher = SSL_get_current_cipher(ssl);
2233 return cipher ? ossl_ssl_cipher_to_ary(cipher) : Qnil;
2234}
2235
2236/*
2237 * call-seq:
2238 * ssl.state => string
2239 *
2240 * A description of the current connection state. This is for diagnostic
2241 * purposes only.
2242 */
2243static VALUE
2244ossl_ssl_get_state(VALUE self)
2245{
2246 SSL *ssl;
2247 VALUE ret;
2248
2249 GetSSL(self, ssl);
2250
2251 ret = rb_str_new2(SSL_state_string(ssl));
2252 if (ruby_verbose) {
2253 rb_str_cat2(ret, ": ");
2254 rb_str_cat2(ret, SSL_state_string_long(ssl));
2255 }
2256 return ret;
2257}
2258
2259/*
2260 * call-seq:
2261 * ssl.pending => Integer
2262 *
2263 * The number of bytes that are immediately available for reading.
2264 */
2265static VALUE
2266ossl_ssl_pending(VALUE self)
2267{
2268 SSL *ssl;
2269
2270 GetSSL(self, ssl);
2271
2272 return INT2NUM(SSL_pending(ssl));
2273}
2274
2275/*
2276 * call-seq:
2277 * ssl.session_reused? -> true | false
2278 *
2279 * Returns +true+ if a reused session was negotiated during the handshake.
2280 */
2281static VALUE
2282ossl_ssl_session_reused(VALUE self)
2283{
2284 SSL *ssl;
2285
2286 GetSSL(self, ssl);
2287
2288 return SSL_session_reused(ssl) ? Qtrue : Qfalse;
2289}
2290
2291/*
2292 * call-seq:
2293 * ssl.session = session -> session
2294 *
2295 * Sets the Session to be used when the connection is established.
2296 */
2297static VALUE
2298ossl_ssl_set_session(VALUE self, VALUE arg1)
2299{
2300 SSL *ssl;
2301 SSL_SESSION *sess;
2302
2303 GetSSL(self, ssl);
2304 GetSSLSession(arg1, sess);
2305
2306 if (SSL_set_session(ssl, sess) != 1)
2307 ossl_raise(eSSLError, "SSL_set_session");
2308
2309 return arg1;
2310}
2311
2312/*
2313 * call-seq:
2314 * ssl.hostname = hostname -> hostname
2315 *
2316 * Sets the server hostname used for SNI. This needs to be set before
2317 * SSLSocket#connect.
2318 */
2319static VALUE
2320ossl_ssl_set_hostname(VALUE self, VALUE arg)
2321{
2322 SSL *ssl;
2323 char *hostname = NULL;
2324
2325 GetSSL(self, ssl);
2326
2327 if (!NIL_P(arg))
2328 hostname = StringValueCStr(arg);
2329
2330 if (!SSL_set_tlsext_host_name(ssl, hostname))
2331 ossl_raise(eSSLError, NULL);
2332
2333 /* for SSLSocket#hostname */
2334 rb_ivar_set(self, id_i_hostname, arg);
2335
2336 return arg;
2337}
2338
2339/*
2340 * call-seq:
2341 * ssl.verify_result => Integer
2342 *
2343 * Returns the result of the peer certificates verification. See verify(1)
2344 * for error values and descriptions.
2345 *
2346 * If no peer certificate was presented X509_V_OK is returned.
2347 */
2348static VALUE
2349ossl_ssl_get_verify_result(VALUE self)
2350{
2351 SSL *ssl;
2352
2353 GetSSL(self, ssl);
2354
2355 return INT2NUM(SSL_get_verify_result(ssl));
2356}
2357
2358/*
2359 * call-seq:
2360 * ssl.client_ca => [x509name, ...]
2361 *
2362 * Returns the list of client CAs. Please note that in contrast to
2363 * SSLContext#client_ca= no array of X509::Certificate is returned but
2364 * X509::Name instances of the CA's subject distinguished name.
2365 *
2366 * In server mode, returns the list set by SSLContext#client_ca=.
2367 * In client mode, returns the list of client CAs sent from the server.
2368 */
2369static VALUE
2370ossl_ssl_get_client_ca_list(VALUE self)
2371{
2372 SSL *ssl;
2373 STACK_OF(X509_NAME) *ca;
2374
2375 GetSSL(self, ssl);
2376
2377 ca = SSL_get_client_CA_list(ssl);
2378 return ossl_x509name_sk2ary(ca);
2379}
2380
2381# ifndef OPENSSL_NO_NEXTPROTONEG
2382/*
2383 * call-seq:
2384 * ssl.npn_protocol => String | nil
2385 *
2386 * Returns the protocol string that was finally selected by the client
2387 * during the handshake.
2388 */
2389static VALUE
2390ossl_ssl_npn_protocol(VALUE self)
2391{
2392 SSL *ssl;
2393 const unsigned char *out;
2394 unsigned int outlen;
2395
2396 GetSSL(self, ssl);
2397
2398 SSL_get0_next_proto_negotiated(ssl, &out, &outlen);
2399 if (!outlen)
2400 return Qnil;
2401 else
2402 return rb_str_new((const char *) out, outlen);
2403}
2404# endif
2405
2406# ifdef HAVE_SSL_CTX_SET_ALPN_SELECT_CB
2407/*
2408 * call-seq:
2409 * ssl.alpn_protocol => String | nil
2410 *
2411 * Returns the ALPN protocol string that was finally selected by the server
2412 * during the handshake.
2413 */
2414static VALUE
2415ossl_ssl_alpn_protocol(VALUE self)
2416{
2417 SSL *ssl;
2418 const unsigned char *out;
2419 unsigned int outlen;
2420
2421 GetSSL(self, ssl);
2422
2423 SSL_get0_alpn_selected(ssl, &out, &outlen);
2424 if (!outlen)
2425 return Qnil;
2426 else
2427 return rb_str_new((const char *) out, outlen);
2428}
2429# endif
2430
2431# ifdef HAVE_SSL_GET_SERVER_TMP_KEY
2432/*
2433 * call-seq:
2434 * ssl.tmp_key => PKey or nil
2435 *
2436 * Returns the ephemeral key used in case of forward secrecy cipher.
2437 */
2438static VALUE
2439ossl_ssl_tmp_key(VALUE self)
2440{
2441 SSL *ssl;
2442 EVP_PKEY *key;
2443
2444 GetSSL(self, ssl);
2445 if (!SSL_get_server_tmp_key(ssl, &key))
2446 return Qnil;
2447 return ossl_pkey_new(key);
2448}
2449# endif /* defined(HAVE_SSL_GET_SERVER_TMP_KEY) */
2450#endif /* !defined(OPENSSL_NO_SOCK) */
2451
2452#undef rb_intern
2453#define rb_intern(s) rb_intern_const(s)
2454void
2456{
2457#if 0
2458 mOSSL = rb_define_module("OpenSSL");
2462#endif
2463
2464 id_call = rb_intern("call");
2465 ID_callback_state = rb_intern("callback_state");
2466
2467 ossl_ssl_ex_vcb_idx = SSL_get_ex_new_index(0, (void *)"ossl_ssl_ex_vcb_idx", 0, 0, 0);
2468 if (ossl_ssl_ex_vcb_idx < 0)
2469 ossl_raise(rb_eRuntimeError, "SSL_get_ex_new_index");
2470 ossl_ssl_ex_ptr_idx = SSL_get_ex_new_index(0, (void *)"ossl_ssl_ex_ptr_idx", 0, 0, 0);
2471 if (ossl_ssl_ex_ptr_idx < 0)
2472 ossl_raise(rb_eRuntimeError, "SSL_get_ex_new_index");
2473 ossl_sslctx_ex_ptr_idx = SSL_CTX_get_ex_new_index(0, (void *)"ossl_sslctx_ex_ptr_idx", 0, 0, 0);
2474 if (ossl_sslctx_ex_ptr_idx < 0)
2475 ossl_raise(rb_eRuntimeError, "SSL_CTX_get_ex_new_index");
2476#if !defined(HAVE_X509_STORE_UP_REF)
2477 ossl_sslctx_ex_store_p = SSL_CTX_get_ex_new_index(0, (void *)"ossl_sslctx_ex_store_p", 0, 0, 0);
2478 if (ossl_sslctx_ex_store_p < 0)
2479 ossl_raise(rb_eRuntimeError, "SSL_CTX_get_ex_new_index");
2480#endif
2481
2482 /* Document-module: OpenSSL::SSL
2483 *
2484 * Use SSLContext to set up the parameters for a TLS (former SSL)
2485 * connection. Both client and server TLS connections are supported,
2486 * SSLSocket and SSLServer may be used in conjunction with an instance
2487 * of SSLContext to set up connections.
2488 */
2490
2491 /* Document-module: OpenSSL::ExtConfig
2492 *
2493 * This module contains configuration information about the SSL extension,
2494 * for example if socket support is enabled, or the host name TLS extension
2495 * is enabled. Constants in this module will always be defined, but contain
2496 * +true+ or +false+ values depending on the configuration of your OpenSSL
2497 * installation.
2498 */
2499 mSSLExtConfig = rb_define_module_under(mOSSL, "ExtConfig");
2500
2501 /* Document-class: OpenSSL::SSL::SSLError
2502 *
2503 * Generic error class raised by SSLSocket and SSLContext.
2504 */
2505 eSSLError = rb_define_class_under(mSSL, "SSLError", eOSSLError);
2506 eSSLErrorWaitReadable = rb_define_class_under(mSSL, "SSLErrorWaitReadable", eSSLError);
2507 rb_include_module(eSSLErrorWaitReadable, rb_mWaitReadable);
2508 eSSLErrorWaitWritable = rb_define_class_under(mSSL, "SSLErrorWaitWritable", eSSLError);
2509 rb_include_module(eSSLErrorWaitWritable, rb_mWaitWritable);
2510
2512
2513 /* Document-class: OpenSSL::SSL::SSLContext
2514 *
2515 * An SSLContext is used to set various options regarding certificates,
2516 * algorithms, verification, session caching, etc. The SSLContext is
2517 * used to create an SSLSocket.
2518 *
2519 * All attributes must be set before creating an SSLSocket as the
2520 * SSLContext will be frozen afterward.
2521 */
2523 rb_define_alloc_func(cSSLContext, ossl_sslctx_s_alloc);
2524 rb_undef_method(cSSLContext, "initialize_copy");
2525
2526 /*
2527 * Context certificate
2528 *
2529 * The _cert_, _key_, and _extra_chain_cert_ attributes are deprecated.
2530 * It is recommended to use #add_certificate instead.
2531 */
2532 rb_attr(cSSLContext, rb_intern("cert"), 1, 1, Qfalse);
2533
2534 /*
2535 * Context private key
2536 *
2537 * The _cert_, _key_, and _extra_chain_cert_ attributes are deprecated.
2538 * It is recommended to use #add_certificate instead.
2539 */
2540 rb_attr(cSSLContext, rb_intern("key"), 1, 1, Qfalse);
2541
2542 /*
2543 * A certificate or Array of certificates that will be sent to the client.
2544 */
2545 rb_attr(cSSLContext, rb_intern("client_ca"), 1, 1, Qfalse);
2546
2547 /*
2548 * The path to a file containing a PEM-format CA certificate
2549 */
2550 rb_attr(cSSLContext, rb_intern("ca_file"), 1, 1, Qfalse);
2551
2552 /*
2553 * The path to a directory containing CA certificates in PEM format.
2554 *
2555 * Files are looked up by subject's X509 name's hash value.
2556 */
2557 rb_attr(cSSLContext, rb_intern("ca_path"), 1, 1, Qfalse);
2558
2559 /*
2560 * Maximum session lifetime in seconds.
2561 */
2562 rb_attr(cSSLContext, rb_intern("timeout"), 1, 1, Qfalse);
2563
2564 /*
2565 * Session verification mode.
2566 *
2567 * Valid modes are VERIFY_NONE, VERIFY_PEER, VERIFY_CLIENT_ONCE,
2568 * VERIFY_FAIL_IF_NO_PEER_CERT and defined on OpenSSL::SSL
2569 *
2570 * The default mode is VERIFY_NONE, which does not perform any verification
2571 * at all.
2572 *
2573 * See SSL_CTX_set_verify(3) for details.
2574 */
2575 rb_attr(cSSLContext, rb_intern("verify_mode"), 1, 1, Qfalse);
2576
2577 /*
2578 * Number of CA certificates to walk when verifying a certificate chain.
2579 */
2580 rb_attr(cSSLContext, rb_intern("verify_depth"), 1, 1, Qfalse);
2581
2582 /*
2583 * A callback for additional certificate verification. The callback is
2584 * invoked for each certificate in the chain.
2585 *
2586 * The callback is invoked with two values. _preverify_ok_ indicates
2587 * indicates if the verification was passed (+true+) or not (+false+).
2588 * _store_context_ is an OpenSSL::X509::StoreContext containing the
2589 * context used for certificate verification.
2590 *
2591 * If the callback returns +false+, the chain verification is immediately
2592 * stopped and a bad_certificate alert is then sent.
2593 */
2594 rb_attr(cSSLContext, rb_intern("verify_callback"), 1, 1, Qfalse);
2595
2596 /*
2597 * Whether to check the server certificate is valid for the hostname.
2598 *
2599 * In order to make this work, verify_mode must be set to VERIFY_PEER and
2600 * the server hostname must be given by OpenSSL::SSL::SSLSocket#hostname=.
2601 */
2602 rb_attr(cSSLContext, rb_intern("verify_hostname"), 1, 1, Qfalse);
2603
2604 /*
2605 * An OpenSSL::X509::Store used for certificate verification.
2606 */
2607 rb_attr(cSSLContext, rb_intern("cert_store"), 1, 1, Qfalse);
2608
2609 /*
2610 * An Array of extra X509 certificates to be added to the certificate
2611 * chain.
2612 *
2613 * The _cert_, _key_, and _extra_chain_cert_ attributes are deprecated.
2614 * It is recommended to use #add_certificate instead.
2615 */
2616 rb_attr(cSSLContext, rb_intern("extra_chain_cert"), 1, 1, Qfalse);
2617
2618 /*
2619 * A callback invoked when a client certificate is requested by a server
2620 * and no certificate has been set.
2621 *
2622 * The callback is invoked with a Session and must return an Array
2623 * containing an OpenSSL::X509::Certificate and an OpenSSL::PKey. If any
2624 * other value is returned the handshake is suspended.
2625 */
2626 rb_attr(cSSLContext, rb_intern("client_cert_cb"), 1, 1, Qfalse);
2627
2628#if !defined(OPENSSL_NO_EC) && defined(HAVE_SSL_CTX_SET_TMP_ECDH_CALLBACK)
2629 /*
2630 * A callback invoked when ECDH parameters are required.
2631 *
2632 * The callback is invoked with the Session for the key exchange, an
2633 * flag indicating the use of an export cipher and the keylength
2634 * required.
2635 *
2636 * The callback is deprecated. This does not work with recent versions of
2637 * OpenSSL. Use OpenSSL::SSL::SSLContext#ecdh_curves= instead.
2638 */
2639 rb_attr(cSSLContext, rb_intern("tmp_ecdh_callback"), 1, 1, Qfalse);
2640#endif
2641
2642 /*
2643 * Sets the context in which a session can be reused. This allows
2644 * sessions for multiple applications to be distinguished, for example, by
2645 * name.
2646 */
2647 rb_attr(cSSLContext, rb_intern("session_id_context"), 1, 1, Qfalse);
2648
2649 /*
2650 * A callback invoked on a server when a session is proposed by the client
2651 * but the session could not be found in the server's internal cache.
2652 *
2653 * The callback is invoked with the SSLSocket and session id. The
2654 * callback may return a Session from an external cache.
2655 */
2656 rb_attr(cSSLContext, rb_intern("session_get_cb"), 1, 1, Qfalse);
2657
2658 /*
2659 * A callback invoked when a new session was negotiated.
2660 *
2661 * The callback is invoked with an SSLSocket. If +false+ is returned the
2662 * session will be removed from the internal cache.
2663 */
2664 rb_attr(cSSLContext, rb_intern("session_new_cb"), 1, 1, Qfalse);
2665
2666 /*
2667 * A callback invoked when a session is removed from the internal cache.
2668 *
2669 * The callback is invoked with an SSLContext and a Session.
2670 *
2671 * IMPORTANT NOTE: It is currently not possible to use this safely in a
2672 * multi-threaded application. The callback is called inside a global lock
2673 * and it can randomly cause deadlock on Ruby thread switching.
2674 */
2675 rb_attr(cSSLContext, rb_intern("session_remove_cb"), 1, 1, Qfalse);
2676
2677 rb_define_const(mSSLExtConfig, "HAVE_TLSEXT_HOST_NAME", Qtrue);
2678
2679 /*
2680 * A callback invoked whenever a new handshake is initiated. May be used
2681 * to disable renegotiation entirely.
2682 *
2683 * The callback is invoked with the active SSLSocket. The callback's
2684 * return value is irrelevant, normal return indicates "approval" of the
2685 * renegotiation and will continue the process. To forbid renegotiation
2686 * and to cancel the process, an Error may be raised within the callback.
2687 *
2688 * === Disable client renegotiation
2689 *
2690 * When running a server, it is often desirable to disable client
2691 * renegotiation entirely. You may use a callback as follows to implement
2692 * this feature:
2693 *
2694 * num_handshakes = 0
2695 * ctx.renegotiation_cb = lambda do |ssl|
2696 * num_handshakes += 1
2697 * raise RuntimeError.new("Client renegotiation disabled") if num_handshakes > 1
2698 * end
2699 */
2700 rb_attr(cSSLContext, rb_intern("renegotiation_cb"), 1, 1, Qfalse);
2701#ifndef OPENSSL_NO_NEXTPROTONEG
2702 /*
2703 * An Enumerable of Strings. Each String represents a protocol to be
2704 * advertised as the list of supported protocols for Next Protocol
2705 * Negotiation. Supported in OpenSSL 1.0.1 and higher. Has no effect
2706 * on the client side. If not set explicitly, the NPN extension will
2707 * not be sent by the server in the handshake.
2708 *
2709 * === Example
2710 *
2711 * ctx.npn_protocols = ["http/1.1", "spdy/2"]
2712 */
2713 rb_attr(cSSLContext, rb_intern("npn_protocols"), 1, 1, Qfalse);
2714 /*
2715 * A callback invoked on the client side when the client needs to select
2716 * a protocol from the list sent by the server. Supported in OpenSSL 1.0.1
2717 * and higher. The client MUST select a protocol of those advertised by
2718 * the server. If none is acceptable, raising an error in the callback
2719 * will cause the handshake to fail. Not setting this callback explicitly
2720 * means not supporting the NPN extension on the client - any protocols
2721 * advertised by the server will be ignored.
2722 *
2723 * === Example
2724 *
2725 * ctx.npn_select_cb = lambda do |protocols|
2726 * # inspect the protocols and select one
2727 * protocols.first
2728 * end
2729 */
2730 rb_attr(cSSLContext, rb_intern("npn_select_cb"), 1, 1, Qfalse);
2731#endif
2732
2733#ifdef HAVE_SSL_CTX_SET_ALPN_SELECT_CB
2734 /*
2735 * An Enumerable of Strings. Each String represents a protocol to be
2736 * advertised as the list of supported protocols for Application-Layer
2737 * Protocol Negotiation. Supported in OpenSSL 1.0.2 and higher. Has no
2738 * effect on the server side. If not set explicitly, the ALPN extension will
2739 * not be included in the handshake.
2740 *
2741 * === Example
2742 *
2743 * ctx.alpn_protocols = ["http/1.1", "spdy/2", "h2"]
2744 */
2745 rb_attr(cSSLContext, rb_intern("alpn_protocols"), 1, 1, Qfalse);
2746 /*
2747 * A callback invoked on the server side when the server needs to select
2748 * a protocol from the list sent by the client. Supported in OpenSSL 1.0.2
2749 * and higher. The callback must return a protocol of those advertised by
2750 * the client. If none is acceptable, raising an error in the callback
2751 * will cause the handshake to fail. Not setting this callback explicitly
2752 * means not supporting the ALPN extension on the server - any protocols
2753 * advertised by the client will be ignored.
2754 *
2755 * === Example
2756 *
2757 * ctx.alpn_select_cb = lambda do |protocols|
2758 * # inspect the protocols and select one
2759 * protocols.first
2760 * end
2761 */
2762 rb_attr(cSSLContext, rb_intern("alpn_select_cb"), 1, 1, Qfalse);
2763#endif
2764
2765 rb_define_alias(cSSLContext, "ssl_timeout", "timeout");
2766 rb_define_alias(cSSLContext, "ssl_timeout=", "timeout=");
2767 rb_define_private_method(cSSLContext, "set_minmax_proto_version",
2768 ossl_sslctx_set_minmax_proto_version, 2);
2769 rb_define_method(cSSLContext, "ciphers", ossl_sslctx_get_ciphers, 0);
2770 rb_define_method(cSSLContext, "ciphers=", ossl_sslctx_set_ciphers, 1);
2771 rb_define_method(cSSLContext, "ecdh_curves=", ossl_sslctx_set_ecdh_curves, 1);
2772 rb_define_method(cSSLContext, "security_level", ossl_sslctx_get_security_level, 0);
2773 rb_define_method(cSSLContext, "security_level=", ossl_sslctx_set_security_level, 1);
2774#ifdef SSL_MODE_SEND_FALLBACK_SCSV
2775 rb_define_method(cSSLContext, "enable_fallback_scsv", ossl_sslctx_enable_fallback_scsv, 0);
2776#endif
2777 rb_define_method(cSSLContext, "add_certificate", ossl_sslctx_add_certificate, -1);
2778
2779 rb_define_method(cSSLContext, "setup", ossl_sslctx_setup, 0);
2780 rb_define_alias(cSSLContext, "freeze", "setup");
2781
2782 /*
2783 * No session caching for client or server
2784 */
2785 rb_define_const(cSSLContext, "SESSION_CACHE_OFF", LONG2NUM(SSL_SESS_CACHE_OFF));
2786
2787 /*
2788 * Client sessions are added to the session cache
2789 */
2790 rb_define_const(cSSLContext, "SESSION_CACHE_CLIENT", LONG2NUM(SSL_SESS_CACHE_CLIENT)); /* doesn't actually do anything in 0.9.8e */
2791
2792 /*
2793 * Server sessions are added to the session cache
2794 */
2795 rb_define_const(cSSLContext, "SESSION_CACHE_SERVER", LONG2NUM(SSL_SESS_CACHE_SERVER));
2796
2797 /*
2798 * Both client and server sessions are added to the session cache
2799 */
2800 rb_define_const(cSSLContext, "SESSION_CACHE_BOTH", LONG2NUM(SSL_SESS_CACHE_BOTH)); /* no different than CACHE_SERVER in 0.9.8e */
2801
2802 /*
2803 * Normally the session cache is checked for expired sessions every 255
2804 * connections. Since this may lead to a delay that cannot be controlled,
2805 * the automatic flushing may be disabled and #flush_sessions can be
2806 * called explicitly.
2807 */
2808 rb_define_const(cSSLContext, "SESSION_CACHE_NO_AUTO_CLEAR", LONG2NUM(SSL_SESS_CACHE_NO_AUTO_CLEAR));
2809
2810 /*
2811 * Always perform external lookups of sessions even if they are in the
2812 * internal cache.
2813 *
2814 * This flag has no effect on clients
2815 */
2816 rb_define_const(cSSLContext, "SESSION_CACHE_NO_INTERNAL_LOOKUP", LONG2NUM(SSL_SESS_CACHE_NO_INTERNAL_LOOKUP));
2817
2818 /*
2819 * Never automatically store sessions in the internal store.
2820 */
2821 rb_define_const(cSSLContext, "SESSION_CACHE_NO_INTERNAL_STORE", LONG2NUM(SSL_SESS_CACHE_NO_INTERNAL_STORE));
2822
2823 /*
2824 * Enables both SESSION_CACHE_NO_INTERNAL_LOOKUP and
2825 * SESSION_CACHE_NO_INTERNAL_STORE.
2826 */
2827 rb_define_const(cSSLContext, "SESSION_CACHE_NO_INTERNAL", LONG2NUM(SSL_SESS_CACHE_NO_INTERNAL));
2828
2829 rb_define_method(cSSLContext, "session_add", ossl_sslctx_session_add, 1);
2830 rb_define_method(cSSLContext, "session_remove", ossl_sslctx_session_remove, 1);
2831 rb_define_method(cSSLContext, "session_cache_mode", ossl_sslctx_get_session_cache_mode, 0);
2832 rb_define_method(cSSLContext, "session_cache_mode=", ossl_sslctx_set_session_cache_mode, 1);
2833 rb_define_method(cSSLContext, "session_cache_size", ossl_sslctx_get_session_cache_size, 0);
2834 rb_define_method(cSSLContext, "session_cache_size=", ossl_sslctx_set_session_cache_size, 1);
2835 rb_define_method(cSSLContext, "session_cache_stats", ossl_sslctx_get_session_cache_stats, 0);
2836 rb_define_method(cSSLContext, "flush_sessions", ossl_sslctx_flush_sessions, -1);
2837 rb_define_method(cSSLContext, "options", ossl_sslctx_get_options, 0);
2838 rb_define_method(cSSLContext, "options=", ossl_sslctx_set_options, 1);
2839
2840 /*
2841 * Document-class: OpenSSL::SSL::SSLSocket
2842 */
2844#ifdef OPENSSL_NO_SOCK
2845 rb_define_const(mSSLExtConfig, "OPENSSL_NO_SOCK", Qtrue);
2846 rb_define_method(cSSLSocket, "initialize", rb_f_notimplement, -1);
2847#else
2848 rb_define_const(mSSLExtConfig, "OPENSSL_NO_SOCK", Qfalse);
2849 rb_define_alloc_func(cSSLSocket, ossl_ssl_s_alloc);
2850 rb_define_method(cSSLSocket, "initialize", ossl_ssl_initialize, -1);
2851 rb_undef_method(cSSLSocket, "initialize_copy");
2852 rb_define_method(cSSLSocket, "connect", ossl_ssl_connect, 0);
2853 rb_define_method(cSSLSocket, "connect_nonblock", ossl_ssl_connect_nonblock, -1);
2854 rb_define_method(cSSLSocket, "accept", ossl_ssl_accept, 0);
2855 rb_define_method(cSSLSocket, "accept_nonblock", ossl_ssl_accept_nonblock, -1);
2856 rb_define_method(cSSLSocket, "sysread", ossl_ssl_read, -1);
2857 rb_define_private_method(cSSLSocket, "sysread_nonblock", ossl_ssl_read_nonblock, -1);
2858 rb_define_method(cSSLSocket, "syswrite", ossl_ssl_write, 1);
2859 rb_define_private_method(cSSLSocket, "syswrite_nonblock", ossl_ssl_write_nonblock, -1);
2860 rb_define_private_method(cSSLSocket, "stop", ossl_ssl_stop, 0);
2861 rb_define_method(cSSLSocket, "cert", ossl_ssl_get_cert, 0);
2862 rb_define_method(cSSLSocket, "peer_cert", ossl_ssl_get_peer_cert, 0);
2863 rb_define_method(cSSLSocket, "peer_cert_chain", ossl_ssl_get_peer_cert_chain, 0);
2864 rb_define_method(cSSLSocket, "ssl_version", ossl_ssl_get_version, 0);
2865 rb_define_method(cSSLSocket, "cipher", ossl_ssl_get_cipher, 0);
2866 rb_define_method(cSSLSocket, "state", ossl_ssl_get_state, 0);
2867 rb_define_method(cSSLSocket, "pending", ossl_ssl_pending, 0);
2868 rb_define_method(cSSLSocket, "session_reused?", ossl_ssl_session_reused, 0);
2869 /* implementation of OpenSSL::SSL::SSLSocket#session is in lib/openssl/ssl.rb */
2870 rb_define_method(cSSLSocket, "session=", ossl_ssl_set_session, 1);
2871 rb_define_method(cSSLSocket, "verify_result", ossl_ssl_get_verify_result, 0);
2872 rb_define_method(cSSLSocket, "client_ca", ossl_ssl_get_client_ca_list, 0);
2873 /* #hostname is defined in lib/openssl/ssl.rb */
2874 rb_define_method(cSSLSocket, "hostname=", ossl_ssl_set_hostname, 1);
2875# ifdef HAVE_SSL_GET_SERVER_TMP_KEY
2876 rb_define_method(cSSLSocket, "tmp_key", ossl_ssl_tmp_key, 0);
2877# endif
2878# ifdef HAVE_SSL_CTX_SET_ALPN_SELECT_CB
2879 rb_define_method(cSSLSocket, "alpn_protocol", ossl_ssl_alpn_protocol, 0);
2880# endif
2881# ifndef OPENSSL_NO_NEXTPROTONEG
2882 rb_define_method(cSSLSocket, "npn_protocol", ossl_ssl_npn_protocol, 0);
2883# endif
2884#endif
2885
2886 rb_define_const(mSSL, "VERIFY_NONE", INT2NUM(SSL_VERIFY_NONE));
2887 rb_define_const(mSSL, "VERIFY_PEER", INT2NUM(SSL_VERIFY_PEER));
2888 rb_define_const(mSSL, "VERIFY_FAIL_IF_NO_PEER_CERT", INT2NUM(SSL_VERIFY_FAIL_IF_NO_PEER_CERT));
2889 rb_define_const(mSSL, "VERIFY_CLIENT_ONCE", INT2NUM(SSL_VERIFY_CLIENT_ONCE));
2890
2891 rb_define_const(mSSL, "OP_ALL", ULONG2NUM(SSL_OP_ALL));
2892 rb_define_const(mSSL, "OP_LEGACY_SERVER_CONNECT", ULONG2NUM(SSL_OP_LEGACY_SERVER_CONNECT));
2893#ifdef SSL_OP_TLSEXT_PADDING /* OpenSSL 1.0.1h and OpenSSL 1.0.2 */
2894 rb_define_const(mSSL, "OP_TLSEXT_PADDING", ULONG2NUM(SSL_OP_TLSEXT_PADDING));
2895#endif
2896#ifdef SSL_OP_SAFARI_ECDHE_ECDSA_BUG /* OpenSSL 1.0.1f and OpenSSL 1.0.2 */
2897 rb_define_const(mSSL, "OP_SAFARI_ECDHE_ECDSA_BUG", ULONG2NUM(SSL_OP_SAFARI_ECDHE_ECDSA_BUG));
2898#endif
2899#ifdef SSL_OP_ALLOW_NO_DHE_KEX /* OpenSSL 1.1.1 */
2900 rb_define_const(mSSL, "OP_ALLOW_NO_DHE_KEX", ULONG2NUM(SSL_OP_ALLOW_NO_DHE_KEX));
2901#endif
2902 rb_define_const(mSSL, "OP_DONT_INSERT_EMPTY_FRAGMENTS", ULONG2NUM(SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS));
2903 rb_define_const(mSSL, "OP_NO_TICKET", ULONG2NUM(SSL_OP_NO_TICKET));
2904 rb_define_const(mSSL, "OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION", ULONG2NUM(SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION));
2905 rb_define_const(mSSL, "OP_NO_COMPRESSION", ULONG2NUM(SSL_OP_NO_COMPRESSION));
2906 rb_define_const(mSSL, "OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION", ULONG2NUM(SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION));
2907#ifdef SSL_OP_NO_ENCRYPT_THEN_MAC /* OpenSSL 1.1.1 */
2908 rb_define_const(mSSL, "OP_NO_ENCRYPT_THEN_MAC", ULONG2NUM(SSL_OP_NO_ENCRYPT_THEN_MAC));
2909#endif
2910 rb_define_const(mSSL, "OP_CIPHER_SERVER_PREFERENCE", ULONG2NUM(SSL_OP_CIPHER_SERVER_PREFERENCE));
2911 rb_define_const(mSSL, "OP_TLS_ROLLBACK_BUG", ULONG2NUM(SSL_OP_TLS_ROLLBACK_BUG));
2912#ifdef SSL_OP_NO_RENEGOTIATION /* OpenSSL 1.1.1 */
2913 rb_define_const(mSSL, "OP_NO_RENEGOTIATION", ULONG2NUM(SSL_OP_NO_RENEGOTIATION));
2914#endif
2915 rb_define_const(mSSL, "OP_CRYPTOPRO_TLSEXT_BUG", ULONG2NUM(SSL_OP_CRYPTOPRO_TLSEXT_BUG));
2916
2917 rb_define_const(mSSL, "OP_NO_SSLv3", ULONG2NUM(SSL_OP_NO_SSLv3));
2918 rb_define_const(mSSL, "OP_NO_TLSv1", ULONG2NUM(SSL_OP_NO_TLSv1));
2919 rb_define_const(mSSL, "OP_NO_TLSv1_1", ULONG2NUM(SSL_OP_NO_TLSv1_1));
2920 rb_define_const(mSSL, "OP_NO_TLSv1_2", ULONG2NUM(SSL_OP_NO_TLSv1_2));
2921#ifdef SSL_OP_NO_TLSv1_3 /* OpenSSL 1.1.1 */
2922 rb_define_const(mSSL, "OP_NO_TLSv1_3", ULONG2NUM(SSL_OP_NO_TLSv1_3));
2923#endif
2924
2925 /* SSL_OP_* flags for DTLS */
2926#if 0
2927 rb_define_const(mSSL, "OP_NO_QUERY_MTU", ULONG2NUM(SSL_OP_NO_QUERY_MTU));
2928 rb_define_const(mSSL, "OP_COOKIE_EXCHANGE", ULONG2NUM(SSL_OP_COOKIE_EXCHANGE));
2929 rb_define_const(mSSL, "OP_CISCO_ANYCONNECT", ULONG2NUM(SSL_OP_CISCO_ANYCONNECT));
2930#endif
2931
2932 /* Deprecated in OpenSSL 1.1.0. */
2933 rb_define_const(mSSL, "OP_MICROSOFT_SESS_ID_BUG", ULONG2NUM(SSL_OP_MICROSOFT_SESS_ID_BUG));
2934 /* Deprecated in OpenSSL 1.1.0. */
2935 rb_define_const(mSSL, "OP_NETSCAPE_CHALLENGE_BUG", ULONG2NUM(SSL_OP_NETSCAPE_CHALLENGE_BUG));
2936 /* Deprecated in OpenSSL 0.9.8q and 1.0.0c. */
2937 rb_define_const(mSSL, "OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG", ULONG2NUM(SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG));
2938 /* Deprecated in OpenSSL 1.0.1h and 1.0.2. */
2939 rb_define_const(mSSL, "OP_SSLREF2_REUSE_CERT_TYPE_BUG", ULONG2NUM(SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG));
2940 /* Deprecated in OpenSSL 1.1.0. */
2941 rb_define_const(mSSL, "OP_MICROSOFT_BIG_SSLV3_BUFFER", ULONG2NUM(SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER));
2942 /* Deprecated in OpenSSL 0.9.7h and 0.9.8b. */
2943 rb_define_const(mSSL, "OP_MSIE_SSLV2_RSA_PADDING", ULONG2NUM(SSL_OP_MSIE_SSLV2_RSA_PADDING));
2944 /* Deprecated in OpenSSL 1.1.0. */
2945 rb_define_const(mSSL, "OP_SSLEAY_080_CLIENT_DH_BUG", ULONG2NUM(SSL_OP_SSLEAY_080_CLIENT_DH_BUG));
2946 /* Deprecated in OpenSSL 1.1.0. */
2947 rb_define_const(mSSL, "OP_TLS_D5_BUG", ULONG2NUM(SSL_OP_TLS_D5_BUG));
2948 /* Deprecated in OpenSSL 1.1.0. */
2949 rb_define_const(mSSL, "OP_TLS_BLOCK_PADDING_BUG", ULONG2NUM(SSL_OP_TLS_BLOCK_PADDING_BUG));
2950 /* Deprecated in OpenSSL 1.1.0. */
2951 rb_define_const(mSSL, "OP_SINGLE_ECDH_USE", ULONG2NUM(SSL_OP_SINGLE_ECDH_USE));
2952 /* Deprecated in OpenSSL 1.1.0. */
2953 rb_define_const(mSSL, "OP_SINGLE_DH_USE", ULONG2NUM(SSL_OP_SINGLE_DH_USE));
2954 /* Deprecated in OpenSSL 1.0.1k and 1.0.2. */
2955 rb_define_const(mSSL, "OP_EPHEMERAL_RSA", ULONG2NUM(SSL_OP_EPHEMERAL_RSA));
2956 /* Deprecated in OpenSSL 1.1.0. */
2957 rb_define_const(mSSL, "OP_NO_SSLv2", ULONG2NUM(SSL_OP_NO_SSLv2));
2958 /* Deprecated in OpenSSL 1.0.1. */
2959 rb_define_const(mSSL, "OP_PKCS1_CHECK_1", ULONG2NUM(SSL_OP_PKCS1_CHECK_1));
2960 /* Deprecated in OpenSSL 1.0.1. */
2961 rb_define_const(mSSL, "OP_PKCS1_CHECK_2", ULONG2NUM(SSL_OP_PKCS1_CHECK_2));
2962 /* Deprecated in OpenSSL 1.1.0. */
2963 rb_define_const(mSSL, "OP_NETSCAPE_CA_DN_BUG", ULONG2NUM(SSL_OP_NETSCAPE_CA_DN_BUG));
2964 /* Deprecated in OpenSSL 1.1.0. */
2965 rb_define_const(mSSL, "OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG", ULONG2NUM(SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG));
2966
2967
2968 /*
2969 * SSL/TLS version constants. Used by SSLContext#min_version= and
2970 * #max_version=
2971 */
2972 /* SSL 2.0 */
2973 rb_define_const(mSSL, "SSL2_VERSION", INT2NUM(SSL2_VERSION));
2974 /* SSL 3.0 */
2975 rb_define_const(mSSL, "SSL3_VERSION", INT2NUM(SSL3_VERSION));
2976 /* TLS 1.0 */
2977 rb_define_const(mSSL, "TLS1_VERSION", INT2NUM(TLS1_VERSION));
2978 /* TLS 1.1 */
2979 rb_define_const(mSSL, "TLS1_1_VERSION", INT2NUM(TLS1_1_VERSION));
2980 /* TLS 1.2 */
2981 rb_define_const(mSSL, "TLS1_2_VERSION", INT2NUM(TLS1_2_VERSION));
2982#ifdef TLS1_3_VERSION /* OpenSSL 1.1.1 */
2983 /* TLS 1.3 */
2984 rb_define_const(mSSL, "TLS1_3_VERSION", INT2NUM(TLS1_3_VERSION));
2985#endif
2986
2987
2988 sym_exception = ID2SYM(rb_intern("exception"));
2989 sym_wait_readable = ID2SYM(rb_intern("wait_readable"));
2990 sym_wait_writable = ID2SYM(rb_intern("wait_writable"));
2991
2992 id_tmp_dh_callback = rb_intern("tmp_dh_callback");
2993 id_tmp_ecdh_callback = rb_intern("tmp_ecdh_callback");
2994 id_npn_protocols_encoded = rb_intern("npn_protocols_encoded");
2995 id_each = rb_intern_const("each");
2996
2997#define DefIVarID(name) do \
2998 id_i_##name = rb_intern("@"#name); while (0)
2999
3000 DefIVarID(cert_store);
3001 DefIVarID(ca_file);
3002 DefIVarID(ca_path);
3003 DefIVarID(verify_mode);
3004 DefIVarID(verify_depth);
3005 DefIVarID(verify_callback);
3006 DefIVarID(client_ca);
3007 DefIVarID(renegotiation_cb);
3008 DefIVarID(cert);
3009 DefIVarID(key);
3010 DefIVarID(extra_chain_cert);
3011 DefIVarID(client_cert_cb);
3012 DefIVarID(tmp_ecdh_callback);
3013 DefIVarID(timeout);
3014 DefIVarID(session_id_context);
3015 DefIVarID(session_get_cb);
3016 DefIVarID(session_new_cb);
3017 DefIVarID(session_remove_cb);
3018 DefIVarID(npn_select_cb);
3019 DefIVarID(npn_protocols);
3020 DefIVarID(alpn_protocols);
3021 DefIVarID(alpn_select_cb);
3022 DefIVarID(servername_cb);
3023 DefIVarID(verify_hostname);
3024
3025 DefIVarID(io);
3026 DefIVarID(context);
3027 DefIVarID(hostname);
3028}
int errno
struct RIMemo * ptr
Definition: debug.c:65
#define id_each
Definition: enum.c:25
char str[HTML_ESCAPE_MAX_LEN+1]
Definition: escape.c:18
ID id_call
Definition: eventids1.c:30
int rb_during_gc(void)
Definition: gc.c:8703
void rb_include_module(VALUE, VALUE)
Definition: class.c:882
VALUE rb_define_class_under(VALUE, const char *, VALUE)
Defines a class under the namespace of outer.
Definition: class.c:711
VALUE rb_define_module(const char *)
Definition: class.c:785
VALUE rb_define_module_under(VALUE, const char *)
Definition: class.c:810
void rb_undef_method(VALUE, const char *)
Definition: class.c:1593
void rb_define_alias(VALUE, const char *, const char *)
Defines an alias of a method.
Definition: class.c:1818
VALUE rb_cObject
Object class.
Definition: ruby.h:2012
VALUE rb_cTime
Definition: ruby.h:2050
VALUE rb_mWaitWritable
Definition: ruby.h:2009
VALUE rb_mWaitReadable
Definition: ruby.h:2008
VALUE rb_cIO
Definition: ruby.h:2032
void rb_raise(VALUE exc, const char *fmt,...)
Definition: error.c:2671
VALUE rb_eNotImpError
Definition: error.c:934
VALUE rb_eStandardError
Definition: error.c:921
VALUE rb_protect(VALUE(*)(VALUE), VALUE, int *)
Protects a function call from potential global escapes from the function.
Definition: eval.c:1072
VALUE rb_eRuntimeError
Definition: error.c:922
void rb_warn(const char *fmt,...)
Definition: error.c:315
VALUE rb_eArgError
Definition: error.c:925
void rb_jump_tag(int tag)
Continues the exception caught by rb_protect() and rb_eval_string_protect().
Definition: eval.c:884
void rb_sys_fail(const char *mesg)
Definition: error.c:2795
VALUE rb_obj_alloc(VALUE)
Allocates an instance of klass.
Definition: object.c:1895
VALUE rb_obj_is_instance_of(VALUE, VALUE)
Determines if obj is an instance of c.
Definition: object.c:675
VALUE rb_obj_is_kind_of(VALUE, VALUE)
Determines if obj is a kind of c.
Definition: object.c:692
VALUE rb_obj_freeze(VALUE)
Make the object unmodifiable.
Definition: object.c:1080
VALUE rb_String(VALUE)
Equivalent to Kernel#String in Ruby.
Definition: object.c:3652
#define no_exception_p(opts)
Definition: io.c:2803
void rb_eof_error(void)
Definition: io.c:697
void rb_io_check_writable(rb_io_t *)
Definition: io.c:923
void rb_io_check_readable(rb_io_t *)
Definition: io.c:899
#define GetOpenFile(obj, fp)
Definition: io.h:127
int rb_io_wait_readable(int)
Definition: io.c:1204
int rb_io_wait_writable(int)
Definition: io.c:1228
const char * name
Definition: nkf.c:208
int nid
#define SSL_is_server(s)
#define SSL_SESSION_up_ref(x)
#define EC_curve_nist2nid
#define X509_STORE_up_ref(x)
#define SSL_CTX_get_ciphers(ctx)
VALUE mOSSL
Definition: ossl.c:231
void ossl_raise(VALUE exc, const char *fmt,...)
Definition: ossl.c:293
VALUE eOSSLError
Definition: ossl.c:236
void ossl_clear_error(void)
Definition: ossl.c:304
VALUE ossl_x509name_sk2ary(const STACK_OF(X509_NAME) *names)
STACK_OF(X509) *ossl_x509_ary2sk(VALUE)
#define OSSL_Debug
Definition: ossl.h:149
EVP_PKEY * GetPrivPKeyPtr(VALUE obj)
Definition: ossl_pkey.c:239
EVP_PKEY * DupPKeyPtr(VALUE obj)
Definition: ossl_pkey.c:252
EVP_PKEY * GetPKeyPtr(VALUE obj)
Definition: ossl_pkey.c:229
VALUE ossl_pkey_new(EVP_PKEY *pkey)
Definition: ossl_pkey.c:129
#define ssl_get_error(ssl, ret)
Definition: ossl_ssl.c:1643
VALUE mSSL
Definition: ossl_ssl.c:32
VALUE cSSLContext
Definition: ossl_ssl.c:35
const rb_data_type_t ossl_ssl_type
Definition: ossl_ssl.c:1552
#define numberof(ary)
Definition: ossl_ssl.c:14
#define TO_SOCKET(s)
Definition: ossl_ssl.c:25
#define DefIVarID(name)
#define rb_intern(s)
Definition: ossl_ssl.c:2453
VALUE cSSLSocket
Definition: ossl_ssl.c:36
#define GetSSLCTX(obj, ctx)
Definition: ossl_ssl.c:28
void Init_ossl_ssl(void)
Definition: ossl_ssl.c:2455
#define GetSSL(obj, ssl)
Definition: ossl_ssl.h:13
VALUE cSSLSession
void Init_ossl_ssl_session(void)
#define GetSSLSession(obj, sess)
Definition: ossl_ssl.h:20
VALUE ossl_x509_new(X509 *)
Definition: ossl_x509cert.c:51
X509_STORE * GetX509StorePtr(VALUE)
int ossl_verify_cb_call(VALUE, int, X509_STORE_CTX *)
X509 * DupX509CertPtr(VALUE)
Definition: ossl_x509cert.c:81
X509 * GetX509CertPtr(VALUE)
Definition: ossl_x509cert.c:71
#define RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, callback_arg)
#define RARRAY_LEN(a)
VALUE rb_str_unlocktmp(VALUE)
Definition: string.c:2675
#define rb_str_new2
#define NULL
#define rb_funcallv(recv, mid, argc, argv)
use StringValue() instead")))
#define RSTRING_LEN(str)
#define RTEST(v)
#define RB_PASS_KEYWORDS
void rb_attr(VALUE, ID, int, int, int)
Definition: vm_method.c:1180
#define NUM2ULONG(x)
void rb_define_private_method(VALUE, const char *, VALUE(*)(), int)
time_t time(time_t *_timer)
#define Qundef
#define rb_str_cat2
const VALUE VALUE obj
#define rb_check_frozen(obj)
VALUE rb_funcallv_kw(VALUE, ID, int, const VALUE *, int)
Definition: vm_eval.c:962
#define RSTRING_PTR(str)
#define RTYPEDDATA_DATA(v)
#define rb_str_new(str, len)
#define NIL_P(v)
#define rb_str_buf_cat
#define ID2SYM(x)
#define RSTRING_LENINT(str)
#define ruby_verbose
#define rb_intern_const(str)
void rb_str_set_len(VALUE, long)
Definition: string.c:2692
int rb_respond_to(VALUE, ID)
Definition: vm_method.c:2207
unsigned long VALUE
VALUE rb_ary_push(VALUE, VALUE)
Definition: array.c:1195
VALUE rb_sym2str(VALUE)
Definition: symbol.c:784
void rb_str_modify(VALUE)
Definition: string.c:2114
VALUE rb_hash_lookup2(VALUE, VALUE, VALUE)
Definition: hash.c:2050
void rb_define_alloc_func(VALUE, rb_alloc_func_t)
uint32_t i
#define char
int strncmp(const char *, const char *, size_t)
__inline__ const void *__restrict__ size_t len
#define OBJ_FROZEN(x)
#define INT2NUM(x)
#define T_HASH
#define LONG2NUM(x)
void rb_define_const(VALUE, const char *, VALUE)
Definition: variable.c:2891
#define NUM2INT(x)
#define RUBY_TYPED_FREE_IMMEDIATELY
#define TypedData_Get_Struct(obj, type, data_type, sval)
#define PRIsVALUE
VALUE rb_str_split(VALUE, const char *)
Definition: string.c:8116
#define rb_ary_new3
#define rb_funcall(recv, mid, argc,...)
int VALUE v
VALUE rb_ary_new(void)
Definition: array.c:723
#define rb_scan_args(argc, argvp, fmt,...)
void rb_gc_mark(VALUE)
Definition: gc.c:5228
#define TypedData_Wrap_Struct(klass, data_type, sval)
#define Qtrue
struct rb_call_cache buf
VALUE rb_str_append(VALUE, VALUE)
Definition: string.c:2965
VALUE rb_str_new_frozen(VALUE)
Definition: string.c:1203
VALUE rb_attr_get(VALUE, ID)
Definition: variable.c:1084
#define Qnil
#define Qfalse
#define DATA_PTR(dta)
#define T_ARRAY
void rb_str_modify_expand(VALUE, long)
Definition: string.c:2122
#define ULONG2NUM(x)
#define RB_TYPE_P(obj, type)
#define INT2FIX(i)
VALUE rb_str_locktmp(VALUE)
const VALUE * argv
#define SYMBOL_P(x)
VALUE rb_ivar_set(VALUE, ID, VALUE)
Definition: variable.c:1300
#define Check_Type(v, t)
#define RB_INTEGER_TYPE_P(obj)
VALUE rb_hash_aset(VALUE, VALUE, VALUE)
Definition: hash.c:2852
VALUE rb_block_call(VALUE, ID, int, const VALUE *, rb_block_call_func_t, VALUE)
Definition: vm_eval.c:1470
unsigned long ID
#define EPROTOTYPE
const char *void rb_warning(const char *,...) __attribute__((format(printf
#define NUM2LONG(x)
void rb_define_method(VALUE, const char *, VALUE(*)(), int)
#define rb_ary_new2
#define RARRAY_AREF(a, i)
VALUE rb_hash_new(void)
Definition: hash.c:1523
VALUE rb_call_super(int, const VALUE *)
Definition: vm_eval.c:306
VALUE rb_ary_entry(VALUE, long)
Definition: array.c:1512
#define StringValueCStr(v)
const unsigned char * in
Definition: ossl_ssl.c:638
Definition: io.h:66
int fd
Definition: io.h:68
VALUE rb_f_notimplement(int argc, const VALUE *argv, VALUE obj, VALUE marker)
Definition: vm_method.c:120