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