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