ext/openssl/ossl.c

Go to the documentation of this file.
00001 /*
00002  * $Id: ossl.c 46525 2014-06-23 16:03:42Z nagachika $
00003  * 'OpenSSL for Ruby' project
00004  * Copyright (C) 2001-2002  Michal Rokos <m.rokos@sh.cvut.cz>
00005  * All rights reserved.
00006  */
00007 /*
00008  * This program is licenced under the same licence as Ruby.
00009  * (See the file 'LICENCE'.)
00010  */
00011 #include "ossl.h"
00012 #include <stdarg.h> /* for ossl_raise */
00013 
00014 /*
00015  * String to HEXString conversion
00016  */
00017 int
00018 string2hex(const unsigned char *buf, int buf_len, char **hexbuf, int *hexbuf_len)
00019 {
00020     static const char hex[]="0123456789abcdef";
00021     int i, len = 2 * buf_len;
00022 
00023     if (buf_len < 0 || len < buf_len) { /* PARANOIA? */
00024         return -1;
00025     }
00026     if (!hexbuf) { /* if no buf, return calculated len */
00027         if (hexbuf_len) {
00028             *hexbuf_len = len;
00029         }
00030         return len;
00031     }
00032     if (!(*hexbuf = OPENSSL_malloc(len + 1))) {
00033         return -1;
00034     }
00035     for (i = 0; i < buf_len; i++) {
00036         (*hexbuf)[2 * i] = hex[((unsigned char)buf[i]) >> 4];
00037         (*hexbuf)[2 * i + 1] = hex[buf[i] & 0x0f];
00038     }
00039     (*hexbuf)[2 * i] = '\0';
00040 
00041     if (hexbuf_len) {
00042         *hexbuf_len = len;
00043     }
00044     return len;
00045 }
00046 
00047 /*
00048  * Data Conversion
00049  */
00050 #define OSSL_IMPL_ARY2SK(name, type, expected_class, dup)       \
00051 STACK_OF(type) *                                                \
00052 ossl_##name##_ary2sk0(VALUE ary)                                \
00053 {                                                               \
00054     STACK_OF(type) *sk;                                         \
00055     VALUE val;                                                  \
00056     type *x;                                                    \
00057     int i;                                                      \
00058                                                                 \
00059     Check_Type(ary, T_ARRAY);                                   \
00060     sk = sk_##type##_new_null();                                \
00061     if (!sk) ossl_raise(eOSSLError, NULL);                      \
00062                                                                 \
00063     for (i = 0; i < RARRAY_LEN(ary); i++) {                     \
00064         val = rb_ary_entry(ary, i);                             \
00065         if (!rb_obj_is_kind_of(val, expected_class)) {          \
00066             sk_##type##_pop_free(sk, type##_free);              \
00067             ossl_raise(eOSSLError, "object in array not"        \
00068                        " of class ##type##");                   \
00069         }                                                       \
00070         x = dup(val); /* NEED TO DUP */                         \
00071         sk_##type##_push(sk, x);                                \
00072     }                                                           \
00073     return sk;                                                  \
00074 }                                                               \
00075                                                                 \
00076 STACK_OF(type) *                                                \
00077 ossl_protect_##name##_ary2sk(VALUE ary, int *status)            \
00078 {                                                               \
00079     return (STACK_OF(type)*)rb_protect(                         \
00080             (VALUE(*)_((VALUE)))ossl_##name##_ary2sk0,          \
00081             ary,                                                \
00082             status);                                            \
00083 }                                                               \
00084                                                                 \
00085 STACK_OF(type) *                                                \
00086 ossl_##name##_ary2sk(VALUE ary)                                 \
00087 {                                                               \
00088     STACK_OF(type) *sk;                                         \
00089     int status = 0;                                             \
00090                                                                 \
00091     sk = ossl_protect_##name##_ary2sk(ary, &status);            \
00092     if (status) rb_jump_tag(status);                            \
00093                                                                 \
00094     return sk;                                                  \
00095 }
00096 OSSL_IMPL_ARY2SK(x509, X509, cX509Cert, DupX509CertPtr)
00097 
00098 #define OSSL_IMPL_SK2ARY(name, type)            \
00099 VALUE                                           \
00100 ossl_##name##_sk2ary(STACK_OF(type) *sk)        \
00101 {                                               \
00102     type *t;                                    \
00103     int i, num;                                 \
00104     VALUE ary;                                  \
00105                                                 \
00106     if (!sk) {                                  \
00107         OSSL_Debug("empty sk!");                \
00108         return Qnil;                            \
00109     }                                           \
00110     num = sk_##type##_num(sk);                  \
00111     if (num < 0) {                              \
00112         OSSL_Debug("items in sk < -1???");      \
00113         return rb_ary_new();                    \
00114     }                                           \
00115     ary = rb_ary_new2(num);                     \
00116                                                 \
00117     for (i=0; i<num; i++) {                     \
00118         t = sk_##type##_value(sk, i);           \
00119         rb_ary_push(ary, ossl_##name##_new(t)); \
00120     }                                           \
00121     return ary;                                 \
00122 }
00123 OSSL_IMPL_SK2ARY(x509, X509)
00124 OSSL_IMPL_SK2ARY(x509crl, X509_CRL)
00125 OSSL_IMPL_SK2ARY(x509name, X509_NAME)
00126 
00127 static VALUE
00128 ossl_str_new(int size)
00129 {
00130     return rb_str_new(0, size);
00131 }
00132 
00133 VALUE
00134 ossl_buf2str(char *buf, int len)
00135 {
00136     VALUE str;
00137     int status = 0;
00138 
00139     str = rb_protect((VALUE(*)_((VALUE)))ossl_str_new, len, &status);
00140     if(!NIL_P(str)) memcpy(RSTRING_PTR(str), buf, len);
00141     OPENSSL_free(buf);
00142     if(status) rb_jump_tag(status);
00143 
00144     return str;
00145 }
00146 
00147 /*
00148  * our default PEM callback
00149  */
00150 static VALUE
00151 ossl_pem_passwd_cb0(VALUE flag)
00152 {
00153     VALUE pass;
00154 
00155     pass = rb_yield(flag);
00156     SafeStringValue(pass);
00157 
00158     return pass;
00159 }
00160 
00161 int
00162 ossl_pem_passwd_cb(char *buf, int max_len, int flag, void *pwd)
00163 {
00164     int len, status = 0;
00165     VALUE rflag, pass;
00166 
00167     if (pwd || !rb_block_given_p())
00168         return PEM_def_callback(buf, max_len, flag, pwd);
00169 
00170     while (1) {
00171         /*
00172          * when the flag is nonzero, this passphrase
00173          * will be used to perform encryption; otherwise it will
00174          * be used to perform decryption.
00175          */
00176         rflag = flag ? Qtrue : Qfalse;
00177         pass  = rb_protect(ossl_pem_passwd_cb0, rflag, &status);
00178         if (status) {
00179             /* ignore an exception raised. */
00180             rb_set_errinfo(Qnil);
00181             return -1;
00182         }
00183         len = RSTRING_LENINT(pass);
00184         if (len < 4) { /* 4 is OpenSSL hardcoded limit */
00185             rb_warning("password must be longer than 4 bytes");
00186             continue;
00187         }
00188         if (len > max_len) {
00189             rb_warning("password must be shorter then %d bytes", max_len-1);
00190             continue;
00191         }
00192         memcpy(buf, RSTRING_PTR(pass), len);
00193         break;
00194     }
00195     return len;
00196 }
00197 
00198 /*
00199  * Verify callback
00200  */
00201 int ossl_verify_cb_idx;
00202 
00203 VALUE
00204 ossl_call_verify_cb_proc(struct ossl_verify_cb_args *args)
00205 {
00206     return rb_funcall(args->proc, rb_intern("call"), 2,
00207                       args->preverify_ok, args->store_ctx);
00208 }
00209 
00210 int
00211 ossl_verify_cb(int ok, X509_STORE_CTX *ctx)
00212 {
00213     VALUE proc, rctx, ret;
00214     struct ossl_verify_cb_args args;
00215     int state = 0;
00216 
00217     proc = (VALUE)X509_STORE_CTX_get_ex_data(ctx, ossl_verify_cb_idx);
00218     if ((void*)proc == 0)
00219         proc = (VALUE)X509_STORE_get_ex_data(ctx->ctx, ossl_verify_cb_idx);
00220     if ((void*)proc == 0)
00221         return ok;
00222     if (!NIL_P(proc)) {
00223         ret = Qfalse;
00224         rctx = rb_protect((VALUE(*)(VALUE))ossl_x509stctx_new,
00225                           (VALUE)ctx, &state);
00226         if (state) {
00227             rb_set_errinfo(Qnil);
00228             rb_warn("StoreContext initialization failure");
00229         }
00230         else {
00231             args.proc = proc;
00232             args.preverify_ok = ok ? Qtrue : Qfalse;
00233             args.store_ctx = rctx;
00234             ret = rb_protect((VALUE(*)(VALUE))ossl_call_verify_cb_proc, (VALUE)&args, &state);
00235             if (state) {
00236                 rb_set_errinfo(Qnil);
00237                 rb_warn("exception in verify_callback is ignored");
00238             }
00239             ossl_x509stctx_clear_ptr(rctx);
00240         }
00241         if (ret == Qtrue) {
00242             X509_STORE_CTX_set_error(ctx, X509_V_OK);
00243             ok = 1;
00244         }
00245         else{
00246             if (X509_STORE_CTX_get_error(ctx) == X509_V_OK) {
00247                 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_REJECTED);
00248             }
00249             ok = 0;
00250         }
00251     }
00252 
00253     return ok;
00254 }
00255 
00256 /*
00257  * main module
00258  */
00259 VALUE mOSSL;
00260 
00261 /*
00262  * OpenSSLError < StandardError
00263  */
00264 VALUE eOSSLError;
00265 
00266 /*
00267  * Convert to DER string
00268  */
00269 ID ossl_s_to_der;
00270 
00271 VALUE
00272 ossl_to_der(VALUE obj)
00273 {
00274     VALUE tmp;
00275 
00276     tmp = rb_funcall(obj, ossl_s_to_der, 0);
00277     StringValue(tmp);
00278 
00279     return tmp;
00280 }
00281 
00282 VALUE
00283 ossl_to_der_if_possible(VALUE obj)
00284 {
00285     if(rb_respond_to(obj, ossl_s_to_der))
00286         return ossl_to_der(obj);
00287     return obj;
00288 }
00289 
00290 /*
00291  * Errors
00292  */
00293 static VALUE
00294 ossl_make_error(VALUE exc, const char *fmt, va_list args)
00295 {
00296     VALUE str = Qnil;
00297     const char *msg;
00298     long e;
00299 
00300 #ifdef HAVE_ERR_PEEK_LAST_ERROR
00301     e = ERR_peek_last_error();
00302 #else
00303     e = ERR_peek_error();
00304 #endif
00305     if (fmt) {
00306         str = rb_vsprintf(fmt, args);
00307     }
00308     if (e) {
00309         if (dOSSL == Qtrue) /* FULL INFO */
00310             msg = ERR_error_string(e, NULL);
00311         else
00312             msg = ERR_reason_error_string(e);
00313         if (NIL_P(str)) {
00314             if (msg) str = rb_str_new_cstr(msg);
00315         }
00316         else {
00317             if (RSTRING_LEN(str)) rb_str_cat2(str, ": ");
00318             rb_str_cat2(str, msg ? msg : "(null)");
00319         }
00320     }
00321     if (dOSSL == Qtrue){ /* show all errors on the stack */
00322         while ((e = ERR_get_error()) != 0){
00323             rb_warn("error on stack: %s", ERR_error_string(e, NULL));
00324         }
00325     }
00326     ERR_clear_error();
00327 
00328     if (NIL_P(str)) str = rb_str_new(0, 0);
00329     return rb_exc_new3(exc, str);
00330 }
00331 
00332 void
00333 ossl_raise(VALUE exc, const char *fmt, ...)
00334 {
00335     va_list args;
00336     VALUE err;
00337     va_start(args, fmt);
00338     err = ossl_make_error(exc, fmt, args);
00339     va_end(args);
00340     rb_exc_raise(err);
00341 }
00342 
00343 VALUE
00344 ossl_exc_new(VALUE exc, const char *fmt, ...)
00345 {
00346     va_list args;
00347     VALUE err;
00348     va_start(args, fmt);
00349     err = ossl_make_error(exc, fmt, args);
00350     va_end(args);
00351     return err;
00352 }
00353 
00354 /*
00355  * call-seq:
00356  *   OpenSSL.errors -> [String...]
00357  *
00358  * See any remaining errors held in queue.
00359  *
00360  * Any errors you see here are probably due to a bug in ruby's OpenSSL implementation.
00361  */
00362 VALUE
00363 ossl_get_errors()
00364 {
00365     VALUE ary;
00366     long e;
00367 
00368     ary = rb_ary_new();
00369     while ((e = ERR_get_error()) != 0){
00370         rb_ary_push(ary, rb_str_new2(ERR_error_string(e, NULL)));
00371     }
00372 
00373     return ary;
00374 }
00375 
00376 /*
00377  * Debug
00378  */
00379 VALUE dOSSL;
00380 
00381 #if !defined(HAVE_VA_ARGS_MACRO)
00382 void
00383 ossl_debug(const char *fmt, ...)
00384 {
00385     va_list args;
00386 
00387     if (dOSSL == Qtrue) {
00388         fprintf(stderr, "OSSL_DEBUG: ");
00389         va_start(args, fmt);
00390         vfprintf(stderr, fmt, args);
00391         va_end(args);
00392         fprintf(stderr, " [CONTEXT N/A]\n");
00393     }
00394 }
00395 #endif
00396 
00397 /*
00398  * call-seq:
00399  *   OpenSSL.debug -> true | false
00400  */
00401 static VALUE
00402 ossl_debug_get(VALUE self)
00403 {
00404     return dOSSL;
00405 }
00406 
00407 /*
00408  * call-seq:
00409  *   OpenSSL.debug = boolean -> boolean
00410  *
00411  * Turns on or off CRYPTO_MEM_CHECK.
00412  * Also shows some debugging message on stderr.
00413  */
00414 static VALUE
00415 ossl_debug_set(VALUE self, VALUE val)
00416 {
00417     VALUE old = dOSSL;
00418     dOSSL = val;
00419 
00420     if (old != dOSSL) {
00421         if (dOSSL == Qtrue) {
00422             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
00423             fprintf(stderr, "OSSL_DEBUG: IS NOW ON!\n");
00424         } else if (old == Qtrue) {
00425             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_OFF);
00426             fprintf(stderr, "OSSL_DEBUG: IS NOW OFF!\n");
00427         }
00428     }
00429     return val;
00430 }
00431 
00432 /*
00433  * call-seq:
00434  *   OpenSSL.fips_mode = boolean -> boolean
00435  *
00436  * Turns FIPS mode on or off. Turning on FIPS mode will obviously only have an
00437  * effect for FIPS-capable installations of the OpenSSL library. Trying to do
00438  * so otherwise will result in an error.
00439  *
00440  * === Examples
00441  *
00442  * OpenSSL.fips_mode = true   # turn FIPS mode on
00443  * OpenSSL.fips_mode = false  # and off again
00444  */
00445 static VALUE
00446 ossl_fips_mode_set(VALUE self, VALUE enabled)
00447 {
00448 
00449 #ifdef HAVE_OPENSSL_FIPS
00450     if (RTEST(enabled)) {
00451         int mode = FIPS_mode();
00452         if(!mode && !FIPS_mode_set(1)) /* turning on twice leads to an error */
00453             ossl_raise(eOSSLError, "Turning on FIPS mode failed");
00454     } else {
00455         if(!FIPS_mode_set(0)) /* turning off twice is OK */
00456             ossl_raise(eOSSLError, "Turning off FIPS mode failed");
00457     }
00458     return enabled;
00459 #else
00460     if (RTEST(enabled))
00461         ossl_raise(eOSSLError, "This version of OpenSSL does not support FIPS mode");
00462     return enabled;
00463 #endif
00464 }
00465 
00469 #include "../../thread_native.h"
00470 static rb_nativethread_lock_t *ossl_locks;
00471 
00472 static void
00473 ossl_lock_unlock(int mode, rb_nativethread_lock_t *lock)
00474 {
00475     if (mode & CRYPTO_LOCK) {
00476         rb_nativethread_lock_lock(lock);
00477     } else {
00478         rb_nativethread_lock_unlock(lock);
00479     }
00480 }
00481 
00482 static void
00483 ossl_lock_callback(int mode, int type, const char *file, int line)
00484 {
00485     ossl_lock_unlock(mode, &ossl_locks[type]);
00486 }
00487 
00488 struct CRYPTO_dynlock_value {
00489     rb_nativethread_lock_t lock;
00490 };
00491 
00492 static struct CRYPTO_dynlock_value *
00493 ossl_dyn_create_callback(const char *file, int line)
00494 {
00495     struct CRYPTO_dynlock_value *dynlock = (struct CRYPTO_dynlock_value *)OPENSSL_malloc((int)sizeof(struct CRYPTO_dynlock_value));
00496     rb_nativethread_lock_initialize(&dynlock->lock);
00497     return dynlock;
00498 }
00499 
00500 static void
00501 ossl_dyn_lock_callback(int mode, struct CRYPTO_dynlock_value *l, const char *file, int line)
00502 {
00503     ossl_lock_unlock(mode, &l->lock);
00504 }
00505 
00506 static void
00507 ossl_dyn_destroy_callback(struct CRYPTO_dynlock_value *l, const char *file, int line)
00508 {
00509     rb_nativethread_lock_destroy(&l->lock);
00510     OPENSSL_free(l);
00511 }
00512 
00513 #ifdef HAVE_CRYPTO_THREADID_PTR
00514 static void ossl_threadid_func(CRYPTO_THREADID *id)
00515 {
00516     /* register native thread id */
00517     CRYPTO_THREADID_set_pointer(id, (void *)rb_nativethread_self());
00518 }
00519 #else
00520 static unsigned long ossl_thread_id(void)
00521 {
00522     /* before OpenSSL 1.0, this is 'unsigned long' */
00523     return (unsigned long)rb_nativethread_self();
00524 }
00525 #endif
00526 
00527 static void Init_ossl_locks(void)
00528 {
00529     int i;
00530     int num_locks = CRYPTO_num_locks();
00531 
00532     if ((unsigned)num_locks >= INT_MAX / (int)sizeof(VALUE)) {
00533         rb_raise(rb_eRuntimeError, "CRYPTO_num_locks() is too big: %d", num_locks);
00534     }
00535     ossl_locks = (rb_nativethread_lock_t *) OPENSSL_malloc(num_locks * (int)sizeof(rb_nativethread_lock_t));
00536     if (!ossl_locks) {
00537         rb_raise(rb_eNoMemError, "CRYPTO_num_locks() is too big: %d", num_locks);
00538     }
00539     for (i = 0; i < num_locks; i++) {
00540         rb_nativethread_lock_initialize(&ossl_locks[i]);
00541     }
00542 
00543 #ifdef HAVE_CRYPTO_THREADID_PTR
00544     CRYPTO_THREADID_set_callback(ossl_threadid_func);
00545 #else
00546     CRYPTO_set_id_callback(ossl_thread_id);
00547 #endif
00548     CRYPTO_set_locking_callback(ossl_lock_callback);
00549     CRYPTO_set_dynlock_create_callback(ossl_dyn_create_callback);
00550     CRYPTO_set_dynlock_lock_callback(ossl_dyn_lock_callback);
00551     CRYPTO_set_dynlock_destroy_callback(ossl_dyn_destroy_callback);
00552 }
00553 
00554 /*
00555  * OpenSSL provides SSL, TLS and general purpose cryptography.  It wraps the
00556  * OpenSSL[http://www.openssl.org/] library.
00557  *
00558  * = Examples
00559  *
00560  * All examples assume you have loaded OpenSSL with:
00561  *
00562  *   require 'openssl'
00563  *
00564  * These examples build atop each other.  For example the key created in the
00565  * next is used in throughout these examples.
00566  *
00567  * == Keys
00568  *
00569  * === Creating a Key
00570  *
00571  * This example creates a 2048 bit RSA keypair and writes it to the current
00572  * directory.
00573  *
00574  *   key = OpenSSL::PKey::RSA.new 2048
00575  *
00576  *   open 'private_key.pem', 'w' do |io| io.write key.to_pem end
00577  *   open 'public_key.pem', 'w' do |io| io.write key.public_key.to_pem end
00578  *
00579  * === Exporting a Key
00580  *
00581  * Keys saved to disk without encryption are not secure as anyone who gets
00582  * ahold of the key may use it unless it is encrypted.  In order to securely
00583  * export a key you may export it with a pass phrase.
00584  *
00585  *   cipher = OpenSSL::Cipher.new 'AES-128-CBC'
00586  *   pass_phrase = 'my secure pass phrase goes here'
00587  *
00588  *   key_secure = key.export cipher, pass_phrase
00589  *
00590  *   open 'private.secure.pem', 'w' do |io|
00591  *     io.write key_secure
00592  *   end
00593  *
00594  * OpenSSL::Cipher.ciphers returns a list of available ciphers.
00595  *
00596  * === Loading a Key
00597  *
00598  * A key can also be loaded from a file.
00599  *
00600  *   key2 = OpenSSL::PKey::RSA.new File.read 'private_key.pem'
00601  *   key2.public? # => true
00602  *
00603  * or
00604  *
00605  *   key3 = OpenSSL::PKey::RSA.new File.read 'public_key.pem'
00606  *   key3.private? # => false
00607  *
00608  * === Loading an Encrypted Key
00609  *
00610  * OpenSSL will prompt you for your pass phrase when loading an encrypted key.
00611  * If you will not be able to type in the pass phrase you may provide it when
00612  * loading the key:
00613  *
00614  *   key4_pem = File.read 'private.secure.pem'
00615  *   key4 = OpenSSL::PKey::RSA.new key4_pem, pass_phrase
00616  *
00617  * == RSA Encryption
00618  *
00619  * RSA provides encryption and decryption using the public and private keys.
00620  * You can use a variety of padding methods depending upon the intended use of
00621  * encrypted data.
00622  *
00623  * === Encryption & Decryption
00624  *
00625  * Asymmetric public/private key encryption is slow and victim to attack in
00626  * cases where it is used without padding or directly to encrypt larger chunks
00627  * of data. Typical use cases for RSA encryption involve "wrapping" a symmetric
00628  * key with the public key of the recipient who would "unwrap" that symmetric
00629  * key again using their private key.
00630  * The following illustrates a simplified example of such a key transport
00631  * scheme. It shouldn't be used in practice, though, standardized protocols
00632  * should always be preferred.
00633  *
00634  *   wrapped_key = key.public_encrypt key
00635  *
00636  * A symmetric key encrypted with the public key can only be decrypted with
00637  * the corresponding private key of the recipient.
00638  *
00639  *   original_key = key.private_decrypt wrapped_key
00640  *
00641  * By default PKCS#1 padding will be used, but it is also possible to use
00642  * other forms of padding, see PKey::RSA for further details.
00643  *
00644  * === Signatures
00645  *
00646  * Using "private_encrypt" to encrypt some data with the private key is
00647  * equivalent to applying a digital signature to the data. A verifying
00648  * party may validate the signature by comparing the result of decrypting
00649  * the signature with "public_decrypt" to the original data. However,
00650  * OpenSSL::PKey already has methods "sign" and "verify" that handle
00651  * digital signatures in a standardized way - "private_encrypt" and
00652  * "public_decrypt" shouldn't be used in practice.
00653  *
00654  * To sign a document, a cryptographically secure hash of the document is
00655  * computed first, which is then signed using the private key.
00656  *
00657  *   digest = OpenSSL::Digest::SHA256.new
00658  *   signature = key.sign digest, document
00659  *
00660  * To validate the signature, again a hash of the document is computed and
00661  * the signature is decrypted using the public key. The result is then
00662  * compared to the hash just computed, if they are equal the signature was
00663  * valid.
00664  *
00665  *   digest = OpenSSL::Digest::SHA256.new
00666  *   if key.verify digest, signature, document
00667  *     puts 'Valid'
00668  *   else
00669  *     puts 'Invalid'
00670  *   end
00671  *
00672  * == PBKDF2 Password-based Encryption
00673  *
00674  * If supported by the underlying OpenSSL version used, Password-based
00675  * Encryption should use the features of PKCS5. If not supported or if
00676  * required by legacy applications, the older, less secure methods specified
00677  * in RFC 2898 are also supported (see below).
00678  *
00679  * PKCS5 supports PBKDF2 as it was specified in PKCS#5
00680  * v2.0[http://www.rsa.com/rsalabs/node.asp?id=2127]. It still uses a
00681  * password, a salt, and additionally a number of iterations that will
00682  * slow the key derivation process down. The slower this is, the more work
00683  * it requires being able to brute-force the resulting key.
00684  *
00685  * === Encryption
00686  *
00687  * The strategy is to first instantiate a Cipher for encryption, and
00688  * then to generate a random IV plus a key derived from the password
00689  * using PBKDF2. PKCS #5 v2.0 recommends at least 8 bytes for the salt,
00690  * the number of iterations largely depends on the hardware being used.
00691  *
00692  *   cipher = OpenSSL::Cipher.new 'AES-128-CBC'
00693  *   cipher.encrypt
00694  *   iv = cipher.random_iv
00695  *
00696  *   pwd = 'some hopefully not to easily guessable password'
00697  *   salt = OpenSSL::Random.random_bytes 16
00698  *   iter = 20000
00699  *   key_len = cipher.key_len
00700  *   digest = OpenSSL::Digest::SHA256.new
00701  *
00702  *   key = OpenSSL::PKCS5.pbkdf2_hmac(pwd, salt, iter, key_len, digest)
00703  *   cipher.key = key
00704  *
00705  *   Now encrypt the data:
00706  *
00707  *   encrypted = cipher.update document
00708  *   encrypted << cipher.final
00709  *
00710  * === Decryption
00711  *
00712  * Use the same steps as before to derive the symmetric AES key, this time
00713  * setting the Cipher up for decryption.
00714  *
00715  *   cipher = OpenSSL::Cipher.new 'AES-128-CBC'
00716  *   cipher.decrypt
00717  *   cipher.iv = iv # the one generated with #random_iv
00718  *
00719  *   pwd = 'some hopefully not to easily guessable password'
00720  *   salt = ... # the one generated above
00721  *   iter = 20000
00722  *   key_len = cipher.key_len
00723  *   digest = OpenSSL::Digest::SHA256.new
00724  *
00725  *   key = OpenSSL::PKCS5.pbkdf2_hmac(pwd, salt, iter, key_len, digest)
00726  *   cipher.key = key
00727  *
00728  *   Now decrypt the data:
00729  *
00730  *   decrypted = cipher.update encrypted
00731  *   decrypted << cipher.final
00732  *
00733  * == PKCS #5 Password-based Encryption
00734  *
00735  * PKCS #5 is a password-based encryption standard documented at
00736  * RFC2898[http://www.ietf.org/rfc/rfc2898.txt].  It allows a short password or
00737  * passphrase to be used to create a secure encryption key. If possible, PBKDF2
00738  * as described above should be used if the circumstances allow it.
00739  *
00740  * PKCS #5 uses a Cipher, a pass phrase and a salt to generate an encryption
00741  * key.
00742  *
00743  *   pass_phrase = 'my secure pass phrase goes here'
00744  *   salt = '8 octets'
00745  *
00746  * === Encryption
00747  *
00748  * First set up the cipher for encryption
00749  *
00750  *   encrypter = OpenSSL::Cipher.new 'AES-128-CBC'
00751  *   encrypter.encrypt
00752  *   encrypter.pkcs5_keyivgen pass_phrase, salt
00753  *
00754  * Then pass the data you want to encrypt through
00755  *
00756  *   encrypted = encrypter.update 'top secret document'
00757  *   encrypted << encrypter.final
00758  *
00759  * === Decryption
00760  *
00761  * Use a new Cipher instance set up for decryption
00762  *
00763  *   decrypter = OpenSSL::Cipher.new 'AES-128-CBC'
00764  *   decrypter.decrypt
00765  *   decrypter.pkcs5_keyivgen pass_phrase, salt
00766  *
00767  * Then pass the data you want to decrypt through
00768  *
00769  *   plain = decrypter.update encrypted
00770  *   plain << decrypter.final
00771  *
00772  * == X509 Certificates
00773  *
00774  * === Creating a Certificate
00775  *
00776  * This example creates a self-signed certificate using an RSA key and a SHA1
00777  * signature.
00778  *
00779  *   name = OpenSSL::X509::Name.parse 'CN=nobody/DC=example'
00780  *
00781  *   cert = OpenSSL::X509::Certificate.new
00782  *   cert.version = 2
00783  *   cert.serial = 0
00784  *   cert.not_before = Time.now
00785  *   cert.not_after = Time.now + 3600
00786  *
00787  *   cert.public_key = key.public_key
00788  *   cert.subject = name
00789  *
00790  * === Certificate Extensions
00791  *
00792  * You can add extensions to the certificate with
00793  * OpenSSL::SSL::ExtensionFactory to indicate the purpose of the certificate.
00794  *
00795  *   extension_factory = OpenSSL::X509::ExtensionFactory.new nil, cert
00796  *
00797  *   cert.add_extension \
00798  *     extension_factory.create_extension('basicConstraints', 'CA:FALSE', true)
00799  *
00800  *   cert.add_extension \
00801  *     extension_factory.create_extension(
00802  *       'keyUsage', 'keyEncipherment,dataEncipherment,digitalSignature')
00803  *
00804  *   cert.add_extension \
00805  *     extension_factory.create_extension('subjectKeyIdentifier', 'hash')
00806  *
00807  * The list of supported extensions (and in some cases their possible values)
00808  * can be derived from the "objects.h" file in the OpenSSL source code.
00809  *
00810  * === Signing a Certificate
00811  *
00812  * To sign a certificate set the issuer and use OpenSSL::X509::Certificate#sign
00813  * with a digest algorithm.  This creates a self-signed cert because we're using
00814  * the same name and key to sign the certificate as was used to create the
00815  * certificate.
00816  *
00817  *   cert.issuer = name
00818  *   cert.sign key, OpenSSL::Digest::SHA1.new
00819  *
00820  *   open 'certificate.pem', 'w' do |io| io.write cert.to_pem end
00821  *
00822  * === Loading a Certificate
00823  *
00824  * Like a key, a cert can also be loaded from a file.
00825  *
00826  *   cert2 = OpenSSL::X509::Certificate.new File.read 'certificate.pem'
00827  *
00828  * === Verifying a Certificate
00829  *
00830  * Certificate#verify will return true when a certificate was signed with the
00831  * given public key.
00832  *
00833  *   raise 'certificate can not be verified' unless cert2.verify key
00834  *
00835  * == Certificate Authority
00836  *
00837  * A certificate authority (CA) is a trusted third party that allows you to
00838  * verify the ownership of unknown certificates.  The CA issues key signatures
00839  * that indicate it trusts the user of that key.  A user encountering the key
00840  * can verify the signature by using the CA's public key.
00841  *
00842  * === CA Key
00843  *
00844  * CA keys are valuable, so we encrypt and save it to disk and make sure it is
00845  * not readable by other users.
00846  *
00847  *   ca_key = OpenSSL::PKey::RSA.new 2048
00848  *
00849  *   cipher = OpenSSL::Cipher::Cipher.new 'AES-128-CBC'
00850  *
00851  *   open 'ca_key.pem', 'w', 0400 do |io|
00852  *     io.write ca_key.export(cipher, pass_phrase)
00853  *   end
00854  *
00855  * === CA Certificate
00856  *
00857  * A CA certificate is created the same way we created a certificate above, but
00858  * with different extensions.
00859  *
00860  *   ca_name = OpenSSL::X509::Name.parse 'CN=ca/DC=example'
00861  *
00862  *   ca_cert = OpenSSL::X509::Certificate.new
00863  *   ca_cert.serial = 0
00864  *   ca_cert.version = 2
00865  *   ca_cert.not_before = Time.now
00866  *   ca_cert.not_after = Time.now + 86400
00867  *
00868  *   ca_cert.public_key = ca_key.public_key
00869  *   ca_cert.subject = ca_name
00870  *   ca_cert.issuer = ca_name
00871  *
00872  *   extension_factory = OpenSSL::X509::ExtensionFactory.new
00873  *   extension_factory.subject_certificate = ca_cert
00874  *   extension_factory.issuer_certificate = ca_cert
00875  *
00876  *   ca_cert.add_extension \
00877  *     extension_factory.create_extension('subjectKeyIdentifier', 'hash')
00878  *
00879  * This extension indicates the CA's key may be used as a CA.
00880  *
00881  *   ca_cert.add_extension \
00882  *     extension_factory.create_extension('basicConstraints', 'CA:TRUE', true)
00883  *
00884  * This extension indicates the CA's key may be used to verify signatures on
00885  * both certificates and certificate revocations.
00886  *
00887  *   ca_cert.add_extension \
00888  *     extension_factory.create_extension(
00889  *       'keyUsage', 'cRLSign,keyCertSign', true)
00890  *
00891  * Root CA certificates are self-signed.
00892  *
00893  *   ca_cert.sign ca_key, OpenSSL::Digest::SHA1.new
00894  *
00895  * The CA certificate is saved to disk so it may be distributed to all the
00896  * users of the keys this CA will sign.
00897  *
00898  *   open 'ca_cert.pem', 'w' do |io|
00899  *     io.write ca_cert.to_pem
00900  *   end
00901  *
00902  * === Certificate Signing Request
00903  *
00904  * The CA signs keys through a Certificate Signing Request (CSR).  The CSR
00905  * contains the information necessary to identify the key.
00906  *
00907  *   csr = OpenSSL::X509::Request.new
00908  *   csr.version = 0
00909  *   csr.subject = name
00910  *   csr.public_key = key.public_key
00911  *   csr.sign key, OpenSSL::Digest::SHA1.new
00912  *
00913  * A CSR is saved to disk and sent to the CA for signing.
00914  *
00915  *   open 'csr.pem', 'w' do |io|
00916  *     io.write csr.to_pem
00917  *   end
00918  *
00919  * === Creating a Certificate from a CSR
00920  *
00921  * Upon receiving a CSR the CA will verify it before signing it.  A minimal
00922  * verification would be to check the CSR's signature.
00923  *
00924  *   csr = OpenSSL::X509::Request.new File.read 'csr.pem'
00925  *
00926  *   raise 'CSR can not be verified' unless csr.verify csr.public_key
00927  *
00928  * After verification a certificate is created, marked for various usages,
00929  * signed with the CA key and returned to the requester.
00930  *
00931  *   csr_cert = OpenSSL::X509::Certificate.new
00932  *   csr_cert.serial = 0
00933  *   csr_cert.version = 2
00934  *   csr_cert.not_before = Time.now
00935  *   csr_cert.not_after = Time.now + 600
00936  *
00937  *   csr_cert.subject = csr.subject
00938  *   csr_cert.public_key = csr.public_key
00939  *   csr_cert.issuer = ca_cert.subject
00940  *
00941  *   extension_factory = OpenSSL::X509::ExtensionFactory.new
00942  *   extension_factory.subject_certificate = csr_cert
00943  *   extension_factory.issuer_certificate = ca_cert
00944  *
00945  *   csr_cert.add_extension \
00946  *     extension_factory.create_extension('basicConstraints', 'CA:FALSE')
00947  *
00948  *   csr_cert.add_extension \
00949  *     extension_factory.create_extension(
00950  *       'keyUsage', 'keyEncipherment,dataEncipherment,digitalSignature')
00951  *
00952  *   csr_cert.add_extension \
00953  *     extension_factory.create_extension('subjectKeyIdentifier', 'hash')
00954  *
00955  *   csr_cert.sign ca_key, OpenSSL::Digest::SHA1.new
00956  *
00957  *   open 'csr_cert.pem', 'w' do |io|
00958  *     io.write csr_cert.to_pem
00959  *   end
00960  *
00961  * == SSL and TLS Connections
00962  *
00963  * Using our created key and certificate we can create an SSL or TLS connection.
00964  * An SSLContext is used to set up an SSL session.
00965  *
00966  *   context = OpenSSL::SSL::SSLContext.new
00967  *
00968  * === SSL Server
00969  *
00970  * An SSL server requires the certificate and private key to communicate
00971  * securely with its clients:
00972  *
00973  *   context.cert = cert
00974  *   context.key = key
00975  *
00976  * Then create an SSLServer with a TCP server socket and the context.  Use the
00977  * SSLServer like an ordinary TCP server.
00978  *
00979  *   require 'socket'
00980  *
00981  *   tcp_server = TCPServer.new 5000
00982  *   ssl_server = OpenSSL::SSL::SSLServer.new tcp_server, context
00983  *
00984  *   loop do
00985  *     ssl_connection = ssl_server.accept
00986  *
00987  *     data = connection.gets
00988  *
00989  *     response = "I got #{data.dump}"
00990  *     puts response
00991  *
00992  *     connection.puts "I got #{data.dump}"
00993  *     connection.close
00994  *   end
00995  *
00996  * === SSL client
00997  *
00998  * An SSL client is created with a TCP socket and the context.
00999  * SSLSocket#connect must be called to initiate the SSL handshake and start
01000  * encryption.  A key and certificate are not required for the client socket.
01001  *
01002  *   require 'socket'
01003  *
01004  *   tcp_client = TCPSocket.new 'localhost', 5000
01005  *   ssl_client = OpenSSL::SSL::SSLSocket.new client_socket, context
01006  *   ssl_client.connect
01007  *
01008  *   ssl_client.puts "hello server!"
01009  *   puts ssl_client.gets
01010  *
01011  * === Peer Verification
01012  *
01013  * An unverified SSL connection does not provide much security.  For enhanced
01014  * security the client or server can verify the certificate of its peer.
01015  *
01016  * The client can be modified to verify the server's certificate against the
01017  * certificate authority's certificate:
01018  *
01019  *   context.ca_file = 'ca_cert.pem'
01020  *   context.verify_mode = OpenSSL::SSL::VERIFY_PEER
01021  *
01022  *   require 'socket'
01023  *
01024  *   tcp_client = TCPSocket.new 'localhost', 5000
01025  *   ssl_client = OpenSSL::SSL::SSLSocket.new client_socket, context
01026  *   ssl_client.connect
01027  *
01028  *   ssl_client.puts "hello server!"
01029  *   puts ssl_client.gets
01030  *
01031  * If the server certificate is invalid or <tt>context.ca_file</tt> is not set
01032  * when verifying peers an OpenSSL::SSL::SSLError will be raised.
01033  *
01034  */
01035 void
01036 Init_openssl()
01037 {
01038     /*
01039      * Init timezone info
01040      */
01041 #if 0
01042     tzset();
01043 #endif
01044 
01045     /*
01046      * Init all digests, ciphers
01047      */
01048     /* CRYPTO_malloc_init(); */
01049     /* ENGINE_load_builtin_engines(); */
01050     OpenSSL_add_ssl_algorithms();
01051     OpenSSL_add_all_algorithms();
01052     ERR_load_crypto_strings();
01053     SSL_load_error_strings();
01054 
01055     /*
01056      * FIXME:
01057      * On unload do:
01058      */
01059 #if 0
01060     CONF_modules_unload(1);
01061     destroy_ui_method();
01062     EVP_cleanup();
01063     ENGINE_cleanup();
01064     CRYPTO_cleanup_all_ex_data();
01065     ERR_remove_state(0);
01066     ERR_free_strings();
01067 #endif
01068 
01069     /*
01070      * Init main module
01071      */
01072     mOSSL = rb_define_module("OpenSSL");
01073     rb_global_variable(&mOSSL);
01074 
01075     /*
01076      * OpenSSL ruby extension version
01077      */
01078     rb_define_const(mOSSL, "VERSION", rb_str_new2(OSSL_VERSION));
01079 
01080     /*
01081      * Version of OpenSSL the ruby OpenSSL extension was built with
01082      */
01083     rb_define_const(mOSSL, "OPENSSL_VERSION", rb_str_new2(OPENSSL_VERSION_TEXT));
01084 
01085     /*
01086      * Version of OpenSSL the ruby OpenSSL extension is running with
01087      */
01088     rb_define_const(mOSSL, "OPENSSL_LIBRARY_VERSION", rb_str_new2(SSLeay_version(SSLEAY_VERSION)));
01089 
01090     /*
01091      * Version number of OpenSSL the ruby OpenSSL extension was built with
01092      * (base 16)
01093      */
01094     rb_define_const(mOSSL, "OPENSSL_VERSION_NUMBER", INT2NUM(OPENSSL_VERSION_NUMBER));
01095 
01096     /*
01097      * Boolean indicating whether OpenSSL is FIPS-enabled or not
01098      */
01099 #ifdef HAVE_OPENSSL_FIPS
01100     rb_define_const(mOSSL, "OPENSSL_FIPS", Qtrue);
01101 #else
01102     rb_define_const(mOSSL, "OPENSSL_FIPS", Qfalse);
01103 #endif
01104     rb_define_module_function(mOSSL, "fips_mode=", ossl_fips_mode_set, 1);
01105 
01106     /*
01107      * Generic error,
01108      * common for all classes under OpenSSL module
01109      */
01110     eOSSLError = rb_define_class_under(mOSSL,"OpenSSLError",rb_eStandardError);
01111     rb_global_variable(&eOSSLError);
01112 
01113     /*
01114      * Verify callback Proc index for ext-data
01115      */
01116     if ((ossl_verify_cb_idx = X509_STORE_CTX_get_ex_new_index(0, (void *)"ossl_verify_cb_idx", 0, 0, 0)) < 0)
01117         ossl_raise(eOSSLError, "X509_STORE_CTX_get_ex_new_index");
01118 
01119     /*
01120      * Init debug core
01121      */
01122     dOSSL = Qfalse;
01123     rb_global_variable(&dOSSL);
01124 
01125     rb_define_module_function(mOSSL, "debug", ossl_debug_get, 0);
01126     rb_define_module_function(mOSSL, "debug=", ossl_debug_set, 1);
01127     rb_define_module_function(mOSSL, "errors", ossl_get_errors, 0);
01128 
01129     /*
01130      * Get ID of to_der
01131      */
01132     ossl_s_to_der = rb_intern("to_der");
01133 
01134     Init_ossl_locks();
01135 
01136     /*
01137      * Init components
01138      */
01139     Init_ossl_bn();
01140     Init_ossl_cipher();
01141     Init_ossl_config();
01142     Init_ossl_digest();
01143     Init_ossl_hmac();
01144     Init_ossl_ns_spki();
01145     Init_ossl_pkcs12();
01146     Init_ossl_pkcs7();
01147     Init_ossl_pkcs5();
01148     Init_ossl_pkey();
01149     Init_ossl_rand();
01150     Init_ossl_ssl();
01151     Init_ossl_x509();
01152     Init_ossl_ocsp();
01153     Init_ossl_engine();
01154     Init_ossl_asn1();
01155 }
01156 
01157 #if defined(OSSL_DEBUG)
01158 /*
01159  * Check if all symbols are OK with 'make LDSHARED=gcc all'
01160  */
01161 int
01162 main(int argc, char *argv[])
01163 {
01164     return 0;
01165 }
01166 #endif /* OSSL_DEBUG */
01167 
01168 

Generated on 19 Jul 2016 for Ruby by  doxygen 1.4.7