Ruby  2.0.0p451(2014-02-24revision45167)
ext/openssl/ossl.c
Go to the documentation of this file.
00001 /*
00002  * $Id: ossl.c 44659 2014-01-19 16:28:53Z 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             str = rb_str_new_cstr(msg);
00315         }
00316         else {
00317             rb_str_cat2(rb_str_cat2(str, ": "), msg);
00318         }
00319     }
00320     if (dOSSL == Qtrue){ /* show all errors on the stack */
00321         while ((e = ERR_get_error()) != 0){
00322             rb_warn("error on stack: %s", ERR_error_string(e, NULL));
00323         }
00324     }
00325     ERR_clear_error();
00326 
00327     if (NIL_P(str)) str = rb_str_new(0, 0);
00328     return rb_exc_new3(exc, str);
00329 }
00330 
00331 void
00332 ossl_raise(VALUE exc, const char *fmt, ...)
00333 {
00334     va_list args;
00335     VALUE err;
00336     va_start(args, fmt);
00337     err = ossl_make_error(exc, fmt, args);
00338     va_end(args);
00339     rb_exc_raise(err);
00340 }
00341 
00342 VALUE
00343 ossl_exc_new(VALUE exc, const char *fmt, ...)
00344 {
00345     va_list args;
00346     VALUE err;
00347     va_start(args, fmt);
00348     err = ossl_make_error(exc, fmt, args);
00349     va_end(args);
00350     return err;
00351 }
00352 
00353 /*
00354  * call-seq:
00355  *   OpenSSL.errors -> [String...]
00356  *
00357  * See any remaining errors held in queue.
00358  *
00359  * Any errors you see here are probably due to a bug in ruby's OpenSSL implementation.
00360  */
00361 VALUE
00362 ossl_get_errors()
00363 {
00364     VALUE ary;
00365     long e;
00366 
00367     ary = rb_ary_new();
00368     while ((e = ERR_get_error()) != 0){
00369         rb_ary_push(ary, rb_str_new2(ERR_error_string(e, NULL)));
00370     }
00371 
00372     return ary;
00373 }
00374 
00375 /*
00376  * Debug
00377  */
00378 VALUE dOSSL;
00379 
00380 #if !defined(HAVE_VA_ARGS_MACRO)
00381 void
00382 ossl_debug(const char *fmt, ...)
00383 {
00384     va_list args;
00385 
00386     if (dOSSL == Qtrue) {
00387         fprintf(stderr, "OSSL_DEBUG: ");
00388         va_start(args, fmt);
00389         vfprintf(stderr, fmt, args);
00390         va_end(args);
00391         fprintf(stderr, " [CONTEXT N/A]\n");
00392     }
00393 }
00394 #endif
00395 
00396 /*
00397  * call-seq:
00398  *   OpenSSL.debug -> true | false
00399  */
00400 static VALUE
00401 ossl_debug_get(VALUE self)
00402 {
00403     return dOSSL;
00404 }
00405 
00406 /*
00407  * call-seq:
00408  *   OpenSSL.debug = boolean -> boolean
00409  *
00410  * Turns on or off CRYPTO_MEM_CHECK.
00411  * Also shows some debugging message on stderr.
00412  */
00413 static VALUE
00414 ossl_debug_set(VALUE self, VALUE val)
00415 {
00416     VALUE old = dOSSL;
00417     dOSSL = val;
00418 
00419     if (old != dOSSL) {
00420         if (dOSSL == Qtrue) {
00421             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
00422             fprintf(stderr, "OSSL_DEBUG: IS NOW ON!\n");
00423         } else if (old == Qtrue) {
00424             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_OFF);
00425             fprintf(stderr, "OSSL_DEBUG: IS NOW OFF!\n");
00426         }
00427     }
00428     return val;
00429 }
00430 
00431 /*
00432  * call-seq:
00433  *   OpenSSL.fips_mode = boolean -> boolean
00434  *
00435  * Turns FIPS mode on or off. Turning on FIPS mode will obviously only have an
00436  * effect for FIPS-capable installations of the OpenSSL library. Trying to do
00437  * so otherwise will result in an error.
00438  *
00439  * === Examples
00440  *
00441  * OpenSSL.fips_mode = true   # turn FIPS mode on
00442  * OpenSSL.fips_mode = false  # and off again
00443  */
00444 static VALUE
00445 ossl_fips_mode_set(VALUE self, VALUE enabled)
00446 {
00447 
00448 #ifdef HAVE_OPENSSL_FIPS
00449     if (RTEST(enabled)) {
00450         int mode = FIPS_mode();
00451         if(!mode && !FIPS_mode_set(1)) /* turning on twice leads to an error */
00452             ossl_raise(eOSSLError, "Turning on FIPS mode failed");
00453     } else {
00454         if(!FIPS_mode_set(0)) /* turning off twice is OK */
00455             ossl_raise(eOSSLError, "Turning off FIPS mode failed");
00456     }
00457     return enabled;
00458 #else
00459     if (RTEST(enabled))
00460         ossl_raise(eOSSLError, "This version of OpenSSL does not support FIPS mode");
00461     return enabled;
00462 #endif
00463 }
00464 
00465 /*
00466  * OpenSSL provides SSL, TLS and general purpose cryptography.  It wraps the
00467  * OpenSSL[http://www.openssl.org/] library.
00468  *
00469  * = Examples
00470  *
00471  * All examples assume you have loaded OpenSSL with:
00472  *
00473  *   require 'openssl'
00474  *
00475  * These examples build atop each other.  For example the key created in the
00476  * next is used in throughout these examples.
00477  *
00478  * == Keys
00479  *
00480  * === Creating a Key
00481  *
00482  * This example creates a 2048 bit RSA keypair and writes it to the current
00483  * directory.
00484  *
00485  *   key = OpenSSL::PKey::RSA.new 2048
00486  *
00487  *   open 'private_key.pem', 'w' do |io| io.write key.to_pem end
00488  *   open 'public_key.pem', 'w' do |io| io.write key.public_key.to_pem end
00489  *
00490  * === Exporting a Key
00491  *
00492  * Keys saved to disk without encryption are not secure as anyone who gets
00493  * ahold of the key may use it unless it is encrypted.  In order to securely
00494  * export a key you may export it with a pass phrase.
00495  *
00496  *   cipher = OpenSSL::Cipher.new 'AES-128-CBC'
00497  *   pass_phrase = 'my secure pass phrase goes here'
00498  *
00499  *   key_secure = key.export cipher, pass_phrase
00500  *
00501  *   open 'private.secure.pem', 'w' do |io|
00502  *     io.write key_secure
00503  *   end
00504  *
00505  * OpenSSL::Cipher.ciphers returns a list of available ciphers.
00506  *
00507  * === Loading a Key
00508  *
00509  * A key can also be loaded from a file.
00510  *
00511  *   key2 = OpenSSL::PKey::RSA.new File.read 'private_key.pem'
00512  *   key2.public? # => true
00513  *
00514  * or
00515  *
00516  *   key3 = OpenSSL::PKey::RSA.new File.read 'public_key.pem'
00517  *   key3.private? # => false
00518  *
00519  * === Loading an Encrypted Key
00520  *
00521  * OpenSSL will prompt you for your pass phrase when loading an encrypted key.
00522  * If you will not be able to type in the pass phrase you may provide it when
00523  * loading the key:
00524  *
00525  *   key4_pem = File.read 'private.secure.pem'
00526  *   key4 = OpenSSL::PKey::RSA.new key4_pem, pass_phrase
00527  *
00528  * == RSA Encryption
00529  *
00530  * RSA provides encryption and decryption using the public and private keys.
00531  * You can use a variety of padding methods depending upon the intended use of
00532  * encrypted data.
00533  *
00534  * === Encryption & Decryption
00535  *
00536  * Asymmetric public/private key encryption is slow and victim to attack in
00537  * cases where it is used without padding or directly to encrypt larger chunks
00538  * of data. Typical use cases for RSA encryption involve "wrapping" a symmetric
00539  * key with the public key of the recipient who would "unwrap" that symmetric
00540  * key again using their private key.
00541  * The following illustrates a simplified example of such a key transport
00542  * scheme. It shouldn't be used in practice, though, standardized protocols
00543  * should always be preferred.
00544  *
00545  *   wrapped_key = key.public_encrypt key
00546  *
00547  * A symmetric key encrypted with the public key can only be decrypted with
00548  * the corresponding private key of the recipient.
00549  *
00550  *   original_key = key.private_decrypt wrapped_key
00551  *
00552  * By default PKCS#1 padding will be used, but it is also possible to use
00553  * other forms of padding, see PKey::RSA for further details.
00554  *
00555  * === Signatures
00556  *
00557  * Using "private_encrypt" to encrypt some data with the private key is
00558  * equivalent to applying a digital signature to the data. A verifying
00559  * party may validate the signature by comparing the result of decrypting
00560  * the signature with "public_decrypt" to the original data. However,
00561  * OpenSSL::PKey already has methods "sign" and "verify" that handle
00562  * digital signatures in a standardized way - "private_encrypt" and
00563  * "public_decrypt" shouldn't be used in practice.
00564  *
00565  * To sign a document, a cryptographically secure hash of the document is
00566  * computed first, which is then signed using the private key.
00567  *
00568  *   digest = OpenSSL::Digest::SHA256.new
00569  *   signature = key.sign digest, document
00570  *
00571  * To validate the signature, again a hash of the document is computed and
00572  * the signature is decrypted using the public key. The result is then
00573  * compared to the hash just computed, if they are equal the signature was
00574  * valid.
00575  *
00576  *   digest = OpenSSL::Digest::SHA256.new
00577  *   if key.verify digest, signature, document
00578  *     puts 'Valid'
00579  *   else
00580  *     puts 'Invalid'
00581  *   end
00582  *
00583  * == PBKDF2 Password-based Encryption
00584  *
00585  * If supported by the underlying OpenSSL version used, Password-based
00586  * Encryption should use the features of PKCS5. If not supported or if
00587  * required by legacy applications, the older, less secure methods specified
00588  * in RFC 2898 are also supported (see below).
00589  *
00590  * PKCS5 supports PBKDF2 as it was specified in PKCS#5
00591  * v2.0[http://www.rsa.com/rsalabs/node.asp?id=2127]. It still uses a
00592  * password, a salt, and additionally a number of iterations that will
00593  * slow the key derivation process down. The slower this is, the more work
00594  * it requires being able to brute-force the resulting key.
00595  *
00596  * === Encryption
00597  *
00598  * The strategy is to first instantiate a Cipher for encryption, and
00599  * then to generate a random IV plus a key derived from the password
00600  * using PBKDF2. PKCS #5 v2.0 recommends at least 8 bytes for the salt,
00601  * the number of iterations largely depends on the hardware being used.
00602  *
00603  *   cipher = OpenSSL::Cipher.new 'AES-128-CBC'
00604  *   cipher.encrypt
00605  *   iv = cipher.random_iv
00606  *
00607  *   pwd = 'some hopefully not to easily guessable password'
00608  *   salt = OpenSSL::Random.random_bytes 16
00609  *   iter = 20000
00610  *   key_len = cipher.key_len
00611  *   digest = OpenSSL::Digest::SHA256.new
00612  *
00613  *   key = OpenSSL::PKCS5.pbkdf2_hmac(pwd, salt, iter, key_len, digest)
00614  *   cipher.key = key
00615  *
00616  *   Now encrypt the data:
00617  *
00618  *   encrypted = cipher.update document
00619  *   encrypted << cipher.final
00620  *
00621  * === Decryption
00622  *
00623  * Use the same steps as before to derive the symmetric AES key, this time
00624  * setting the Cipher up for decryption.
00625  *
00626  *   cipher = OpenSSL::Cipher.new 'AES-128-CBC'
00627  *   cipher.decrypt
00628  *   cipher.iv = iv # the one generated with #random_iv
00629  *
00630  *   pwd = 'some hopefully not to easily guessable password'
00631  *   salt = ... # the one generated above
00632  *   iter = 20000
00633  *   key_len = cipher.key_len
00634  *   digest = OpenSSL::Digest::SHA256.new
00635  *
00636  *   key = OpenSSL::PKCS5.pbkdf2_hmac(pwd, salt, iter, key_len, digest)
00637  *   cipher.key = key
00638  *
00639  *   Now decrypt the data:
00640  *
00641  *   decrypted = cipher.update encrypted
00642  *   decrypted << cipher.final
00643  *
00644  * == PKCS #5 Password-based Encryption
00645  *
00646  * PKCS #5 is a password-based encryption standard documented at
00647  * RFC2898[http://www.ietf.org/rfc/rfc2898.txt].  It allows a short password or
00648  * passphrase to be used to create a secure encryption key. If possible, PBKDF2
00649  * as described above should be used if the circumstances allow it.
00650  *
00651  * PKCS #5 uses a Cipher, a pass phrase and a salt to generate an encryption
00652  * key.
00653  *
00654  *   pass_phrase = 'my secure pass phrase goes here'
00655  *   salt = '8 octets'
00656  *
00657  * === Encryption
00658  *
00659  * First set up the cipher for encryption
00660  *
00661  *   encrypter = OpenSSL::Cipher.new 'AES-128-CBC'
00662  *   encrypter.encrypt
00663  *   encrypter.pkcs5_keyivgen pass_phrase, salt
00664  *
00665  * Then pass the data you want to encrypt through
00666  *
00667  *   encrypted = encrypter.update 'top secret document'
00668  *   encrypted << encrypter.final
00669  *
00670  * === Decryption
00671  *
00672  * Use a new Cipher instance set up for decryption
00673  *
00674  *   decrypter = OpenSSL::Cipher.new 'AES-128-CBC'
00675  *   decrypter.decrypt
00676  *   decrypter.pkcs5_keyivgen pass_phrase, salt
00677  *
00678  * Then pass the data you want to decrypt through
00679  *
00680  *   plain = decrypter.update encrypted
00681  *   plain << decrypter.final
00682  *
00683  * == X509 Certificates
00684  *
00685  * === Creating a Certificate
00686  *
00687  * This example creates a self-signed certificate using an RSA key and a SHA1
00688  * signature.
00689  *
00690  *   name = OpenSSL::X509::Name.parse 'CN=nobody/DC=example'
00691  *
00692  *   cert = OpenSSL::X509::Certificate.new
00693  *   cert.version = 2
00694  *   cert.serial = 0
00695  *   cert.not_before = Time.now
00696  *   cert.not_after = Time.now + 3600
00697  *
00698  *   cert.public_key = key.public_key
00699  *   cert.subject = name
00700  *
00701  * === Certificate Extensions
00702  *
00703  * You can add extensions to the certificate with
00704  * OpenSSL::SSL::ExtensionFactory to indicate the purpose of the certificate.
00705  *
00706  *   extension_factory = OpenSSL::X509::ExtensionFactory.new nil, cert
00707  *
00708  *   cert.add_extension \
00709  *     extension_factory.create_extension('basicConstraints', 'CA:FALSE', true)
00710  *
00711  *   cert.add_extension \
00712  *     extension_factory.create_extension(
00713  *       'keyUsage', 'keyEncipherment,dataEncipherment,digitalSignature')
00714  *
00715  *   cert.add_extension \
00716  *     extension_factory.create_extension('subjectKeyIdentifier', 'hash')
00717  *
00718  * The list of supported extensions (and in some cases their possible values)
00719  * can be derived from the "objects.h" file in the OpenSSL source code.
00720  *
00721  * === Signing a Certificate
00722  *
00723  * To sign a certificate set the issuer and use OpenSSL::X509::Certificate#sign
00724  * with a digest algorithm.  This creates a self-signed cert because we're using
00725  * the same name and key to sign the certificate as was used to create the
00726  * certificate.
00727  *
00728  *   cert.issuer = name
00729  *   cert.sign key, OpenSSL::Digest::SHA1.new
00730  *
00731  *   open 'certificate.pem', 'w' do |io| io.write cert.to_pem end
00732  *
00733  * === Loading a Certificate
00734  *
00735  * Like a key, a cert can also be loaded from a file.
00736  *
00737  *   cert2 = OpenSSL::X509::Certificate.new File.read 'certificate.pem'
00738  *
00739  * === Verifying a Certificate
00740  *
00741  * Certificate#verify will return true when a certificate was signed with the
00742  * given public key.
00743  *
00744  *   raise 'certificate can not be verified' unless cert2.verify key
00745  *
00746  * == Certificate Authority
00747  *
00748  * A certificate authority (CA) is a trusted third party that allows you to
00749  * verify the ownership of unknown certificates.  The CA issues key signatures
00750  * that indicate it trusts the user of that key.  A user encountering the key
00751  * can verify the signature by using the CA's public key.
00752  *
00753  * === CA Key
00754  *
00755  * CA keys are valuable, so we encrypt and save it to disk and make sure it is
00756  * not readable by other users.
00757  *
00758  *   ca_key = OpenSSL::PKey::RSA.new 2048
00759  *
00760  *   cipher = OpenSSL::Cipher::Cipher.new 'AES-128-CBC'
00761  *
00762  *   open 'ca_key.pem', 'w', 0400 do |io|
00763  *     io.write key.export(cipher, pass_phrase)
00764  *   end
00765  *
00766  * === CA Certificate
00767  *
00768  * A CA certificate is created the same way we created a certificate above, but
00769  * with different extensions.
00770  *
00771  *   ca_name = OpenSSL::X509::Name.parse 'CN=ca/DC=example'
00772  *
00773  *   ca_cert = OpenSSL::X509::Certificate.new
00774  *   ca_cert.serial = 0
00775  *   ca_cert.version = 2
00776  *   ca_cert.not_before = Time.now
00777  *   ca_cert.not_after = Time.now + 86400
00778  *
00779  *   ca_cert.public_key = ca_key.public_key
00780  *   ca_cert.subject = ca_name
00781  *   ca_cert.issuer = ca_name
00782  *
00783  *   extension_factory = OpenSSL::X509::ExtensionFactory.new
00784  *   extension_factory.subject_certificate = ca_cert
00785  *   extension_factory.issuer_certificate = ca_cert
00786  *
00787  *   ca_cert.add_extension \
00788  *     extension_factory.create_extension('subjectKeyIdentifier', 'hash')
00789  *
00790  * This extension indicates the CA's key may be used as a CA.
00791  *
00792  *   ca_cert.add_extension \
00793  *     extension_factory.create_extension('basicConstraints', 'CA:TRUE', true)
00794  *
00795  * This extension indicates the CA's key may be used to verify signatures on
00796  * both certificates and certificate revocations.
00797  *
00798  *   ca_cert.add_extension \
00799  *     extension_factory.create_extension(
00800  *       'keyUsage', 'cRLSign,keyCertSign', true)
00801  *
00802  * Root CA certificates are self-signed.
00803  *
00804  *   ca_cert.sign ca_key, OpenSSL::Digest::SHA1.new
00805  *
00806  * The CA certificate is saved to disk so it may be distributed to all the
00807  * users of the keys this CA will sign.
00808  *
00809  *   open 'ca_cert.pem', 'w' do |io|
00810  *     io.write ca_cert.to_pem
00811  *   end
00812  *
00813  * === Certificate Signing Request
00814  *
00815  * The CA signs keys through a Certificate Signing Request (CSR).  The CSR
00816  * contains the information necessary to identify the key.
00817  *
00818  *   csr = OpenSSL::X509::Request.new
00819  *   csr.version = 0
00820  *   csr.subject = name
00821  *   csr.public_key = key.public_key
00822  *   csr.sign key, OpenSSL::Digest::SHA1.new
00823  *
00824  * A CSR is saved to disk and sent to the CA for signing.
00825  *
00826  *   open 'csr.pem', 'w' do |io|
00827  *     io.write csr.to_pem
00828  *   end
00829  *
00830  * === Creating a Certificate from a CSR
00831  *
00832  * Upon receiving a CSR the CA will verify it before signing it.  A minimal
00833  * verification would be to check the CSR's signature.
00834  *
00835  *   csr = OpenSSL::X509::Request.new File.read 'csr.pem'
00836  *
00837  *   raise 'CSR can not be verified' unless csr.verify csr.public_key
00838  *
00839  * After verification a certificate is created, marked for various usages,
00840  * signed with the CA key and returned to the requester.
00841  *
00842  *   csr_cert = OpenSSL::X509::Certificate.new
00843  *   csr_cert.serial = 0
00844  *   csr_cert.version = 2
00845  *   csr_cert.not_before = Time.now
00846  *   csr_cert.not_after = Time.now + 600
00847  *
00848  *   csr_cert.subject = csr.subject
00849  *   csr_cert.public_key = csr.public_key
00850  *   csr_cert.issuer = ca_cert.subject
00851  *
00852  *   extension_factory = OpenSSL::X509::ExtensionFactory.new
00853  *   extension_factory.subject_certificate = csr_cert
00854  *   extension_factory.issuer_certificate = ca_cert
00855  *
00856  *   csr_cert.add_extension \
00857  *     extension_factory.create_extension('basicConstraints', 'CA:FALSE')
00858  *
00859  *   csr_cert.add_extension \
00860  *     extension_factory.create_extension(
00861  *       'keyUsage', 'keyEncipherment,dataEncipherment,digitalSignature')
00862  *
00863  *   csr_cert.add_extension \
00864  *     extension_factory.create_extension('subjectKeyIdentifier', 'hash')
00865  *
00866  *   csr_cert.sign ca_key, OpenSSL::Digest::SHA1.new
00867  *
00868  *   open 'csr_cert.pem', 'w' do |io|
00869  *     io.write csr_cert.to_pem
00870  *   end
00871  *
00872  * == SSL and TLS Connections
00873  *
00874  * Using our created key and certificate we can create an SSL or TLS connection.
00875  * An SSLContext is used to set up an SSL session.
00876  *
00877  *   context = OpenSSL::SSL::SSLContext.new
00878  *
00879  * === SSL Server
00880  *
00881  * An SSL server requires the certificate and private key to communicate
00882  * securely with its clients:
00883  *
00884  *   context.cert = cert
00885  *   context.key = key
00886  *
00887  * Then create an SSLServer with a TCP server socket and the context.  Use the
00888  * SSLServer like an ordinary TCP server.
00889  *
00890  *   require 'socket'
00891  *
00892  *   tcp_server = TCPServer.new 5000
00893  *   ssl_server = OpenSSL::SSL::SSLServer.new tcp_server, context
00894  *
00895  *   loop do
00896  *     ssl_connection = ssl_server.accept
00897  *
00898  *     data = connection.gets
00899  *
00900  *     response = "I got #{data.dump}"
00901  *     puts response
00902  *
00903  *     connection.puts "I got #{data.dump}"
00904  *     connection.close
00905  *   end
00906  *
00907  * === SSL client
00908  *
00909  * An SSL client is created with a TCP socket and the context.
00910  * SSLSocket#connect must be called to initiate the SSL handshake and start
00911  * encryption.  A key and certificate are not required for the client socket.
00912  *
00913  *   require 'socket'
00914  *
00915  *   tcp_client = TCPSocket.new 'localhost', 5000
00916  *   ssl_client = OpenSSL::SSL::SSLSocket.new client_socket, context
00917  *   ssl_client.connect
00918  *
00919  *   ssl_client.puts "hello server!"
00920  *   puts ssl_client.gets
00921  *
00922  * === Peer Verification
00923  *
00924  * An unverified SSL connection does not provide much security.  For enhanced
00925  * security the client or server can verify the certificate of its peer.
00926  *
00927  * The client can be modified to verify the server's certificate against the
00928  * certificate authority's certificate:
00929  *
00930  *   context.ca_file = 'ca_cert.pem'
00931  *   context.verify_mode = OpenSSL::SSL::VERIFY_PEER
00932  *
00933  *   require 'socket'
00934  *
00935  *   tcp_client = TCPSocket.new 'localhost', 5000
00936  *   ssl_client = OpenSSL::SSL::SSLSocket.new client_socket, context
00937  *   ssl_client.connect
00938  *
00939  *   ssl_client.puts "hello server!"
00940  *   puts ssl_client.gets
00941  *
00942  * If the server certificate is invalid or <tt>context.ca_file</tt> is not set
00943  * when verifying peers an OpenSSL::SSL::SSLError will be raised.
00944  *
00945  */
00946 void
00947 Init_openssl()
00948 {
00949     /*
00950      * Init timezone info
00951      */
00952 #if 0
00953     tzset();
00954 #endif
00955 
00956     /*
00957      * Init all digests, ciphers
00958      */
00959     /* CRYPTO_malloc_init(); */
00960     /* ENGINE_load_builtin_engines(); */
00961     OpenSSL_add_ssl_algorithms();
00962     OpenSSL_add_all_algorithms();
00963     ERR_load_crypto_strings();
00964     SSL_load_error_strings();
00965 
00966     /*
00967      * FIXME:
00968      * On unload do:
00969      */
00970 #if 0
00971     CONF_modules_unload(1);
00972     destroy_ui_method();
00973     EVP_cleanup();
00974     ENGINE_cleanup();
00975     CRYPTO_cleanup_all_ex_data();
00976     ERR_remove_state(0);
00977     ERR_free_strings();
00978 #endif
00979 
00980     /*
00981      * Init main module
00982      */
00983     mOSSL = rb_define_module("OpenSSL");
00984 
00985     /*
00986      * OpenSSL ruby extension version
00987      */
00988     rb_define_const(mOSSL, "VERSION", rb_str_new2(OSSL_VERSION));
00989 
00990     /*
00991      * Version of OpenSSL the ruby OpenSSL extension was built with
00992      */
00993     rb_define_const(mOSSL, "OPENSSL_VERSION", rb_str_new2(OPENSSL_VERSION_TEXT));
00994 
00995     /*
00996      * Version number of OpenSSL the ruby OpenSSL extension was built with
00997      * (base 16)
00998      */
00999     rb_define_const(mOSSL, "OPENSSL_VERSION_NUMBER", INT2NUM(OPENSSL_VERSION_NUMBER));
01000 
01001     /*
01002      * Boolean indicating whether OpenSSL is FIPS-enabled or not
01003      */
01004 #ifdef HAVE_OPENSSL_FIPS
01005     rb_define_const(mOSSL, "OPENSSL_FIPS", Qtrue);
01006 #else
01007     rb_define_const(mOSSL, "OPENSSL_FIPS", Qfalse);
01008 #endif
01009     rb_define_module_function(mOSSL, "fips_mode=", ossl_fips_mode_set, 1);
01010 
01011     /*
01012      * Generic error,
01013      * common for all classes under OpenSSL module
01014      */
01015     eOSSLError = rb_define_class_under(mOSSL,"OpenSSLError",rb_eStandardError);
01016 
01017     /*
01018      * Verify callback Proc index for ext-data
01019      */
01020     if ((ossl_verify_cb_idx = X509_STORE_CTX_get_ex_new_index(0, (void *)"ossl_verify_cb_idx", 0, 0, 0)) < 0)
01021         ossl_raise(eOSSLError, "X509_STORE_CTX_get_ex_new_index");
01022 
01023     /*
01024      * Init debug core
01025      */
01026     dOSSL = Qfalse;
01027     rb_define_module_function(mOSSL, "debug", ossl_debug_get, 0);
01028     rb_define_module_function(mOSSL, "debug=", ossl_debug_set, 1);
01029     rb_define_module_function(mOSSL, "errors", ossl_get_errors, 0);
01030 
01031     /*
01032      * Get ID of to_der
01033      */
01034     ossl_s_to_der = rb_intern("to_der");
01035 
01036     /*
01037      * Init components
01038      */
01039     Init_ossl_bn();
01040     Init_ossl_cipher();
01041     Init_ossl_config();
01042     Init_ossl_digest();
01043     Init_ossl_hmac();
01044     Init_ossl_ns_spki();
01045     Init_ossl_pkcs12();
01046     Init_ossl_pkcs7();
01047     Init_ossl_pkcs5();
01048     Init_ossl_pkey();
01049     Init_ossl_rand();
01050     Init_ossl_ssl();
01051     Init_ossl_x509();
01052     Init_ossl_ocsp();
01053     Init_ossl_engine();
01054     Init_ossl_asn1();
01055 }
01056 
01057 #if defined(OSSL_DEBUG)
01058 /*
01059  * Check if all symbols are OK with 'make LDSHARED=gcc all'
01060  */
01061 int
01062 main(int argc, char *argv[])
01063 {
01064     return 0;
01065 }
01066 #endif /* OSSL_DEBUG */
01067 
01068