Ruby  2.5.0dev(2017-10-22revision60238)
ossl.c
Go to the documentation of this file.
1 /*
2  * 'OpenSSL for Ruby' project
3  * Copyright (C) 2001-2002 Michal Rokos <m.rokos@sh.cvut.cz>
4  * All rights reserved.
5  */
6 /*
7  * This program is licensed under the same licence as Ruby.
8  * (See the file 'LICENCE'.)
9  */
10 #include "ossl.h"
11 #include <stdarg.h> /* for ossl_raise */
12 #include <ruby/thread_native.h> /* for OpenSSL < 1.1.0 locks */
13 
14 /*
15  * Data Conversion
16  */
17 #define OSSL_IMPL_ARY2SK(name, type, expected_class, dup) \
18 STACK_OF(type) * \
19 ossl_##name##_ary2sk0(VALUE ary) \
20 { \
21  STACK_OF(type) *sk; \
22  VALUE val; \
23  type *x; \
24  int i; \
25  \
26  Check_Type(ary, T_ARRAY); \
27  sk = sk_##type##_new_null(); \
28  if (!sk) ossl_raise(eOSSLError, NULL); \
29  \
30  for (i = 0; i < RARRAY_LEN(ary); i++) { \
31  val = rb_ary_entry(ary, i); \
32  if (!rb_obj_is_kind_of(val, expected_class)) { \
33  sk_##type##_pop_free(sk, type##_free); \
34  ossl_raise(eOSSLError, "object in array not" \
35  " of class ##type##"); \
36  } \
37  x = dup(val); /* NEED TO DUP */ \
38  sk_##type##_push(sk, x); \
39  } \
40  return sk; \
41 } \
42  \
43 STACK_OF(type) * \
44 ossl_protect_##name##_ary2sk(VALUE ary, int *status) \
45 { \
46  return (STACK_OF(type)*)rb_protect( \
47  (VALUE (*)(VALUE))ossl_##name##_ary2sk0, \
48  ary, \
49  status); \
50 } \
51  \
52 STACK_OF(type) * \
53 ossl_##name##_ary2sk(VALUE ary) \
54 { \
55  STACK_OF(type) *sk; \
56  int status = 0; \
57  \
58  sk = ossl_protect_##name##_ary2sk(ary, &status); \
59  if (status) rb_jump_tag(status); \
60  \
61  return sk; \
62 }
64 
65 #define OSSL_IMPL_SK2ARY(name, type) \
66 VALUE \
67 ossl_##name##_sk2ary(const STACK_OF(type) *sk) \
68 { \
69  type *t; \
70  int i, num; \
71  VALUE ary; \
72  \
73  if (!sk) { \
74  OSSL_Debug("empty sk!"); \
75  return Qnil; \
76  } \
77  num = sk_##type##_num(sk); \
78  if (num < 0) { \
79  OSSL_Debug("items in sk < -1???"); \
80  return rb_ary_new(); \
81  } \
82  ary = rb_ary_new2(num); \
83  \
84  for (i=0; i<num; i++) { \
85  t = sk_##type##_value(sk, i); \
86  rb_ary_push(ary, ossl_##name##_new(t)); \
87  } \
88  return ary; \
89 }
90 OSSL_IMPL_SK2ARY(x509, X509)
91 OSSL_IMPL_SK2ARY(x509crl, X509_CRL)
92 OSSL_IMPL_SK2ARY(x509name, X509_NAME)
93 
94 static VALUE
95 ossl_str_new_i(VALUE size)
96 {
97  return rb_str_new(NULL, (long)size);
98 }
99 
100 VALUE
101 ossl_str_new(const char *ptr, long len, int *pstate)
102 {
103  VALUE str;
104  int state;
105 
106  str = rb_protect(ossl_str_new_i, len, &state);
107  if (pstate)
108  *pstate = state;
109  if (state) {
110  if (!pstate)
112  return Qnil;
113  }
114  if (ptr)
115  memcpy(RSTRING_PTR(str), ptr, len);
116  return str;
117 }
118 
119 VALUE
120 ossl_buf2str(char *buf, int len)
121 {
122  VALUE str;
123  int state;
124 
125  str = ossl_str_new(buf, len, &state);
126  OPENSSL_free(buf);
127  if (state)
128  rb_jump_tag(state);
129  return str;
130 }
131 
132 void
133 ossl_bin2hex(unsigned char *in, char *out, size_t inlen)
134 {
135  const char *hex = "0123456789abcdef";
136  size_t i;
137 
138  assert(inlen <= LONG_MAX / 2);
139  for (i = 0; i < inlen; i++) {
140  unsigned char p = in[i];
141 
142  out[i * 2 + 0] = hex[p >> 4];
143  out[i * 2 + 1] = hex[p & 0x0f];
144  }
145 }
146 
147 /*
148  * our default PEM callback
149  */
150 VALUE
152 {
153  if (NIL_P(pass))
154  return Qnil;
155 
156  StringValue(pass);
157 
158  /* PEM_BUFSIZE is currently used as the second argument of pem_password_cb,
159  * that is +max_len+ of ossl_pem_passwd_cb() */
160  if (RSTRING_LEN(pass) > PEM_BUFSIZE)
161  ossl_raise(eOSSLError, "password must not be longer than %d bytes", PEM_BUFSIZE);
162 
163  return pass;
164 }
165 
166 static VALUE
167 ossl_pem_passwd_cb0(VALUE flag)
168 {
169  VALUE pass = rb_yield(flag);
170  if (NIL_P(pass))
171  return Qnil;
172  StringValue(pass);
173  return pass;
174 }
175 
176 int
177 ossl_pem_passwd_cb(char *buf, int max_len, int flag, void *pwd_)
178 {
179  long len;
180  int status;
181  VALUE rflag, pass = (VALUE)pwd_;
182 
183  if (RTEST(pass)) {
184  /* PEM_def_callback(buf, max_len, flag, StringValueCStr(pass)) does not
185  * work because it does not allow NUL characters and truncates to 1024
186  * bytes silently if the input is over 1024 bytes */
187  if (RB_TYPE_P(pass, T_STRING)) {
188  len = RSTRING_LEN(pass);
189  if (len <= max_len) {
190  memcpy(buf, RSTRING_PTR(pass), len);
191  return (int)len;
192  }
193  }
194  OSSL_Debug("passed data is not valid String???");
195  return -1;
196  }
197 
198  if (!rb_block_given_p()) {
199  return PEM_def_callback(buf, max_len, flag, NULL);
200  }
201 
202  while (1) {
203  /*
204  * when the flag is nonzero, this passphrase
205  * will be used to perform encryption; otherwise it will
206  * be used to perform decryption.
207  */
208  rflag = flag ? Qtrue : Qfalse;
209  pass = rb_protect(ossl_pem_passwd_cb0, rflag, &status);
210  if (status) {
211  /* ignore an exception raised. */
213  return -1;
214  }
215  if (NIL_P(pass))
216  return -1;
217  len = RSTRING_LEN(pass);
218  if (len > max_len) {
219  rb_warning("password must not be longer than %d bytes", max_len);
220  continue;
221  }
222  memcpy(buf, RSTRING_PTR(pass), len);
223  break;
224  }
225  return (int)len;
226 }
227 
228 /*
229  * main module
230  */
232 
233 /*
234  * OpenSSLError < StandardError
235  */
237 
238 /*
239  * Convert to DER string
240  */
241 static ID ossl_s_to_der;
242 
243 VALUE
245 {
246  VALUE tmp;
247 
248  tmp = rb_funcall(obj, ossl_s_to_der, 0);
249  StringValue(tmp);
250 
251  return tmp;
252 }
253 
254 VALUE
256 {
257  if(rb_respond_to(obj, ossl_s_to_der))
258  return ossl_to_der(obj);
259  return obj;
260 }
261 
262 /*
263  * Errors
264  */
265 static VALUE
266 ossl_make_error(VALUE exc, const char *fmt, va_list args)
267 {
268  VALUE str = Qnil;
269  unsigned long e;
270 
271  if (fmt) {
272  str = rb_vsprintf(fmt, args);
273  }
274  e = ERR_peek_last_error();
275  if (e) {
276  const char *msg = ERR_reason_error_string(e);
277 
278  if (NIL_P(str)) {
279  if (msg) str = rb_str_new_cstr(msg);
280  }
281  else {
282  if (RSTRING_LEN(str)) rb_str_cat2(str, ": ");
283  rb_str_cat2(str, msg ? msg : "(null)");
284  }
286  }
287 
288  if (NIL_P(str)) str = rb_str_new(0, 0);
289  return rb_exc_new3(exc, str);
290 }
291 
292 void
293 ossl_raise(VALUE exc, const char *fmt, ...)
294 {
295  va_list args;
296  VALUE err;
297  va_start(args, fmt);
298  err = ossl_make_error(exc, fmt, args);
299  va_end(args);
300  rb_exc_raise(err);
301 }
302 
303 void
305 {
306  if (dOSSL == Qtrue) {
307  unsigned long e;
308  const char *file, *data, *errstr;
309  int line, flags;
310 
311  while ((e = ERR_get_error_line_data(&file, &line, &data, &flags))) {
312  errstr = ERR_error_string(e, NULL);
313  if (!errstr)
314  errstr = "(null)";
315 
316  if (flags & ERR_TXT_STRING) {
317  if (!data)
318  data = "(null)";
319  rb_warn("error on stack: %s (%s)", errstr, data);
320  }
321  else {
322  rb_warn("error on stack: %s", errstr);
323  }
324  }
325  }
326  else {
327  ERR_clear_error();
328  }
329 }
330 
331 /*
332  * call-seq:
333  * OpenSSL.errors -> [String...]
334  *
335  * See any remaining errors held in queue.
336  *
337  * Any errors you see here are probably due to a bug in Ruby's OpenSSL
338  * implementation.
339  */
340 VALUE
342 {
343  VALUE ary;
344  long e;
345 
346  ary = rb_ary_new();
347  while ((e = ERR_get_error()) != 0){
348  rb_ary_push(ary, rb_str_new2(ERR_error_string(e, NULL)));
349  }
350 
351  return ary;
352 }
353 
354 /*
355  * Debug
356  */
358 
359 #if !defined(HAVE_VA_ARGS_MACRO)
360 void
361 ossl_debug(const char *fmt, ...)
362 {
363  va_list args;
364 
365  if (dOSSL == Qtrue) {
366  fprintf(stderr, "OSSL_DEBUG: ");
367  va_start(args, fmt);
368  vfprintf(stderr, fmt, args);
369  va_end(args);
370  fprintf(stderr, " [CONTEXT N/A]\n");
371  }
372 }
373 #endif
374 
375 /*
376  * call-seq:
377  * OpenSSL.debug -> true | false
378  */
379 static VALUE
380 ossl_debug_get(VALUE self)
381 {
382  return dOSSL;
383 }
384 
385 /*
386  * call-seq:
387  * OpenSSL.debug = boolean -> boolean
388  *
389  * Turns on or off debug mode. With debug mode, all erros added to the OpenSSL
390  * error queue will be printed to stderr.
391  */
392 static VALUE
393 ossl_debug_set(VALUE self, VALUE val)
394 {
395  dOSSL = RTEST(val) ? Qtrue : Qfalse;
396 
397  return val;
398 }
399 
400 /*
401  * call-seq
402  * OpenSSL.fips_mode -> true | false
403  */
404 static VALUE
405 ossl_fips_mode_get(VALUE self)
406 {
407 
408 #ifdef OPENSSL_FIPS
409  VALUE enabled;
410  enabled = FIPS_mode() ? Qtrue : Qfalse;
411  return enabled;
412 #else
413  return Qfalse;
414 #endif
415 }
416 
417 /*
418  * call-seq:
419  * OpenSSL.fips_mode = boolean -> boolean
420  *
421  * Turns FIPS mode on or off. Turning on FIPS mode will obviously only have an
422  * effect for FIPS-capable installations of the OpenSSL library. Trying to do
423  * so otherwise will result in an error.
424  *
425  * === Examples
426  * OpenSSL.fips_mode = true # turn FIPS mode on
427  * OpenSSL.fips_mode = false # and off again
428  */
429 static VALUE
430 ossl_fips_mode_set(VALUE self, VALUE enabled)
431 {
432 
433 #ifdef OPENSSL_FIPS
434  if (RTEST(enabled)) {
435  int mode = FIPS_mode();
436  if(!mode && !FIPS_mode_set(1)) /* turning on twice leads to an error */
437  ossl_raise(eOSSLError, "Turning on FIPS mode failed");
438  } else {
439  if(!FIPS_mode_set(0)) /* turning off twice is OK */
440  ossl_raise(eOSSLError, "Turning off FIPS mode failed");
441  }
442  return enabled;
443 #else
444  if (RTEST(enabled))
445  ossl_raise(eOSSLError, "This version of OpenSSL does not support FIPS mode");
446  return enabled;
447 #endif
448 }
449 
450 #if defined(OSSL_DEBUG)
451 #if !defined(LIBRESSL_VERSION_NUMBER) && \
452  (OPENSSL_VERSION_NUMBER >= 0x10100000 && !defined(OPENSSL_NO_CRYPTO_MDEBUG) || \
453  defined(CRYPTO_malloc_debug_init))
454 /*
455  * call-seq:
456  * OpenSSL.mem_check_start -> nil
457  *
458  * Calls CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON). Starts tracking memory
459  * allocations. See also OpenSSL.print_mem_leaks.
460  *
461  * This is available only when built with a capable OpenSSL and --enable-debug
462  * configure option.
463  */
464 static VALUE
465 mem_check_start(VALUE self)
466 {
467  CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
468  return Qnil;
469 }
470 
471 /*
472  * call-seq:
473  * OpenSSL.print_mem_leaks -> true | false
474  *
475  * For debugging the Ruby/OpenSSL library. Calls CRYPTO_mem_leaks_fp(stderr).
476  * Prints detected memory leaks to standard error. This cleans the global state
477  * up thus you cannot use any methods of the library after calling this.
478  *
479  * Returns +true+ if leaks detected, +false+ otherwise.
480  *
481  * This is available only when built with a capable OpenSSL and --enable-debug
482  * configure option.
483  *
484  * === Example
485  * OpenSSL.mem_check_start
486  * NOT_GCED = OpenSSL::PKey::RSA.new(256)
487  *
488  * END {
489  * GC.start
490  * OpenSSL.print_mem_leaks # will print the leakage
491  * }
492  */
493 static VALUE
494 print_mem_leaks(VALUE self)
495 {
496 #if OPENSSL_VERSION_NUMBER >= 0x10100000
497  int ret;
498 #endif
499 
500  BN_CTX_free(ossl_bn_ctx);
501  ossl_bn_ctx = NULL;
502 
503 #if OPENSSL_VERSION_NUMBER >= 0x10100000
504  ret = CRYPTO_mem_leaks_fp(stderr);
505  if (ret < 0)
506  ossl_raise(eOSSLError, "CRYPTO_mem_leaks_fp");
507  return ret ? Qfalse : Qtrue;
508 #else
509  CRYPTO_mem_leaks_fp(stderr);
510  return Qnil;
511 #endif
512 }
513 #endif
514 #endif
515 
516 #if !defined(HAVE_OPENSSL_110_THREADING_API)
517 
521  rb_nativethread_lock_t lock;
522  rb_nativethread_id_t owner;
523  size_t count;
524 };
525 
526 static void
527 ossl_lock_init(struct CRYPTO_dynlock_value *l)
528 {
530  l->count = 0;
531 }
532 
533 static void
534 ossl_lock_unlock(int mode, struct CRYPTO_dynlock_value *l)
535 {
536  if (mode & CRYPTO_LOCK) {
537  /* TODO: rb_nativethread_id_t is not necessarily compared with ==. */
538  rb_nativethread_id_t tid = rb_nativethread_self();
539  if (l->count && l->owner == tid) {
540  l->count++;
541  return;
542  }
544  l->owner = tid;
545  l->count = 1;
546  } else {
547  if (!--l->count)
549  }
550 }
551 
552 static struct CRYPTO_dynlock_value *
553 ossl_dyn_create_callback(const char *file, int line)
554 {
555  /* Do not use xmalloc() here, since it may raise NoMemoryError */
556  struct CRYPTO_dynlock_value *dynlock =
557  OPENSSL_malloc(sizeof(struct CRYPTO_dynlock_value));
558  if (dynlock)
559  ossl_lock_init(dynlock);
560  return dynlock;
561 }
562 
563 static void
564 ossl_dyn_lock_callback(int mode, struct CRYPTO_dynlock_value *l, const char *file, int line)
565 {
566  ossl_lock_unlock(mode, l);
567 }
568 
569 static void
570 ossl_dyn_destroy_callback(struct CRYPTO_dynlock_value *l, const char *file, int line)
571 {
573  OPENSSL_free(l);
574 }
575 
576 static void ossl_threadid_func(CRYPTO_THREADID *id)
577 {
578  /* register native thread id */
579  CRYPTO_THREADID_set_pointer(id, (void *)rb_nativethread_self());
580 }
581 
582 static struct CRYPTO_dynlock_value *ossl_locks;
583 
584 static void
585 ossl_lock_callback(int mode, int type, const char *file, int line)
586 {
587  ossl_lock_unlock(mode, &ossl_locks[type]);
588 }
589 
590 static void Init_ossl_locks(void)
591 {
592  int i;
593  int num_locks = CRYPTO_num_locks();
594 
595  ossl_locks = ALLOC_N(struct CRYPTO_dynlock_value, num_locks);
596  for (i = 0; i < num_locks; i++)
597  ossl_lock_init(&ossl_locks[i]);
598 
599  CRYPTO_THREADID_set_callback(ossl_threadid_func);
600  CRYPTO_set_locking_callback(ossl_lock_callback);
601  CRYPTO_set_dynlock_create_callback(ossl_dyn_create_callback);
602  CRYPTO_set_dynlock_lock_callback(ossl_dyn_lock_callback);
603  CRYPTO_set_dynlock_destroy_callback(ossl_dyn_destroy_callback);
604 }
605 #endif /* !HAVE_OPENSSL_110_THREADING_API */
606 
607 /*
608  * OpenSSL provides SSL, TLS and general purpose cryptography. It wraps the
609  * OpenSSL[https://www.openssl.org/] library.
610  *
611  * = Examples
612  *
613  * All examples assume you have loaded OpenSSL with:
614  *
615  * require 'openssl'
616  *
617  * These examples build atop each other. For example the key created in the
618  * next is used in throughout these examples.
619  *
620  * == Keys
621  *
622  * === Creating a Key
623  *
624  * This example creates a 2048 bit RSA keypair and writes it to the current
625  * directory.
626  *
627  * key = OpenSSL::PKey::RSA.new 2048
628  *
629  * open 'private_key.pem', 'w' do |io| io.write key.to_pem end
630  * open 'public_key.pem', 'w' do |io| io.write key.public_key.to_pem end
631  *
632  * === Exporting a Key
633  *
634  * Keys saved to disk without encryption are not secure as anyone who gets
635  * ahold of the key may use it unless it is encrypted. In order to securely
636  * export a key you may export it with a pass phrase.
637  *
638  * cipher = OpenSSL::Cipher.new 'AES-128-CBC'
639  * pass_phrase = 'my secure pass phrase goes here'
640  *
641  * key_secure = key.export cipher, pass_phrase
642  *
643  * open 'private.secure.pem', 'w' do |io|
644  * io.write key_secure
645  * end
646  *
647  * OpenSSL::Cipher.ciphers returns a list of available ciphers.
648  *
649  * === Loading a Key
650  *
651  * A key can also be loaded from a file.
652  *
653  * key2 = OpenSSL::PKey::RSA.new File.read 'private_key.pem'
654  * key2.public? # => true
655  * key2.private? # => true
656  *
657  * or
658  *
659  * key3 = OpenSSL::PKey::RSA.new File.read 'public_key.pem'
660  * key3.public? # => true
661  * key3.private? # => false
662  *
663  * === Loading an Encrypted Key
664  *
665  * OpenSSL will prompt you for your pass phrase when loading an encrypted key.
666  * If you will not be able to type in the pass phrase you may provide it when
667  * loading the key:
668  *
669  * key4_pem = File.read 'private.secure.pem'
670  * pass_phrase = 'my secure pass phrase goes here'
671  * key4 = OpenSSL::PKey::RSA.new key4_pem, pass_phrase
672  *
673  * == RSA Encryption
674  *
675  * RSA provides encryption and decryption using the public and private keys.
676  * You can use a variety of padding methods depending upon the intended use of
677  * encrypted data.
678  *
679  * === Encryption & Decryption
680  *
681  * Asymmetric public/private key encryption is slow and victim to attack in
682  * cases where it is used without padding or directly to encrypt larger chunks
683  * of data. Typical use cases for RSA encryption involve "wrapping" a symmetric
684  * key with the public key of the recipient who would "unwrap" that symmetric
685  * key again using their private key.
686  * The following illustrates a simplified example of such a key transport
687  * scheme. It shouldn't be used in practice, though, standardized protocols
688  * should always be preferred.
689  *
690  * wrapped_key = key.public_encrypt key
691  *
692  * A symmetric key encrypted with the public key can only be decrypted with
693  * the corresponding private key of the recipient.
694  *
695  * original_key = key.private_decrypt wrapped_key
696  *
697  * By default PKCS#1 padding will be used, but it is also possible to use
698  * other forms of padding, see PKey::RSA for further details.
699  *
700  * === Signatures
701  *
702  * Using "private_encrypt" to encrypt some data with the private key is
703  * equivalent to applying a digital signature to the data. A verifying
704  * party may validate the signature by comparing the result of decrypting
705  * the signature with "public_decrypt" to the original data. However,
706  * OpenSSL::PKey already has methods "sign" and "verify" that handle
707  * digital signatures in a standardized way - "private_encrypt" and
708  * "public_decrypt" shouldn't be used in practice.
709  *
710  * To sign a document, a cryptographically secure hash of the document is
711  * computed first, which is then signed using the private key.
712  *
713  * digest = OpenSSL::Digest::SHA256.new
714  * signature = key.sign digest, document
715  *
716  * To validate the signature, again a hash of the document is computed and
717  * the signature is decrypted using the public key. The result is then
718  * compared to the hash just computed, if they are equal the signature was
719  * valid.
720  *
721  * digest = OpenSSL::Digest::SHA256.new
722  * if key.verify digest, signature, document
723  * puts 'Valid'
724  * else
725  * puts 'Invalid'
726  * end
727  *
728  * == PBKDF2 Password-based Encryption
729  *
730  * If supported by the underlying OpenSSL version used, Password-based
731  * Encryption should use the features of PKCS5. If not supported or if
732  * required by legacy applications, the older, less secure methods specified
733  * in RFC 2898 are also supported (see below).
734  *
735  * PKCS5 supports PBKDF2 as it was specified in PKCS#5
736  * v2.0[http://www.rsa.com/rsalabs/node.asp?id=2127]. It still uses a
737  * password, a salt, and additionally a number of iterations that will
738  * slow the key derivation process down. The slower this is, the more work
739  * it requires being able to brute-force the resulting key.
740  *
741  * === Encryption
742  *
743  * The strategy is to first instantiate a Cipher for encryption, and
744  * then to generate a random IV plus a key derived from the password
745  * using PBKDF2. PKCS #5 v2.0 recommends at least 8 bytes for the salt,
746  * the number of iterations largely depends on the hardware being used.
747  *
748  * cipher = OpenSSL::Cipher.new 'AES-128-CBC'
749  * cipher.encrypt
750  * iv = cipher.random_iv
751  *
752  * pwd = 'some hopefully not to easily guessable password'
753  * salt = OpenSSL::Random.random_bytes 16
754  * iter = 20000
755  * key_len = cipher.key_len
756  * digest = OpenSSL::Digest::SHA256.new
757  *
758  * key = OpenSSL::PKCS5.pbkdf2_hmac(pwd, salt, iter, key_len, digest)
759  * cipher.key = key
760  *
761  * Now encrypt the data:
762  *
763  * encrypted = cipher.update document
764  * encrypted << cipher.final
765  *
766  * === Decryption
767  *
768  * Use the same steps as before to derive the symmetric AES key, this time
769  * setting the Cipher up for decryption.
770  *
771  * cipher = OpenSSL::Cipher.new 'AES-128-CBC'
772  * cipher.decrypt
773  * cipher.iv = iv # the one generated with #random_iv
774  *
775  * pwd = 'some hopefully not to easily guessable password'
776  * salt = ... # the one generated above
777  * iter = 20000
778  * key_len = cipher.key_len
779  * digest = OpenSSL::Digest::SHA256.new
780  *
781  * key = OpenSSL::PKCS5.pbkdf2_hmac(pwd, salt, iter, key_len, digest)
782  * cipher.key = key
783  *
784  * Now decrypt the data:
785  *
786  * decrypted = cipher.update encrypted
787  * decrypted << cipher.final
788  *
789  * == PKCS #5 Password-based Encryption
790  *
791  * PKCS #5 is a password-based encryption standard documented at
792  * RFC2898[http://www.ietf.org/rfc/rfc2898.txt]. It allows a short password or
793  * passphrase to be used to create a secure encryption key. If possible, PBKDF2
794  * as described above should be used if the circumstances allow it.
795  *
796  * PKCS #5 uses a Cipher, a pass phrase and a salt to generate an encryption
797  * key.
798  *
799  * pass_phrase = 'my secure pass phrase goes here'
800  * salt = '8 octets'
801  *
802  * === Encryption
803  *
804  * First set up the cipher for encryption
805  *
806  * encryptor = OpenSSL::Cipher.new 'AES-128-CBC'
807  * encryptor.encrypt
808  * encryptor.pkcs5_keyivgen pass_phrase, salt
809  *
810  * Then pass the data you want to encrypt through
811  *
812  * encrypted = encryptor.update 'top secret document'
813  * encrypted << encryptor.final
814  *
815  * === Decryption
816  *
817  * Use a new Cipher instance set up for decryption
818  *
819  * decryptor = OpenSSL::Cipher.new 'AES-128-CBC'
820  * decryptor.decrypt
821  * decryptor.pkcs5_keyivgen pass_phrase, salt
822  *
823  * Then pass the data you want to decrypt through
824  *
825  * plain = decryptor.update encrypted
826  * plain << decryptor.final
827  *
828  * == X509 Certificates
829  *
830  * === Creating a Certificate
831  *
832  * This example creates a self-signed certificate using an RSA key and a SHA1
833  * signature.
834  *
835  * key = OpenSSL::PKey::RSA.new 2048
836  * name = OpenSSL::X509::Name.parse 'CN=nobody/DC=example'
837  *
838  * cert = OpenSSL::X509::Certificate.new
839  * cert.version = 2
840  * cert.serial = 0
841  * cert.not_before = Time.now
842  * cert.not_after = Time.now + 3600
843  *
844  * cert.public_key = key.public_key
845  * cert.subject = name
846  *
847  * === Certificate Extensions
848  *
849  * You can add extensions to the certificate with
850  * OpenSSL::SSL::ExtensionFactory to indicate the purpose of the certificate.
851  *
852  * extension_factory = OpenSSL::X509::ExtensionFactory.new nil, cert
853  *
854  * cert.add_extension \
855  * extension_factory.create_extension('basicConstraints', 'CA:FALSE', true)
856  *
857  * cert.add_extension \
858  * extension_factory.create_extension(
859  * 'keyUsage', 'keyEncipherment,dataEncipherment,digitalSignature')
860  *
861  * cert.add_extension \
862  * extension_factory.create_extension('subjectKeyIdentifier', 'hash')
863  *
864  * The list of supported extensions (and in some cases their possible values)
865  * can be derived from the "objects.h" file in the OpenSSL source code.
866  *
867  * === Signing a Certificate
868  *
869  * To sign a certificate set the issuer and use OpenSSL::X509::Certificate#sign
870  * with a digest algorithm. This creates a self-signed cert because we're using
871  * the same name and key to sign the certificate as was used to create the
872  * certificate.
873  *
874  * cert.issuer = name
875  * cert.sign key, OpenSSL::Digest::SHA1.new
876  *
877  * open 'certificate.pem', 'w' do |io| io.write cert.to_pem end
878  *
879  * === Loading a Certificate
880  *
881  * Like a key, a cert can also be loaded from a file.
882  *
883  * cert2 = OpenSSL::X509::Certificate.new File.read 'certificate.pem'
884  *
885  * === Verifying a Certificate
886  *
887  * Certificate#verify will return true when a certificate was signed with the
888  * given public key.
889  *
890  * raise 'certificate can not be verified' unless cert2.verify key
891  *
892  * == Certificate Authority
893  *
894  * A certificate authority (CA) is a trusted third party that allows you to
895  * verify the ownership of unknown certificates. The CA issues key signatures
896  * that indicate it trusts the user of that key. A user encountering the key
897  * can verify the signature by using the CA's public key.
898  *
899  * === CA Key
900  *
901  * CA keys are valuable, so we encrypt and save it to disk and make sure it is
902  * not readable by other users.
903  *
904  * ca_key = OpenSSL::PKey::RSA.new 2048
905  * pass_phrase = 'my secure pass phrase goes here'
906  *
907  * cipher = OpenSSL::Cipher.new 'AES-128-CBC'
908  *
909  * open 'ca_key.pem', 'w', 0400 do |io|
910  * io.write ca_key.export(cipher, pass_phrase)
911  * end
912  *
913  * === CA Certificate
914  *
915  * A CA certificate is created the same way we created a certificate above, but
916  * with different extensions.
917  *
918  * ca_name = OpenSSL::X509::Name.parse 'CN=ca/DC=example'
919  *
920  * ca_cert = OpenSSL::X509::Certificate.new
921  * ca_cert.serial = 0
922  * ca_cert.version = 2
923  * ca_cert.not_before = Time.now
924  * ca_cert.not_after = Time.now + 86400
925  *
926  * ca_cert.public_key = ca_key.public_key
927  * ca_cert.subject = ca_name
928  * ca_cert.issuer = ca_name
929  *
930  * extension_factory = OpenSSL::X509::ExtensionFactory.new
931  * extension_factory.subject_certificate = ca_cert
932  * extension_factory.issuer_certificate = ca_cert
933  *
934  * ca_cert.add_extension \
935  * extension_factory.create_extension('subjectKeyIdentifier', 'hash')
936  *
937  * This extension indicates the CA's key may be used as a CA.
938  *
939  * ca_cert.add_extension \
940  * extension_factory.create_extension('basicConstraints', 'CA:TRUE', true)
941  *
942  * This extension indicates the CA's key may be used to verify signatures on
943  * both certificates and certificate revocations.
944  *
945  * ca_cert.add_extension \
946  * extension_factory.create_extension(
947  * 'keyUsage', 'cRLSign,keyCertSign', true)
948  *
949  * Root CA certificates are self-signed.
950  *
951  * ca_cert.sign ca_key, OpenSSL::Digest::SHA1.new
952  *
953  * The CA certificate is saved to disk so it may be distributed to all the
954  * users of the keys this CA will sign.
955  *
956  * open 'ca_cert.pem', 'w' do |io|
957  * io.write ca_cert.to_pem
958  * end
959  *
960  * === Certificate Signing Request
961  *
962  * The CA signs keys through a Certificate Signing Request (CSR). The CSR
963  * contains the information necessary to identify the key.
964  *
965  * csr = OpenSSL::X509::Request.new
966  * csr.version = 0
967  * csr.subject = name
968  * csr.public_key = key.public_key
969  * csr.sign key, OpenSSL::Digest::SHA1.new
970  *
971  * A CSR is saved to disk and sent to the CA for signing.
972  *
973  * open 'csr.pem', 'w' do |io|
974  * io.write csr.to_pem
975  * end
976  *
977  * === Creating a Certificate from a CSR
978  *
979  * Upon receiving a CSR the CA will verify it before signing it. A minimal
980  * verification would be to check the CSR's signature.
981  *
982  * csr = OpenSSL::X509::Request.new File.read 'csr.pem'
983  *
984  * raise 'CSR can not be verified' unless csr.verify csr.public_key
985  *
986  * After verification a certificate is created, marked for various usages,
987  * signed with the CA key and returned to the requester.
988  *
989  * csr_cert = OpenSSL::X509::Certificate.new
990  * csr_cert.serial = 0
991  * csr_cert.version = 2
992  * csr_cert.not_before = Time.now
993  * csr_cert.not_after = Time.now + 600
994  *
995  * csr_cert.subject = csr.subject
996  * csr_cert.public_key = csr.public_key
997  * csr_cert.issuer = ca_cert.subject
998  *
999  * extension_factory = OpenSSL::X509::ExtensionFactory.new
1000  * extension_factory.subject_certificate = csr_cert
1001  * extension_factory.issuer_certificate = ca_cert
1002  *
1003  * csr_cert.add_extension \
1004  * extension_factory.create_extension('basicConstraints', 'CA:FALSE')
1005  *
1006  * csr_cert.add_extension \
1007  * extension_factory.create_extension(
1008  * 'keyUsage', 'keyEncipherment,dataEncipherment,digitalSignature')
1009  *
1010  * csr_cert.add_extension \
1011  * extension_factory.create_extension('subjectKeyIdentifier', 'hash')
1012  *
1013  * csr_cert.sign ca_key, OpenSSL::Digest::SHA1.new
1014  *
1015  * open 'csr_cert.pem', 'w' do |io|
1016  * io.write csr_cert.to_pem
1017  * end
1018  *
1019  * == SSL and TLS Connections
1020  *
1021  * Using our created key and certificate we can create an SSL or TLS connection.
1022  * An SSLContext is used to set up an SSL session.
1023  *
1024  * context = OpenSSL::SSL::SSLContext.new
1025  *
1026  * === SSL Server
1027  *
1028  * An SSL server requires the certificate and private key to communicate
1029  * securely with its clients:
1030  *
1031  * context.cert = cert
1032  * context.key = key
1033  *
1034  * Then create an SSLServer with a TCP server socket and the context. Use the
1035  * SSLServer like an ordinary TCP server.
1036  *
1037  * require 'socket'
1038  *
1039  * tcp_server = TCPServer.new 5000
1040  * ssl_server = OpenSSL::SSL::SSLServer.new tcp_server, context
1041  *
1042  * loop do
1043  * ssl_connection = ssl_server.accept
1044  *
1045  * data = connection.gets
1046  *
1047  * response = "I got #{data.dump}"
1048  * puts response
1049  *
1050  * connection.puts "I got #{data.dump}"
1051  * connection.close
1052  * end
1053  *
1054  * === SSL client
1055  *
1056  * An SSL client is created with a TCP socket and the context.
1057  * SSLSocket#connect must be called to initiate the SSL handshake and start
1058  * encryption. A key and certificate are not required for the client socket.
1059  *
1060  * Note that SSLSocket#close doesn't close the underlying socket by default. Set
1061  * SSLSocket#sync_close to true if you want.
1062  *
1063  * require 'socket'
1064  *
1065  * tcp_socket = TCPSocket.new 'localhost', 5000
1066  * ssl_client = OpenSSL::SSL::SSLSocket.new tcp_socket, context
1067  * ssl_client.sync_close = true
1068  * ssl_client.connect
1069  *
1070  * ssl_client.puts "hello server!"
1071  * puts ssl_client.gets
1072  *
1073  * ssl_client.close # shutdown the TLS connection and close tcp_socket
1074  *
1075  * === Peer Verification
1076  *
1077  * An unverified SSL connection does not provide much security. For enhanced
1078  * security the client or server can verify the certificate of its peer.
1079  *
1080  * The client can be modified to verify the server's certificate against the
1081  * certificate authority's certificate:
1082  *
1083  * context.ca_file = 'ca_cert.pem'
1084  * context.verify_mode = OpenSSL::SSL::VERIFY_PEER
1085  *
1086  * require 'socket'
1087  *
1088  * tcp_socket = TCPSocket.new 'localhost', 5000
1089  * ssl_client = OpenSSL::SSL::SSLSocket.new tcp_socket, context
1090  * ssl_client.connect
1091  *
1092  * ssl_client.puts "hello server!"
1093  * puts ssl_client.gets
1094  *
1095  * If the server certificate is invalid or <tt>context.ca_file</tt> is not set
1096  * when verifying peers an OpenSSL::SSL::SSLError will be raised.
1097  *
1098  */
1099 void
1101 {
1102  /*
1103  * Init timezone info
1104  */
1105 #if 0
1106  tzset();
1107 #endif
1108 
1109  /*
1110  * Init all digests, ciphers
1111  */
1112  /* CRYPTO_malloc_init(); */
1113  /* ENGINE_load_builtin_engines(); */
1114  OpenSSL_add_ssl_algorithms();
1115  OpenSSL_add_all_algorithms();
1116  ERR_load_crypto_strings();
1117  SSL_load_error_strings();
1118 
1119  /*
1120  * FIXME:
1121  * On unload do:
1122  */
1123 #if 0
1124  CONF_modules_unload(1);
1125  destroy_ui_method();
1126  EVP_cleanup();
1127  ENGINE_cleanup();
1128  CRYPTO_cleanup_all_ex_data();
1129  ERR_remove_state(0);
1130  ERR_free_strings();
1131 #endif
1132 
1133  /*
1134  * Init main module
1135  */
1136  mOSSL = rb_define_module("OpenSSL");
1137  rb_global_variable(&mOSSL);
1138 
1139  /*
1140  * OpenSSL ruby extension version
1141  */
1142  rb_define_const(mOSSL, "VERSION", rb_str_new2(OSSL_VERSION));
1143 
1144  /*
1145  * Version of OpenSSL the ruby OpenSSL extension was built with
1146  */
1147  rb_define_const(mOSSL, "OPENSSL_VERSION", rb_str_new2(OPENSSL_VERSION_TEXT));
1148 
1149  /*
1150  * Version of OpenSSL the ruby OpenSSL extension is running with
1151  */
1152  rb_define_const(mOSSL, "OPENSSL_LIBRARY_VERSION", rb_str_new2(SSLeay_version(SSLEAY_VERSION)));
1153 
1154  /*
1155  * Version number of OpenSSL the ruby OpenSSL extension was built with
1156  * (base 16)
1157  */
1158  rb_define_const(mOSSL, "OPENSSL_VERSION_NUMBER", INT2NUM(OPENSSL_VERSION_NUMBER));
1159 
1160  /*
1161  * Boolean indicating whether OpenSSL is FIPS-capable or not
1162  */
1163  rb_define_const(mOSSL, "OPENSSL_FIPS",
1164 #ifdef OPENSSL_FIPS
1165  Qtrue
1166 #else
1167  Qfalse
1168 #endif
1169  );
1170 
1171  rb_define_module_function(mOSSL, "fips_mode", ossl_fips_mode_get, 0);
1172  rb_define_module_function(mOSSL, "fips_mode=", ossl_fips_mode_set, 1);
1173 
1174  /*
1175  * Generic error,
1176  * common for all classes under OpenSSL module
1177  */
1178  eOSSLError = rb_define_class_under(mOSSL,"OpenSSLError",rb_eStandardError);
1179  rb_global_variable(&eOSSLError);
1180 
1181  /*
1182  * Init debug core
1183  */
1184  dOSSL = Qfalse;
1185  rb_global_variable(&dOSSL);
1186 
1187  rb_define_module_function(mOSSL, "debug", ossl_debug_get, 0);
1188  rb_define_module_function(mOSSL, "debug=", ossl_debug_set, 1);
1189  rb_define_module_function(mOSSL, "errors", ossl_get_errors, 0);
1190 
1191  /*
1192  * Get ID of to_der
1193  */
1194  ossl_s_to_der = rb_intern("to_der");
1195 
1196 #if !defined(HAVE_OPENSSL_110_THREADING_API)
1197  Init_ossl_locks();
1198 #endif
1199 
1200  /*
1201  * Init components
1202  */
1203  Init_ossl_bn();
1204  Init_ossl_cipher();
1205  Init_ossl_config();
1206  Init_ossl_digest();
1207  Init_ossl_hmac();
1209  Init_ossl_pkcs12();
1210  Init_ossl_pkcs7();
1211  Init_ossl_pkey();
1212  Init_ossl_rand();
1213  Init_ossl_ssl();
1214  Init_ossl_x509();
1215  Init_ossl_ocsp();
1216  Init_ossl_engine();
1217  Init_ossl_asn1();
1218  Init_ossl_kdf();
1219 
1220 #if defined(OSSL_DEBUG)
1221  /*
1222  * For debugging Ruby/OpenSSL. Enable only when built with --enable-debug
1223  */
1224 #if !defined(LIBRESSL_VERSION_NUMBER) && \
1225  (OPENSSL_VERSION_NUMBER >= 0x10100000 && !defined(OPENSSL_NO_CRYPTO_MDEBUG) || \
1226  defined(CRYPTO_malloc_debug_init))
1227  rb_define_module_function(mOSSL, "mem_check_start", mem_check_start, 0);
1228  rb_define_module_function(mOSSL, "print_mem_leaks", print_mem_leaks, 0);
1229 
1230 #if defined(CRYPTO_malloc_debug_init) /* <= 1.0.2 */
1231  CRYPTO_malloc_debug_init();
1232 #endif
1233 
1234 #if defined(V_CRYPTO_MDEBUG_ALL) /* <= 1.0.2 */
1235  CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
1236 #endif
1237 
1238 #if OPENSSL_VERSION_NUMBER < 0x10100000 /* <= 1.0.2 */
1239  {
1240  int i;
1241  /*
1242  * See crypto/ex_data.c; call def_get_class() immediately to avoid
1243  * allocations. 15 is the maximum number that is used as the class index
1244  * in OpenSSL 1.0.2.
1245  */
1246  for (i = 0; i <= 15; i++) {
1247  if (CRYPTO_get_ex_new_index(i, 0, (void *)"ossl-mdebug-dummy", 0, 0, 0) < 0)
1248  rb_raise(rb_eRuntimeError, "CRYPTO_get_ex_new_index for "
1249  "class index %d failed", i);
1250  }
1251  }
1252 #endif
1253 #endif
1254 #endif
1255 }
RUBY_SYMBOL_EXPORT_BEGIN rb_nativethread_id_t rb_nativethread_self()
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
void Init_ossl_kdf(void)
Definition: ossl_kdf.c:142
VALUE dOSSL
Definition: ossl.c:357
#define INT2NUM(x)
Definition: ruby.h:1538
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition: eval.c:835
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
void Init_ossl_engine(void)
Definition: ossl_engine.c:515
rb_nativethread_lock_t lock
Definition: ossl.c:521
void Init_ossl_config(void)
Definition: ossl_config.c:72
VALUE rb_ary_push(VALUE ary, VALUE item)
Definition: array.c:924
#define OSSL_IMPL_SK2ARY(name, type)
Definition: ossl.c:65
VALUE rb_funcall(VALUE, ID, int,...)
Calls a method.
Definition: vm_eval.c:774
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 OSSL_VERSION
Definition: ossl_version.h:13
void Init_ossl_asn1(void)
Definition: ossl_asn1.c:1361
void Init_ossl_rand(void)
Definition: ossl_rand.c:214
void Init_ossl_ocsp(void)
Definition: ossl_ocsp.c:1697
void ossl_debug(const char *fmt,...)
Definition: ossl.c:361
void rb_global_variable(VALUE *var)
Definition: gc.c:6276
void Init_openssl(void)
Definition: ossl.c:1100
#define RB_TYPE_P(obj, type)
Definition: ruby.h:527
VALUE ossl_to_der_if_possible(VALUE obj)
Definition: ossl.c:255
void ossl_clear_error(void)
Definition: ossl.c:304
#define ALLOC_N(type, n)
Definition: ruby.h:1587
VALUE cX509Cert
Definition: ossl_x509cert.c:30
#define val
void rb_nativethread_lock_destroy(rb_nativethread_lock_t *lock)
Definition: thread.c:362
VALUE rb_str_cat2(VALUE, const char *)
void rb_set_errinfo(VALUE err)
Sets the current exception ($!) to the given value.
Definition: eval.c:1792
VALUE rb_ary_new(void)
Definition: array.c:499
#define NIL_P(v)
Definition: ruby.h:451
void rb_define_const(VALUE, const char *, VALUE)
Definition: variable.c:2691
VALUE eOSSLError
Definition: ossl.c:236
#define Qfalse
Definition: ruby.h:436
void Init_ossl_hmac(void)
Definition: ossl_hmac.c:333
#define LONG_MAX
Definition: ruby.h:189
#define rb_str_new2
Definition: intern.h:835
int err
Definition: win32.c:135
void Init_ossl_digest(void)
Definition: ossl_digest.c:314
int ossl_pem_passwd_cb(char *buf, int max_len, int flag, void *pwd_)
Definition: ossl.c:177
#define RSTRING_LEN(str)
Definition: ruby.h:971
void rb_define_module_function(VALUE module, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a module function for module.
Definition: class.c:1731
VALUE rb_yield(VALUE)
Definition: vm_eval.c:973
void Init_ossl_pkcs12(void)
Definition: ossl_pkcs12.c:233
void rb_nativethread_lock_unlock(rb_nativethread_lock_t *lock)
Definition: thread.c:374
unsigned char buf[MIME_BUF_SIZE]
Definition: nkf.c:4309
unsigned long ID
Definition: ruby.h:86
#define Qnil
Definition: ruby.h:438
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition: eval.c:615
VALUE rb_eStandardError
Definition: error.c:799
unsigned long VALUE
Definition: ruby.h:85
#define OSSL_IMPL_ARY2SK(name, type, expected_class, dup)
Definition: ossl.c:17
VALUE ossl_pem_passwd_value(VALUE pass)
Definition: ossl.c:151
void Init_ossl_ssl(void)
Definition: ossl_ssl.c:2255
VALUE rb_str_new_cstr(const char *)
Definition: string.c:771
#define OSSL_Debug
Definition: ossl.h:144
void ossl_bin2hex(unsigned char *in, char *out, size_t inlen)
Definition: ossl.c:133
int rb_respond_to(VALUE, ID)
Definition: vm_method.c:1994
register unsigned int len
Definition: zonetab.h:51
void Init_ossl_ns_spki(void)
Definition: ossl_ns_spki.c:375
#define RSTRING_PTR(str)
Definition: ruby.h:975
#define rb_exc_new3
Definition: intern.h:244
Stores locks needed for OpenSSL thread safety.
Definition: ossl.c:520
VALUE ossl_get_errors(void)
Definition: ossl.c:341
int size
Definition: encoding.c:57
rb_nativethread_id_t owner
Definition: ossl.c:522
void Init_ossl_x509(void)
Definition: ossl_x509.c:30
VALUE rb_eRuntimeError
Definition: error.c:800
BN_CTX * ossl_bn_ctx
Definition: ossl_bn.c:158
#define RTEST(v)
Definition: ruby.h:450
void rb_warning(const char *fmt,...)
Definition: error.c:267
#define T_STRING
Definition: ruby.h:496
VALUE ossl_buf2str(char *buf, int len)
Definition: ossl.c:120
void ossl_raise(VALUE exc, const char *fmt,...)
Definition: ossl.c:293
#define assert
Definition: ruby_assert.h:37
void Init_ossl_bn(void)
Definition: ossl_bn.c:1082
void rb_nativethread_lock_initialize(rb_nativethread_lock_t *lock)
Definition: thread.c:356
X509 * DupX509CertPtr(VALUE)
Definition: ossl_x509cert.c:81
void Init_ossl_cipher(void)
Definition: ossl_cipher.c:817
void Init_ossl_pkcs7(void)
Definition: ossl_pkcs7.c:1043
VALUE ossl_str_new(const char *ptr, long len, int *pstate)
Definition: ossl.c:101
void Init_ossl_pkey(void)
Definition: ossl_pkey.c:389
void rb_nativethread_lock_lock(rb_nativethread_lock_t *lock)
Definition: thread.c:368
VALUE rb_define_module(const char *name)
Definition: class.c:768
#define rb_intern(str)
VALUE rb_vsprintf(const char *, va_list)
Definition: sprintf.c:1446
#define NULL
Definition: _sdbm.c:102
VALUE ossl_to_der(VALUE obj)
Definition: ossl.c:244
#define StringValue(v)
Definition: ruby.h:569
VALUE rb_str_new(const char *, long)
Definition: string.c:737