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