Ruby  2.0.0p451(2014-02-24revision45167)
ossl.c
Go to the documentation of this file.
1 /*
2  * $Id: ossl.c 44659 2014-01-19 16:28:53Z 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  str = rb_str_new_cstr(msg);
315  }
316  else {
317  rb_str_cat2(rb_str_cat2(str, ": "), msg);
318  }
319  }
320  if (dOSSL == Qtrue){ /* show all errors on the stack */
321  while ((e = ERR_get_error()) != 0){
322  rb_warn("error on stack: %s", ERR_error_string(e, NULL));
323  }
324  }
325  ERR_clear_error();
326 
327  if (NIL_P(str)) str = rb_str_new(0, 0);
328  return rb_exc_new3(exc, str);
329 }
330 
331 void
332 ossl_raise(VALUE exc, const char *fmt, ...)
333 {
334  va_list args;
335  VALUE err;
336  va_start(args, fmt);
337  err = ossl_make_error(exc, fmt, args);
338  va_end(args);
339  rb_exc_raise(err);
340 }
341 
342 VALUE
343 ossl_exc_new(VALUE exc, const char *fmt, ...)
344 {
345  va_list args;
346  VALUE err;
347  va_start(args, fmt);
348  err = ossl_make_error(exc, fmt, args);
349  va_end(args);
350  return err;
351 }
352 
353 /*
354  * call-seq:
355  * OpenSSL.errors -> [String...]
356  *
357  * See any remaining errors held in queue.
358  *
359  * Any errors you see here are probably due to a bug in ruby's OpenSSL implementation.
360  */
361 VALUE
363 {
364  VALUE ary;
365  long e;
366 
367  ary = rb_ary_new();
368  while ((e = ERR_get_error()) != 0){
369  rb_ary_push(ary, rb_str_new2(ERR_error_string(e, NULL)));
370  }
371 
372  return ary;
373 }
374 
375 /*
376  * Debug
377  */
379 
380 #if !defined(HAVE_VA_ARGS_MACRO)
381 void
382 ossl_debug(const char *fmt, ...)
383 {
384  va_list args;
385 
386  if (dOSSL == Qtrue) {
387  fprintf(stderr, "OSSL_DEBUG: ");
388  va_start(args, fmt);
389  vfprintf(stderr, fmt, args);
390  va_end(args);
391  fprintf(stderr, " [CONTEXT N/A]\n");
392  }
393 }
394 #endif
395 
396 /*
397  * call-seq:
398  * OpenSSL.debug -> true | false
399  */
400 static VALUE
402 {
403  return dOSSL;
404 }
405 
406 /*
407  * call-seq:
408  * OpenSSL.debug = boolean -> boolean
409  *
410  * Turns on or off CRYPTO_MEM_CHECK.
411  * Also shows some debugging message on stderr.
412  */
413 static VALUE
415 {
416  VALUE old = dOSSL;
417  dOSSL = val;
418 
419  if (old != dOSSL) {
420  if (dOSSL == Qtrue) {
421  CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
422  fprintf(stderr, "OSSL_DEBUG: IS NOW ON!\n");
423  } else if (old == Qtrue) {
424  CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_OFF);
425  fprintf(stderr, "OSSL_DEBUG: IS NOW OFF!\n");
426  }
427  }
428  return val;
429 }
430 
431 /*
432  * call-seq:
433  * OpenSSL.fips_mode = boolean -> boolean
434  *
435  * Turns FIPS mode on or off. Turning on FIPS mode will obviously only have an
436  * effect for FIPS-capable installations of the OpenSSL library. Trying to do
437  * so otherwise will result in an error.
438  *
439  * === Examples
440  *
441  * OpenSSL.fips_mode = true # turn FIPS mode on
442  * OpenSSL.fips_mode = false # and off again
443  */
444 static VALUE
446 {
447 
448 #ifdef HAVE_OPENSSL_FIPS
449  if (RTEST(enabled)) {
450  int mode = FIPS_mode();
451  if(!mode && !FIPS_mode_set(1)) /* turning on twice leads to an error */
452  ossl_raise(eOSSLError, "Turning on FIPS mode failed");
453  } else {
454  if(!FIPS_mode_set(0)) /* turning off twice is OK */
455  ossl_raise(eOSSLError, "Turning off FIPS mode failed");
456  }
457  return enabled;
458 #else
459  if (RTEST(enabled))
460  ossl_raise(eOSSLError, "This version of OpenSSL does not support FIPS mode");
461  return enabled;
462 #endif
463 }
464 
465 /*
466  * OpenSSL provides SSL, TLS and general purpose cryptography. It wraps the
467  * OpenSSL[http://www.openssl.org/] library.
468  *
469  * = Examples
470  *
471  * All examples assume you have loaded OpenSSL with:
472  *
473  * require 'openssl'
474  *
475  * These examples build atop each other. For example the key created in the
476  * next is used in throughout these examples.
477  *
478  * == Keys
479  *
480  * === Creating a Key
481  *
482  * This example creates a 2048 bit RSA keypair and writes it to the current
483  * directory.
484  *
485  * key = OpenSSL::PKey::RSA.new 2048
486  *
487  * open 'private_key.pem', 'w' do |io| io.write key.to_pem end
488  * open 'public_key.pem', 'w' do |io| io.write key.public_key.to_pem end
489  *
490  * === Exporting a Key
491  *
492  * Keys saved to disk without encryption are not secure as anyone who gets
493  * ahold of the key may use it unless it is encrypted. In order to securely
494  * export a key you may export it with a pass phrase.
495  *
496  * cipher = OpenSSL::Cipher.new 'AES-128-CBC'
497  * pass_phrase = 'my secure pass phrase goes here'
498  *
499  * key_secure = key.export cipher, pass_phrase
500  *
501  * open 'private.secure.pem', 'w' do |io|
502  * io.write key_secure
503  * end
504  *
505  * OpenSSL::Cipher.ciphers returns a list of available ciphers.
506  *
507  * === Loading a Key
508  *
509  * A key can also be loaded from a file.
510  *
511  * key2 = OpenSSL::PKey::RSA.new File.read 'private_key.pem'
512  * key2.public? # => true
513  *
514  * or
515  *
516  * key3 = OpenSSL::PKey::RSA.new File.read 'public_key.pem'
517  * key3.private? # => false
518  *
519  * === Loading an Encrypted Key
520  *
521  * OpenSSL will prompt you for your pass phrase when loading an encrypted key.
522  * If you will not be able to type in the pass phrase you may provide it when
523  * loading the key:
524  *
525  * key4_pem = File.read 'private.secure.pem'
526  * key4 = OpenSSL::PKey::RSA.new key4_pem, pass_phrase
527  *
528  * == RSA Encryption
529  *
530  * RSA provides encryption and decryption using the public and private keys.
531  * You can use a variety of padding methods depending upon the intended use of
532  * encrypted data.
533  *
534  * === Encryption & Decryption
535  *
536  * Asymmetric public/private key encryption is slow and victim to attack in
537  * cases where it is used without padding or directly to encrypt larger chunks
538  * of data. Typical use cases for RSA encryption involve "wrapping" a symmetric
539  * key with the public key of the recipient who would "unwrap" that symmetric
540  * key again using their private key.
541  * The following illustrates a simplified example of such a key transport
542  * scheme. It shouldn't be used in practice, though, standardized protocols
543  * should always be preferred.
544  *
545  * wrapped_key = key.public_encrypt key
546  *
547  * A symmetric key encrypted with the public key can only be decrypted with
548  * the corresponding private key of the recipient.
549  *
550  * original_key = key.private_decrypt wrapped_key
551  *
552  * By default PKCS#1 padding will be used, but it is also possible to use
553  * other forms of padding, see PKey::RSA for further details.
554  *
555  * === Signatures
556  *
557  * Using "private_encrypt" to encrypt some data with the private key is
558  * equivalent to applying a digital signature to the data. A verifying
559  * party may validate the signature by comparing the result of decrypting
560  * the signature with "public_decrypt" to the original data. However,
561  * OpenSSL::PKey already has methods "sign" and "verify" that handle
562  * digital signatures in a standardized way - "private_encrypt" and
563  * "public_decrypt" shouldn't be used in practice.
564  *
565  * To sign a document, a cryptographically secure hash of the document is
566  * computed first, which is then signed using the private key.
567  *
568  * digest = OpenSSL::Digest::SHA256.new
569  * signature = key.sign digest, document
570  *
571  * To validate the signature, again a hash of the document is computed and
572  * the signature is decrypted using the public key. The result is then
573  * compared to the hash just computed, if they are equal the signature was
574  * valid.
575  *
576  * digest = OpenSSL::Digest::SHA256.new
577  * if key.verify digest, signature, document
578  * puts 'Valid'
579  * else
580  * puts 'Invalid'
581  * end
582  *
583  * == PBKDF2 Password-based Encryption
584  *
585  * If supported by the underlying OpenSSL version used, Password-based
586  * Encryption should use the features of PKCS5. If not supported or if
587  * required by legacy applications, the older, less secure methods specified
588  * in RFC 2898 are also supported (see below).
589  *
590  * PKCS5 supports PBKDF2 as it was specified in PKCS#5
591  * v2.0[http://www.rsa.com/rsalabs/node.asp?id=2127]. It still uses a
592  * password, a salt, and additionally a number of iterations that will
593  * slow the key derivation process down. The slower this is, the more work
594  * it requires being able to brute-force the resulting key.
595  *
596  * === Encryption
597  *
598  * The strategy is to first instantiate a Cipher for encryption, and
599  * then to generate a random IV plus a key derived from the password
600  * using PBKDF2. PKCS #5 v2.0 recommends at least 8 bytes for the salt,
601  * the number of iterations largely depends on the hardware being used.
602  *
603  * cipher = OpenSSL::Cipher.new 'AES-128-CBC'
604  * cipher.encrypt
605  * iv = cipher.random_iv
606  *
607  * pwd = 'some hopefully not to easily guessable password'
608  * salt = OpenSSL::Random.random_bytes 16
609  * iter = 20000
610  * key_len = cipher.key_len
611  * digest = OpenSSL::Digest::SHA256.new
612  *
613  * key = OpenSSL::PKCS5.pbkdf2_hmac(pwd, salt, iter, key_len, digest)
614  * cipher.key = key
615  *
616  * Now encrypt the data:
617  *
618  * encrypted = cipher.update document
619  * encrypted << cipher.final
620  *
621  * === Decryption
622  *
623  * Use the same steps as before to derive the symmetric AES key, this time
624  * setting the Cipher up for decryption.
625  *
626  * cipher = OpenSSL::Cipher.new 'AES-128-CBC'
627  * cipher.decrypt
628  * cipher.iv = iv # the one generated with #random_iv
629  *
630  * pwd = 'some hopefully not to easily guessable password'
631  * salt = ... # the one generated above
632  * iter = 20000
633  * key_len = cipher.key_len
634  * digest = OpenSSL::Digest::SHA256.new
635  *
636  * key = OpenSSL::PKCS5.pbkdf2_hmac(pwd, salt, iter, key_len, digest)
637  * cipher.key = key
638  *
639  * Now decrypt the data:
640  *
641  * decrypted = cipher.update encrypted
642  * decrypted << cipher.final
643  *
644  * == PKCS #5 Password-based Encryption
645  *
646  * PKCS #5 is a password-based encryption standard documented at
647  * RFC2898[http://www.ietf.org/rfc/rfc2898.txt]. It allows a short password or
648  * passphrase to be used to create a secure encryption key. If possible, PBKDF2
649  * as described above should be used if the circumstances allow it.
650  *
651  * PKCS #5 uses a Cipher, a pass phrase and a salt to generate an encryption
652  * key.
653  *
654  * pass_phrase = 'my secure pass phrase goes here'
655  * salt = '8 octets'
656  *
657  * === Encryption
658  *
659  * First set up the cipher for encryption
660  *
661  * encrypter = OpenSSL::Cipher.new 'AES-128-CBC'
662  * encrypter.encrypt
663  * encrypter.pkcs5_keyivgen pass_phrase, salt
664  *
665  * Then pass the data you want to encrypt through
666  *
667  * encrypted = encrypter.update 'top secret document'
668  * encrypted << encrypter.final
669  *
670  * === Decryption
671  *
672  * Use a new Cipher instance set up for decryption
673  *
674  * decrypter = OpenSSL::Cipher.new 'AES-128-CBC'
675  * decrypter.decrypt
676  * decrypter.pkcs5_keyivgen pass_phrase, salt
677  *
678  * Then pass the data you want to decrypt through
679  *
680  * plain = decrypter.update encrypted
681  * plain << decrypter.final
682  *
683  * == X509 Certificates
684  *
685  * === Creating a Certificate
686  *
687  * This example creates a self-signed certificate using an RSA key and a SHA1
688  * signature.
689  *
690  * name = OpenSSL::X509::Name.parse 'CN=nobody/DC=example'
691  *
692  * cert = OpenSSL::X509::Certificate.new
693  * cert.version = 2
694  * cert.serial = 0
695  * cert.not_before = Time.now
696  * cert.not_after = Time.now + 3600
697  *
698  * cert.public_key = key.public_key
699  * cert.subject = name
700  *
701  * === Certificate Extensions
702  *
703  * You can add extensions to the certificate with
704  * OpenSSL::SSL::ExtensionFactory to indicate the purpose of the certificate.
705  *
706  * extension_factory = OpenSSL::X509::ExtensionFactory.new nil, cert
707  *
708  * cert.add_extension \
709  * extension_factory.create_extension('basicConstraints', 'CA:FALSE', true)
710  *
711  * cert.add_extension \
712  * extension_factory.create_extension(
713  * 'keyUsage', 'keyEncipherment,dataEncipherment,digitalSignature')
714  *
715  * cert.add_extension \
716  * extension_factory.create_extension('subjectKeyIdentifier', 'hash')
717  *
718  * The list of supported extensions (and in some cases their possible values)
719  * can be derived from the "objects.h" file in the OpenSSL source code.
720  *
721  * === Signing a Certificate
722  *
723  * To sign a certificate set the issuer and use OpenSSL::X509::Certificate#sign
724  * with a digest algorithm. This creates a self-signed cert because we're using
725  * the same name and key to sign the certificate as was used to create the
726  * certificate.
727  *
728  * cert.issuer = name
729  * cert.sign key, OpenSSL::Digest::SHA1.new
730  *
731  * open 'certificate.pem', 'w' do |io| io.write cert.to_pem end
732  *
733  * === Loading a Certificate
734  *
735  * Like a key, a cert can also be loaded from a file.
736  *
737  * cert2 = OpenSSL::X509::Certificate.new File.read 'certificate.pem'
738  *
739  * === Verifying a Certificate
740  *
741  * Certificate#verify will return true when a certificate was signed with the
742  * given public key.
743  *
744  * raise 'certificate can not be verified' unless cert2.verify key
745  *
746  * == Certificate Authority
747  *
748  * A certificate authority (CA) is a trusted third party that allows you to
749  * verify the ownership of unknown certificates. The CA issues key signatures
750  * that indicate it trusts the user of that key. A user encountering the key
751  * can verify the signature by using the CA's public key.
752  *
753  * === CA Key
754  *
755  * CA keys are valuable, so we encrypt and save it to disk and make sure it is
756  * not readable by other users.
757  *
758  * ca_key = OpenSSL::PKey::RSA.new 2048
759  *
760  * cipher = OpenSSL::Cipher::Cipher.new 'AES-128-CBC'
761  *
762  * open 'ca_key.pem', 'w', 0400 do |io|
763  * io.write key.export(cipher, pass_phrase)
764  * end
765  *
766  * === CA Certificate
767  *
768  * A CA certificate is created the same way we created a certificate above, but
769  * with different extensions.
770  *
771  * ca_name = OpenSSL::X509::Name.parse 'CN=ca/DC=example'
772  *
773  * ca_cert = OpenSSL::X509::Certificate.new
774  * ca_cert.serial = 0
775  * ca_cert.version = 2
776  * ca_cert.not_before = Time.now
777  * ca_cert.not_after = Time.now + 86400
778  *
779  * ca_cert.public_key = ca_key.public_key
780  * ca_cert.subject = ca_name
781  * ca_cert.issuer = ca_name
782  *
783  * extension_factory = OpenSSL::X509::ExtensionFactory.new
784  * extension_factory.subject_certificate = ca_cert
785  * extension_factory.issuer_certificate = ca_cert
786  *
787  * ca_cert.add_extension \
788  * extension_factory.create_extension('subjectKeyIdentifier', 'hash')
789  *
790  * This extension indicates the CA's key may be used as a CA.
791  *
792  * ca_cert.add_extension \
793  * extension_factory.create_extension('basicConstraints', 'CA:TRUE', true)
794  *
795  * This extension indicates the CA's key may be used to verify signatures on
796  * both certificates and certificate revocations.
797  *
798  * ca_cert.add_extension \
799  * extension_factory.create_extension(
800  * 'keyUsage', 'cRLSign,keyCertSign', true)
801  *
802  * Root CA certificates are self-signed.
803  *
804  * ca_cert.sign ca_key, OpenSSL::Digest::SHA1.new
805  *
806  * The CA certificate is saved to disk so it may be distributed to all the
807  * users of the keys this CA will sign.
808  *
809  * open 'ca_cert.pem', 'w' do |io|
810  * io.write ca_cert.to_pem
811  * end
812  *
813  * === Certificate Signing Request
814  *
815  * The CA signs keys through a Certificate Signing Request (CSR). The CSR
816  * contains the information necessary to identify the key.
817  *
818  * csr = OpenSSL::X509::Request.new
819  * csr.version = 0
820  * csr.subject = name
821  * csr.public_key = key.public_key
822  * csr.sign key, OpenSSL::Digest::SHA1.new
823  *
824  * A CSR is saved to disk and sent to the CA for signing.
825  *
826  * open 'csr.pem', 'w' do |io|
827  * io.write csr.to_pem
828  * end
829  *
830  * === Creating a Certificate from a CSR
831  *
832  * Upon receiving a CSR the CA will verify it before signing it. A minimal
833  * verification would be to check the CSR's signature.
834  *
835  * csr = OpenSSL::X509::Request.new File.read 'csr.pem'
836  *
837  * raise 'CSR can not be verified' unless csr.verify csr.public_key
838  *
839  * After verification a certificate is created, marked for various usages,
840  * signed with the CA key and returned to the requester.
841  *
842  * csr_cert = OpenSSL::X509::Certificate.new
843  * csr_cert.serial = 0
844  * csr_cert.version = 2
845  * csr_cert.not_before = Time.now
846  * csr_cert.not_after = Time.now + 600
847  *
848  * csr_cert.subject = csr.subject
849  * csr_cert.public_key = csr.public_key
850  * csr_cert.issuer = ca_cert.subject
851  *
852  * extension_factory = OpenSSL::X509::ExtensionFactory.new
853  * extension_factory.subject_certificate = csr_cert
854  * extension_factory.issuer_certificate = ca_cert
855  *
856  * csr_cert.add_extension \
857  * extension_factory.create_extension('basicConstraints', 'CA:FALSE')
858  *
859  * csr_cert.add_extension \
860  * extension_factory.create_extension(
861  * 'keyUsage', 'keyEncipherment,dataEncipherment,digitalSignature')
862  *
863  * csr_cert.add_extension \
864  * extension_factory.create_extension('subjectKeyIdentifier', 'hash')
865  *
866  * csr_cert.sign ca_key, OpenSSL::Digest::SHA1.new
867  *
868  * open 'csr_cert.pem', 'w' do |io|
869  * io.write csr_cert.to_pem
870  * end
871  *
872  * == SSL and TLS Connections
873  *
874  * Using our created key and certificate we can create an SSL or TLS connection.
875  * An SSLContext is used to set up an SSL session.
876  *
877  * context = OpenSSL::SSL::SSLContext.new
878  *
879  * === SSL Server
880  *
881  * An SSL server requires the certificate and private key to communicate
882  * securely with its clients:
883  *
884  * context.cert = cert
885  * context.key = key
886  *
887  * Then create an SSLServer with a TCP server socket and the context. Use the
888  * SSLServer like an ordinary TCP server.
889  *
890  * require 'socket'
891  *
892  * tcp_server = TCPServer.new 5000
893  * ssl_server = OpenSSL::SSL::SSLServer.new tcp_server, context
894  *
895  * loop do
896  * ssl_connection = ssl_server.accept
897  *
898  * data = connection.gets
899  *
900  * response = "I got #{data.dump}"
901  * puts response
902  *
903  * connection.puts "I got #{data.dump}"
904  * connection.close
905  * end
906  *
907  * === SSL client
908  *
909  * An SSL client is created with a TCP socket and the context.
910  * SSLSocket#connect must be called to initiate the SSL handshake and start
911  * encryption. A key and certificate are not required for the client socket.
912  *
913  * require 'socket'
914  *
915  * tcp_client = TCPSocket.new 'localhost', 5000
916  * ssl_client = OpenSSL::SSL::SSLSocket.new client_socket, context
917  * ssl_client.connect
918  *
919  * ssl_client.puts "hello server!"
920  * puts ssl_client.gets
921  *
922  * === Peer Verification
923  *
924  * An unverified SSL connection does not provide much security. For enhanced
925  * security the client or server can verify the certificate of its peer.
926  *
927  * The client can be modified to verify the server's certificate against the
928  * certificate authority's certificate:
929  *
930  * context.ca_file = 'ca_cert.pem'
931  * context.verify_mode = OpenSSL::SSL::VERIFY_PEER
932  *
933  * require 'socket'
934  *
935  * tcp_client = TCPSocket.new 'localhost', 5000
936  * ssl_client = OpenSSL::SSL::SSLSocket.new client_socket, context
937  * ssl_client.connect
938  *
939  * ssl_client.puts "hello server!"
940  * puts ssl_client.gets
941  *
942  * If the server certificate is invalid or <tt>context.ca_file</tt> is not set
943  * when verifying peers an OpenSSL::SSL::SSLError will be raised.
944  *
945  */
946 void
948 {
949  /*
950  * Init timezone info
951  */
952 #if 0
953  tzset();
954 #endif
955 
956  /*
957  * Init all digests, ciphers
958  */
959  /* CRYPTO_malloc_init(); */
960  /* ENGINE_load_builtin_engines(); */
961  OpenSSL_add_ssl_algorithms();
962  OpenSSL_add_all_algorithms();
963  ERR_load_crypto_strings();
964  SSL_load_error_strings();
965 
966  /*
967  * FIXME:
968  * On unload do:
969  */
970 #if 0
971  CONF_modules_unload(1);
972  destroy_ui_method();
973  EVP_cleanup();
974  ENGINE_cleanup();
975  CRYPTO_cleanup_all_ex_data();
976  ERR_remove_state(0);
977  ERR_free_strings();
978 #endif
979 
980  /*
981  * Init main module
982  */
983  mOSSL = rb_define_module("OpenSSL");
984 
985  /*
986  * OpenSSL ruby extension version
987  */
988  rb_define_const(mOSSL, "VERSION", rb_str_new2(OSSL_VERSION));
989 
990  /*
991  * Version of OpenSSL the ruby OpenSSL extension was built with
992  */
993  rb_define_const(mOSSL, "OPENSSL_VERSION", rb_str_new2(OPENSSL_VERSION_TEXT));
994 
995  /*
996  * Version number of OpenSSL the ruby OpenSSL extension was built with
997  * (base 16)
998  */
999  rb_define_const(mOSSL, "OPENSSL_VERSION_NUMBER", INT2NUM(OPENSSL_VERSION_NUMBER));
1000 
1001  /*
1002  * Boolean indicating whether OpenSSL is FIPS-enabled or not
1003  */
1004 #ifdef HAVE_OPENSSL_FIPS
1005  rb_define_const(mOSSL, "OPENSSL_FIPS", Qtrue);
1006 #else
1007  rb_define_const(mOSSL, "OPENSSL_FIPS", Qfalse);
1008 #endif
1009  rb_define_module_function(mOSSL, "fips_mode=", ossl_fips_mode_set, 1);
1010 
1011  /*
1012  * Generic error,
1013  * common for all classes under OpenSSL module
1014  */
1015  eOSSLError = rb_define_class_under(mOSSL,"OpenSSLError",rb_eStandardError);
1016 
1017  /*
1018  * Verify callback Proc index for ext-data
1019  */
1020  if ((ossl_verify_cb_idx = X509_STORE_CTX_get_ex_new_index(0, (void *)"ossl_verify_cb_idx", 0, 0, 0)) < 0)
1021  ossl_raise(eOSSLError, "X509_STORE_CTX_get_ex_new_index");
1022 
1023  /*
1024  * Init debug core
1025  */
1026  dOSSL = Qfalse;
1027  rb_define_module_function(mOSSL, "debug", ossl_debug_get, 0);
1028  rb_define_module_function(mOSSL, "debug=", ossl_debug_set, 1);
1029  rb_define_module_function(mOSSL, "errors", ossl_get_errors, 0);
1030 
1031  /*
1032  * Get ID of to_der
1033  */
1034  ossl_s_to_der = rb_intern("to_der");
1035 
1036  /*
1037  * Init components
1038  */
1039  Init_ossl_bn();
1040  Init_ossl_cipher();
1041  Init_ossl_config();
1042  Init_ossl_digest();
1043  Init_ossl_hmac();
1045  Init_ossl_pkcs12();
1046  Init_ossl_pkcs7();
1047  Init_ossl_pkcs5();
1048  Init_ossl_pkey();
1049  Init_ossl_rand();
1050  Init_ossl_ssl();
1051  Init_ossl_x509();
1052  Init_ossl_ocsp();
1053  Init_ossl_engine();
1054  Init_ossl_asn1();
1055 }
1056 
1057 #if defined(OSSL_DEBUG)
1058 /*
1059  * Check if all symbols are OK with 'make LDSHARED=gcc all'
1060  */
1061 int
1062 main(int argc, char *argv[])
1063 {
1064  return 0;
1065 }
1066 #endif /* OSSL_DEBUG */
1067 
VALUE rb_eStandardError
Definition: error.c:509
VALUE mOSSL
Definition: ossl.c:259
static VALUE ossl_str_new(int size)
Definition: ossl.c:128
VALUE dOSSL
Definition: ossl.c:378
ID ossl_s_to_der
Definition: ossl.c:269
int i
Definition: win32ole.c:784
unsigned long VALUE
Definition: ripper.y:104
void Init_ossl_config()
Definition: ossl_config.c:63
VALUE rb_str_new_cstr(const char *)
Definition: string.c:447
VALUE rb_ary_push(VALUE ary, VALUE item)
Definition: array.c:822
void Init_ossl_bn()
Definition: ossl_bn.c:736
#define OSSL_IMPL_SK2ARY(name, type)
Definition: ossl.c:98
#define RSTRING_PTR(str)
VALUE rb_protect(VALUE(*proc)(VALUE), VALUE data, int *state)
Definition: eval.c:771
VALUE rb_funcall(VALUE, ID, int,...)
Calls a method.
Definition: vm_eval.c:773
#define Qnil
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition: class.c:545
#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:342
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
#define rb_str_new2
int ossl_verify_cb_idx
Definition: ossl.c:201
VALUE ossl_get_errors()
Definition: ossl.c:362
void ossl_debug(const char *fmt,...)
Definition: ossl.c:382
void Init_ossl_pkcs7()
Definition: ossl_pkcs7.c:981
void Init_ossl_hmac()
Definition: ossl_hmac.c:237
VALUE ossl_exc_new(VALUE exc, const char *fmt,...)
Definition: ossl.c:343
void Init_openssl()
Definition: ossl.c:947
void rb_exc_raise(VALUE mesg)
Definition: eval.c:527
static VALUE ossl_pem_passwd_cb0(VALUE flag)
Definition: ossl.c:151
int args
Definition: win32ole.c:785
static VALUE ossl_fips_mode_set(VALUE self, VALUE enabled)
Definition: ossl.c:445
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
int rb_block_given_p(void)
Definition: eval.c:672
VALUE preverify_ok
Definition: ossl.h:172
VALUE cX509Cert
Definition: ossl_x509cert.c:33
void Init_ossl_ssl()
Definition: ossl_ssl.c:1823
void Init_ossl_ocsp()
Definition: ossl_ocsp.c:783
#define val
#define Qtrue
VALUE ossl_x509stctx_new(X509_STORE_CTX *)
void Init_ossl_asn1()
Definition: ossl_asn1.c:1444
VALUE rb_ary_new(void)
Definition: array.c:424
unsigned long ID
Definition: ripper.y:105
void rb_define_const(VALUE, const char *, VALUE)
Definition: variable.c:2202
VALUE rb_str_cat2(VALUE, const char *)
Definition: string.c:1983
static char msg[50]
Definition: strerror.c:8
#define Qfalse
VALUE eOSSLError
Definition: ossl.c:264
int argc
Definition: ruby.c:130
#define NIL_P(v)
void Init_ossl_rand()
Definition: ossl_rand.c:182
int err
Definition: win32.c:87
void Init_ossl_engine()
Definition: ossl_engine.c:423
int PEM_def_callback(char *buf, int num, int w, void *key)
static VALUE ossl_debug_get(VALUE self)
Definition: ossl.c:401
VALUE rb_yield(VALUE)
Definition: vm_eval.c:933
#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:1512
#define StringValue(v)
unsigned char buf[MIME_BUF_SIZE]
Definition: nkf.c:4308
#define OSSL_IMPL_ARY2SK(name, type, expected_class, dup)
Definition: ossl.c:50
void rb_jump_tag(int tag)
Definition: eval.c:666
static VALUE ossl_debug_set(VALUE self, VALUE val)
Definition: ossl.c:414
#define _(args)
Definition: dln.h:28
VALUE rb_vsprintf(const char *, va_list)
Definition: sprintf.c:1264
void Init_ossl_digest()
Definition: ossl_digest.c:297
int size
Definition: encoding.c:52
VALUE rb_exc_new3(VALUE etype, VALUE str)
Definition: error.c:548
void rb_set_errinfo(VALUE err)
Definition: eval.c:1436
VALUE ossl_buf2str(char *buf, int len)
Definition: ossl.c:134
#define INT2NUM(x)
int rb_respond_to(VALUE, ID)
Definition: vm_method.c:1583
void ossl_raise(VALUE exc, const char *fmt,...)
Definition: ossl.c:332
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:425
int main(int argc, char **argv)
Definition: nkf.c:6918
void Init_ossl_cipher(void)
Definition: ossl_cipher.c:741
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:229
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:617
#define rb_intern(str)
void Init_ossl_x509()
Definition: ossl_x509.c:20
#define NULL
Definition: _sdbm.c:103
void rb_warn(const char *fmt,...)
Definition: error.c:216
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
char ** argv
Definition: ruby.c:131