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