Ruby  2.0.0p247(2013-06-27revision41674)
ext/openssl/ossl_cipher.c
Go to the documentation of this file.
00001 /*
00002  * $Id: ossl_cipher.c 38492 2012-12-20 07:42:56Z emboss $
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 
00013 #define WrapCipher(obj, klass, ctx) \
00014     (obj) = Data_Wrap_Struct((klass), 0, ossl_cipher_free, (ctx))
00015 #define MakeCipher(obj, klass, ctx) \
00016     (obj) = Data_Make_Struct((klass), EVP_CIPHER_CTX, 0, ossl_cipher_free, (ctx))
00017 #define AllocCipher(obj, ctx) \
00018     memset(DATA_PTR(obj) = (ctx) = ALLOC(EVP_CIPHER_CTX), 0, sizeof(EVP_CIPHER_CTX))
00019 #define GetCipherInit(obj, ctx) do { \
00020     Data_Get_Struct((obj), EVP_CIPHER_CTX, (ctx)); \
00021 } while (0)
00022 #define GetCipher(obj, ctx) do { \
00023     GetCipherInit((obj), (ctx)); \
00024     if (!(ctx)) { \
00025         ossl_raise(rb_eRuntimeError, "Cipher not inititalized!"); \
00026     } \
00027 } while (0)
00028 #define SafeGetCipher(obj, ctx) do { \
00029     OSSL_Check_Kind((obj), cCipher); \
00030     GetCipher((obj), (ctx)); \
00031 } while (0)
00032 
00033 /*
00034  * Classes
00035  */
00036 VALUE cCipher;
00037 VALUE eCipherError;
00038 
00039 static VALUE ossl_cipher_alloc(VALUE klass);
00040 
00041 /*
00042  * PUBLIC
00043  */
00044 const EVP_CIPHER *
00045 GetCipherPtr(VALUE obj)
00046 {
00047     EVP_CIPHER_CTX *ctx;
00048 
00049     SafeGetCipher(obj, ctx);
00050 
00051     return EVP_CIPHER_CTX_cipher(ctx);
00052 }
00053 
00054 VALUE
00055 ossl_cipher_new(const EVP_CIPHER *cipher)
00056 {
00057     VALUE ret;
00058     EVP_CIPHER_CTX *ctx;
00059 
00060     ret = ossl_cipher_alloc(cCipher);
00061     AllocCipher(ret, ctx);
00062     EVP_CIPHER_CTX_init(ctx);
00063     if (EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, -1) != 1)
00064         ossl_raise(eCipherError, NULL);
00065 
00066     return ret;
00067 }
00068 
00069 /*
00070  * PRIVATE
00071  */
00072 static void
00073 ossl_cipher_free(EVP_CIPHER_CTX *ctx)
00074 {
00075     if (ctx) {
00076         EVP_CIPHER_CTX_cleanup(ctx);
00077         ruby_xfree(ctx);
00078     }
00079 }
00080 
00081 static VALUE
00082 ossl_cipher_alloc(VALUE klass)
00083 {
00084     VALUE obj;
00085 
00086     WrapCipher(obj, klass, 0);
00087 
00088     return obj;
00089 }
00090 
00091 /*
00092  *  call-seq:
00093  *     Cipher.new(string) -> cipher
00094  *
00095  *  The string must contain a valid cipher name like "AES-128-CBC" or "3DES".
00096  *
00097  *  A list of cipher names is available by calling OpenSSL::Cipher.ciphers.
00098  */
00099 static VALUE
00100 ossl_cipher_initialize(VALUE self, VALUE str)
00101 {
00102     EVP_CIPHER_CTX *ctx;
00103     const EVP_CIPHER *cipher;
00104     char *name;
00105     unsigned char key[EVP_MAX_KEY_LENGTH];
00106 
00107     name = StringValuePtr(str);
00108     GetCipherInit(self, ctx);
00109     if (ctx) {
00110         ossl_raise(rb_eRuntimeError, "Cipher already inititalized!");
00111     }
00112     AllocCipher(self, ctx);
00113     EVP_CIPHER_CTX_init(ctx);
00114     if (!(cipher = EVP_get_cipherbyname(name))) {
00115         ossl_raise(rb_eRuntimeError, "unsupported cipher algorithm (%s)", name);
00116     }
00117     /*
00118      * The EVP which has EVP_CIPH_RAND_KEY flag (such as DES3) allows
00119      * uninitialized key, but other EVPs (such as AES) does not allow it.
00120      * Calling EVP_CipherUpdate() without initializing key causes SEGV so we
00121      * set the data filled with "\0" as the key by default.
00122      */
00123     memset(key, 0, EVP_MAX_KEY_LENGTH);
00124     if (EVP_CipherInit_ex(ctx, cipher, NULL, key, NULL, -1) != 1)
00125         ossl_raise(eCipherError, NULL);
00126 
00127     return self;
00128 }
00129 
00130 static VALUE
00131 ossl_cipher_copy(VALUE self, VALUE other)
00132 {
00133     EVP_CIPHER_CTX *ctx1, *ctx2;
00134 
00135     rb_check_frozen(self);
00136     if (self == other) return self;
00137 
00138     GetCipherInit(self, ctx1);
00139     if (!ctx1) {
00140         AllocCipher(self, ctx1);
00141     }
00142     SafeGetCipher(other, ctx2);
00143     if (EVP_CIPHER_CTX_copy(ctx1, ctx2) != 1)
00144         ossl_raise(eCipherError, NULL);
00145 
00146     return self;
00147 }
00148 
00149 #ifdef HAVE_OBJ_NAME_DO_ALL_SORTED
00150 static void*
00151 add_cipher_name_to_ary(const OBJ_NAME *name, VALUE ary)
00152 {
00153     rb_ary_push(ary, rb_str_new2(name->name));
00154     return NULL;
00155 }
00156 #endif
00157 
00158 #ifdef HAVE_OBJ_NAME_DO_ALL_SORTED
00159 /*
00160  *  call-seq:
00161  *     Cipher.ciphers -> array[string...]
00162  *
00163  *  Returns the names of all available ciphers in an array.
00164  */
00165 static VALUE
00166 ossl_s_ciphers(VALUE self)
00167 {
00168     VALUE ary;
00169 
00170     ary = rb_ary_new();
00171     OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH,
00172                     (void(*)(const OBJ_NAME*,void*))add_cipher_name_to_ary,
00173                     (void*)ary);
00174 
00175     return ary;
00176 }
00177 #else
00178 #define ossl_s_ciphers rb_f_notimplement
00179 #endif
00180 
00181 /*
00182  *  call-seq:
00183  *     cipher.reset -> self
00184  *
00185  *  Fully resets the internal state of the Cipher. By using this, the same
00186  *  Cipher instance may be used several times for en- or decryption tasks.
00187  *
00188  *  Internally calls EVP_CipherInit_ex(ctx, NULL, NULL, NULL, NULL, -1).
00189  */
00190 static VALUE
00191 ossl_cipher_reset(VALUE self)
00192 {
00193     EVP_CIPHER_CTX *ctx;
00194 
00195     GetCipher(self, ctx);
00196     if (EVP_CipherInit_ex(ctx, NULL, NULL, NULL, NULL, -1) != 1)
00197         ossl_raise(eCipherError, NULL);
00198 
00199     return self;
00200 }
00201 
00202 static VALUE
00203 ossl_cipher_init(int argc, VALUE *argv, VALUE self, int mode)
00204 {
00205     EVP_CIPHER_CTX *ctx;
00206     unsigned char key[EVP_MAX_KEY_LENGTH], *p_key = NULL;
00207     unsigned char iv[EVP_MAX_IV_LENGTH], *p_iv = NULL;
00208     VALUE pass, init_v;
00209 
00210     if(rb_scan_args(argc, argv, "02", &pass, &init_v) > 0){
00211         /*
00212          * oops. this code mistakes salt for IV.
00213          * We deprecated the arguments for this method, but we decided
00214          * keeping this behaviour for backward compatibility.
00215          */
00216         const char *cname  = rb_class2name(rb_obj_class(self));
00217         rb_warn("arguments for %s#encrypt and %s#decrypt were deprecated; "
00218                 "use %s#pkcs5_keyivgen to derive key and IV",
00219                 cname, cname, cname);
00220         StringValue(pass);
00221         GetCipher(self, ctx);
00222         if (NIL_P(init_v)) memcpy(iv, "OpenSSL for Ruby rulez!", sizeof(iv));
00223         else{
00224             StringValue(init_v);
00225             if (EVP_MAX_IV_LENGTH > RSTRING_LEN(init_v)) {
00226                 memset(iv, 0, EVP_MAX_IV_LENGTH);
00227                 memcpy(iv, RSTRING_PTR(init_v), RSTRING_LEN(init_v));
00228             }
00229             else memcpy(iv, RSTRING_PTR(init_v), sizeof(iv));
00230         }
00231         EVP_BytesToKey(EVP_CIPHER_CTX_cipher(ctx), EVP_md5(), iv,
00232                        (unsigned char *)RSTRING_PTR(pass), RSTRING_LENINT(pass), 1, key, NULL);
00233         p_key = key;
00234         p_iv = iv;
00235     }
00236     else {
00237         GetCipher(self, ctx);
00238     }
00239     if (EVP_CipherInit_ex(ctx, NULL, NULL, p_key, p_iv, mode) != 1) {
00240         ossl_raise(eCipherError, NULL);
00241     }
00242 
00243     return self;
00244 }
00245 
00246 /*
00247  *  call-seq:
00248  *     cipher.encrypt -> self
00249  *
00250  *  Initializes the Cipher for encryption.
00251  *
00252  *  Make sure to call Cipher#encrypt or Cipher#decrypt before using any of the
00253  *  following methods:
00254  *  * [key=, iv=, random_key, random_iv, pkcs5_keyivgen]
00255  *
00256  *  Internally calls EVP_CipherInit_ex(ctx, NULL, NULL, NULL, NULL, 1).
00257  */
00258 static VALUE
00259 ossl_cipher_encrypt(int argc, VALUE *argv, VALUE self)
00260 {
00261     return ossl_cipher_init(argc, argv, self, 1);
00262 }
00263 
00264 /*
00265  *  call-seq:
00266  *     cipher.decrypt -> self
00267  *
00268  *  Initializes the Cipher for decryption.
00269  *
00270  *  Make sure to call Cipher#encrypt or Cipher#decrypt before using any of the
00271  *  following methods:
00272  *  * [key=, iv=, random_key, random_iv, pkcs5_keyivgen]
00273  *
00274  *  Internally calls EVP_CipherInit_ex(ctx, NULL, NULL, NULL, NULL, 0).
00275  */
00276 static VALUE
00277 ossl_cipher_decrypt(int argc, VALUE *argv, VALUE self)
00278 {
00279     return ossl_cipher_init(argc, argv, self, 0);
00280 }
00281 
00282 /*
00283  *  call-seq:
00284  *     cipher.pkcs5_keyivgen(pass [, salt [, iterations [, digest]]] ) -> nil
00285  *
00286  *  Generates and sets the key/IV based on a password.
00287  *
00288  *  WARNING: This method is only PKCS5 v1.5 compliant when using RC2, RC4-40,
00289  *  or DES with MD5 or SHA1. Using anything else (like AES) will generate the
00290  *  key/iv using an OpenSSL specific method. This method is deprecated and
00291  *  should no longer be used. Use a PKCS5 v2 key generation method from
00292  *  OpenSSL::PKCS5 instead.
00293  *
00294  *  === Parameters
00295  *  +salt+ must be an 8 byte string if provided.
00296  *  +iterations+ is a integer with a default of 2048.
00297  *  +digest+ is a Digest object that defaults to 'MD5'
00298  *
00299  *  A minimum of 1000 iterations is recommended.
00300  *
00301  */
00302 static VALUE
00303 ossl_cipher_pkcs5_keyivgen(int argc, VALUE *argv, VALUE self)
00304 {
00305     EVP_CIPHER_CTX *ctx;
00306     const EVP_MD *digest;
00307     VALUE vpass, vsalt, viter, vdigest;
00308     unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH], *salt = NULL;
00309     int iter;
00310 
00311     rb_scan_args(argc, argv, "13", &vpass, &vsalt, &viter, &vdigest);
00312     StringValue(vpass);
00313     if(!NIL_P(vsalt)){
00314         StringValue(vsalt);
00315         if(RSTRING_LEN(vsalt) != PKCS5_SALT_LEN)
00316             ossl_raise(eCipherError, "salt must be an 8-octet string");
00317         salt = (unsigned char *)RSTRING_PTR(vsalt);
00318     }
00319     iter = NIL_P(viter) ? 2048 : NUM2INT(viter);
00320     digest = NIL_P(vdigest) ? EVP_md5() : GetDigestPtr(vdigest);
00321     GetCipher(self, ctx);
00322     EVP_BytesToKey(EVP_CIPHER_CTX_cipher(ctx), digest, salt,
00323                    (unsigned char *)RSTRING_PTR(vpass), RSTRING_LENINT(vpass), iter, key, iv);
00324     if (EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, -1) != 1)
00325         ossl_raise(eCipherError, NULL);
00326     OPENSSL_cleanse(key, sizeof key);
00327     OPENSSL_cleanse(iv, sizeof iv);
00328 
00329     return Qnil;
00330 }
00331 
00332 /*
00333  *  call-seq:
00334  *     cipher.update(data [, buffer]) -> string or buffer
00335  *
00336  *  Encrypts data in a streaming fashion. Hand consecutive blocks of data
00337  *  to the +update+ method in order to encrypt it. Returns the encrypted
00338  *  data chunk. When done, the output of Cipher#final should be additionally
00339  *  added to the result.
00340  *
00341  *  === Parameters
00342  *  +data+ is a nonempty string.
00343  *  +buffer+ is an optional string to store the result.
00344  */
00345 static VALUE
00346 ossl_cipher_update(int argc, VALUE *argv, VALUE self)
00347 {
00348     EVP_CIPHER_CTX *ctx;
00349     unsigned char *in;
00350     int in_len, out_len;
00351     VALUE data, str;
00352 
00353     rb_scan_args(argc, argv, "11", &data, &str);
00354 
00355     StringValue(data);
00356     in = (unsigned char *)RSTRING_PTR(data);
00357     if ((in_len = RSTRING_LENINT(data)) == 0)
00358         ossl_raise(rb_eArgError, "data must not be empty");
00359     GetCipher(self, ctx);
00360     out_len = in_len+EVP_CIPHER_CTX_block_size(ctx);
00361 
00362     if (NIL_P(str)) {
00363         str = rb_str_new(0, out_len);
00364     } else {
00365         StringValue(str);
00366         rb_str_resize(str, out_len);
00367     }
00368 
00369     if (!EVP_CipherUpdate(ctx, (unsigned char *)RSTRING_PTR(str), &out_len, in, in_len))
00370         ossl_raise(eCipherError, NULL);
00371     assert(out_len < RSTRING_LEN(str));
00372     rb_str_set_len(str, out_len);
00373 
00374     return str;
00375 }
00376 
00377 /*
00378  *  call-seq:
00379  *     cipher.final -> string
00380  *
00381  *  Returns the remaining data held in the cipher object. Further calls to
00382  *  Cipher#update or Cipher#final will return garbage. This call should always
00383  *  be made as the last call of an encryption or decryption operation, after
00384  *  after having fed the entire plaintext or ciphertext to the Cipher instance.
00385  *
00386  *  If an authenticated cipher was used, a CipherError is raised if the tag
00387  *  could not be authenticated successfully. Only call this method after
00388  *  setting the authentication tag and passing the entire contents of the
00389  *  ciphertext into the cipher.
00390  */
00391 static VALUE
00392 ossl_cipher_final(VALUE self)
00393 {
00394     EVP_CIPHER_CTX *ctx;
00395     int out_len;
00396     VALUE str;
00397 
00398     GetCipher(self, ctx);
00399     str = rb_str_new(0, EVP_CIPHER_CTX_block_size(ctx));
00400     if (!EVP_CipherFinal_ex(ctx, (unsigned char *)RSTRING_PTR(str), &out_len))
00401         ossl_raise(eCipherError, NULL);
00402     assert(out_len <= RSTRING_LEN(str));
00403     rb_str_set_len(str, out_len);
00404 
00405     return str;
00406 }
00407 
00408 /*
00409  *  call-seq:
00410  *     cipher.name -> string
00411  *
00412  *  Returns the name of the cipher which may differ slightly from the original
00413  *  name provided.
00414  */
00415 static VALUE
00416 ossl_cipher_name(VALUE self)
00417 {
00418     EVP_CIPHER_CTX *ctx;
00419 
00420     GetCipher(self, ctx);
00421 
00422     return rb_str_new2(EVP_CIPHER_name(EVP_CIPHER_CTX_cipher(ctx)));
00423 }
00424 
00425 /*
00426  *  call-seq:
00427  *     cipher.key = string -> string
00428  *
00429  *  Sets the cipher key. To generate a key, you should either use a secure
00430  *  random byte string or, if the key is to be derived from a password, you
00431  *  should rely on PBKDF2 functionality provided by OpenSSL::PKCS5. To
00432  *  generate a secure random-based key, Cipher#random_key may be used.
00433  *
00434  *  Only call this method after calling Cipher#encrypt or Cipher#decrypt.
00435  */
00436 static VALUE
00437 ossl_cipher_set_key(VALUE self, VALUE key)
00438 {
00439     EVP_CIPHER_CTX *ctx;
00440 
00441     StringValue(key);
00442     GetCipher(self, ctx);
00443 
00444     if (RSTRING_LEN(key) < EVP_CIPHER_CTX_key_length(ctx))
00445         ossl_raise(eCipherError, "key length too short");
00446 
00447     if (EVP_CipherInit_ex(ctx, NULL, NULL, (unsigned char *)RSTRING_PTR(key), NULL, -1) != 1)
00448         ossl_raise(eCipherError, NULL);
00449 
00450     return key;
00451 }
00452 
00453 /*
00454  *  call-seq:
00455  *     cipher.iv = string -> string
00456  *
00457  *  Sets the cipher IV. Please note that since you should never be using ECB
00458  *  mode, an IV is always explicitly required and should be set prior to
00459  *  encryption. The IV itself can be safely transmitted in public, but it
00460  *  should be unpredictable to prevent certain kinds of attacks. You may use
00461  *  Cipher#random_iv to create a secure random IV.
00462  *
00463  *  Only call this method after calling Cipher#encrypt or Cipher#decrypt.
00464  *
00465  *  If not explicitly set, the OpenSSL default of an all-zeroes ("\\0") IV is
00466  *  used.
00467  */
00468 static VALUE
00469 ossl_cipher_set_iv(VALUE self, VALUE iv)
00470 {
00471     EVP_CIPHER_CTX *ctx;
00472 
00473     StringValue(iv);
00474     GetCipher(self, ctx);
00475 
00476     if (RSTRING_LEN(iv) < EVP_CIPHER_CTX_iv_length(ctx))
00477         ossl_raise(eCipherError, "iv length too short");
00478 
00479     if (EVP_CipherInit_ex(ctx, NULL, NULL, NULL, (unsigned char *)RSTRING_PTR(iv), -1) != 1)
00480         ossl_raise(eCipherError, NULL);
00481 
00482     return iv;
00483 }
00484 
00485 #ifdef HAVE_AUTHENTICATED_ENCRYPTION
00486 /*
00487  *  call-seq:
00488  *     cipher.auth_data = string -> string
00489  *
00490  *  Sets the cipher's additional authenticated data. This field must be
00491  *  set when using AEAD cipher modes such as GCM or CCM. If no associated
00492  *  data shall be used, this method must *still* be called with a value of "".
00493  *  The contents of this field should be non-sensitive data which will be
00494  *  added to the ciphertext to generate the authentication tag which validates
00495  *  the contents of the ciphertext.
00496  *
00497  *  The AAD must be set prior to encryption or decryption. In encryption mode,
00498  *  it must be set after calling Cipher#encrypt and setting Cipher#key= and
00499  *  Cipher#iv=. When decrypting, the authenticated data must be set after key,
00500  *  iv and especially *after* the authentication tag has been set. I.e. set it
00501  *  only after calling Cipher#decrypt, Cipher#key=, Cipher#iv= and
00502  *  Cipher#auth_tag= first.
00503  */
00504 static VALUE
00505 ossl_cipher_set_auth_data(VALUE self, VALUE data)
00506 {
00507     EVP_CIPHER_CTX *ctx;
00508     unsigned char *in;
00509     int in_len;
00510     int out_len;
00511 
00512     StringValue(data);
00513 
00514     in = (unsigned char *) RSTRING_PTR(data);
00515     in_len = RSTRING_LENINT(data);
00516 
00517     GetCipher(self, ctx);
00518 
00519     if (!EVP_CipherUpdate(ctx, NULL, &out_len, in, in_len))
00520         ossl_raise(eCipherError, "couldn't set additional authenticated data");
00521 
00522     return data;
00523 }
00524 
00525 #define ossl_is_gcm(nid)        (nid) == NID_aes_128_gcm || \
00526                                 (nid) == NID_aes_192_gcm || \
00527                                 (nid) == NID_aes_256_gcm
00528 
00529 static VALUE
00530 ossl_get_gcm_auth_tag(EVP_CIPHER_CTX *ctx, int len)
00531 {
00532     unsigned char *tag;
00533     VALUE ret;
00534 
00535     tag = ALLOC_N(unsigned char, len);
00536 
00537     if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, len, tag))
00538         ossl_raise(eCipherError, "retrieving the authentication tag failed");
00539 
00540     ret = rb_str_new((const char *) tag, len);
00541     xfree(tag);
00542     return ret;
00543 }
00544 
00545 /*
00546  *  call-seq:
00547  *     cipher.auth_tag([ tag_len ] -> string
00548  *
00549  *  Gets the authentication tag generated by Authenticated Encryption Cipher
00550  *  modes (GCM for example). This tag may be stored along with the ciphertext,
00551  *  then set on the decryption cipher to authenticate the contents of the
00552  *  ciphertext against changes. If the optional integer parameter +tag_len+ is
00553  *  given, the returned tag will be +tag_len+ bytes long. If the parameter is
00554  *  omitted, the maximum length of 16 bytes will be returned. For maximum
00555  *  security, the default of 16 bytes should be chosen.
00556  *
00557  *  The tag may only be retrieved after calling Cipher#final.
00558  */
00559 static VALUE
00560 ossl_cipher_get_auth_tag(int argc, VALUE *argv, VALUE self)
00561 {
00562     VALUE vtag_len;
00563     EVP_CIPHER_CTX *ctx;
00564     int nid, tag_len;
00565 
00566     if (rb_scan_args(argc, argv, "01", &vtag_len) == 0) {
00567         tag_len = 16;
00568     } else {
00569         tag_len = NUM2INT(vtag_len);
00570     }
00571 
00572     GetCipher(self, ctx);
00573     nid = EVP_CIPHER_CTX_nid(ctx);
00574 
00575     if (ossl_is_gcm(nid)) {
00576         return ossl_get_gcm_auth_tag(ctx, tag_len);
00577     } else {
00578         ossl_raise(eCipherError, "authentication tag not supported by this cipher");
00579         return Qnil; /* dummy */
00580     }
00581 }
00582 
00583 static inline void
00584 ossl_set_gcm_auth_tag(EVP_CIPHER_CTX *ctx, unsigned char *tag, int tag_len)
00585 {
00586     if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, tag_len, tag))
00587         ossl_raise(eCipherError, "unable to set GCM tag");
00588 }
00589 
00590 /*
00591  *  call-seq:
00592  *     cipher.auth_tag = string -> string
00593  *
00594  *  Sets the authentication tag to verify the contents of the
00595  *  ciphertext. The tag must be set after calling Cipher#decrypt,
00596  *  Cipher#key= and Cipher#iv=, but before assigning the associated
00597  *  authenticated data using Cipher#auth_data= and of course, before
00598  *  decrypting any of the ciphertext. After all decryption is
00599  *  performed, the tag is verified automatically in the call to
00600  *  Cipher#final.
00601  */
00602 static VALUE
00603 ossl_cipher_set_auth_tag(VALUE self, VALUE vtag)
00604 {
00605     EVP_CIPHER_CTX *ctx;
00606     int nid;
00607     unsigned char *tag;
00608     int tag_len;
00609 
00610     StringValue(vtag);
00611     tag = (unsigned char *) RSTRING_PTR(vtag);
00612     tag_len = RSTRING_LENINT(vtag);
00613 
00614     GetCipher(self, ctx);
00615     nid = EVP_CIPHER_CTX_nid(ctx);
00616 
00617     if (ossl_is_gcm(nid)) {
00618         ossl_set_gcm_auth_tag(ctx, tag, tag_len);
00619     } else {
00620         ossl_raise(eCipherError, "authentication tag not supported by this cipher");
00621     }
00622 
00623     return vtag;
00624 }
00625 
00626 /*
00627  *  call-seq:
00628  *     cipher.authenticated? -> boolean
00629  *
00630  *  Indicated whether this Cipher instance uses an Authenticated Encryption
00631  *  mode.
00632  */
00633 static VALUE
00634 ossl_cipher_is_authenticated(VALUE self)
00635 {
00636     EVP_CIPHER_CTX *ctx;
00637     int nid;
00638 
00639     GetCipher(self, ctx);
00640     nid = EVP_CIPHER_CTX_nid(ctx);
00641 
00642     if (ossl_is_gcm(nid)) {
00643         return Qtrue;
00644     } else {
00645         return Qfalse;
00646     }
00647 }
00648 #else
00649 #define ossl_cipher_set_auth_data rb_f_notimplement
00650 #define ossl_cipher_get_auth_tag rb_f_notimplement
00651 #define ossl_cipher_set_auth_tag rb_f_notimplement
00652 #define ossl_cipher_is_authenticated rb_f_notimplement
00653 #endif
00654 
00655 /*
00656  *  call-seq:
00657  *     cipher.key_len = integer -> integer
00658  *
00659  *  Sets the key length of the cipher.  If the cipher is a fixed length cipher
00660  *  then attempting to set the key length to any value other than the fixed
00661  *  value is an error.
00662  *
00663  *  Under normal circumstances you do not need to call this method (and probably shouldn't).
00664  *
00665  *  See EVP_CIPHER_CTX_set_key_length for further information.
00666  */
00667 static VALUE
00668 ossl_cipher_set_key_length(VALUE self, VALUE key_length)
00669 {
00670     int len = NUM2INT(key_length);
00671     EVP_CIPHER_CTX *ctx;
00672 
00673     GetCipher(self, ctx);
00674     if (EVP_CIPHER_CTX_set_key_length(ctx, len) != 1)
00675         ossl_raise(eCipherError, NULL);
00676 
00677     return key_length;
00678 }
00679 
00680 #if defined(HAVE_EVP_CIPHER_CTX_SET_PADDING)
00681 /*
00682  *  call-seq:
00683  *     cipher.padding = integer -> integer
00684  *
00685  *  Enables or disables padding. By default encryption operations are padded using standard block padding and the
00686  *  padding is checked and removed when decrypting. If the pad parameter is zero then no padding is performed, the
00687  *  total amount of data encrypted or decrypted must then be a multiple of the block size or an error will occur.
00688  *
00689  *  See EVP_CIPHER_CTX_set_padding for further information.
00690  */
00691 static VALUE
00692 ossl_cipher_set_padding(VALUE self, VALUE padding)
00693 {
00694     EVP_CIPHER_CTX *ctx;
00695     int pad = NUM2INT(padding);
00696 
00697     GetCipher(self, ctx);
00698     if (EVP_CIPHER_CTX_set_padding(ctx, pad) != 1)
00699         ossl_raise(eCipherError, NULL);
00700     return padding;
00701 }
00702 #else
00703 #define ossl_cipher_set_padding rb_f_notimplement
00704 #endif
00705 
00706 #define CIPHER_0ARG_INT(func)                                   \
00707     static VALUE                                                \
00708     ossl_cipher_##func(VALUE self)                              \
00709     {                                                           \
00710         EVP_CIPHER_CTX *ctx;                                    \
00711         GetCipher(self, ctx);                                   \
00712         return INT2NUM(EVP_CIPHER_##func(EVP_CIPHER_CTX_cipher(ctx)));  \
00713     }
00714 
00715 /*
00716  *  call-seq:
00717  *     cipher.key_len -> integer
00718  *
00719  *  Returns the key length in bytes of the Cipher.
00720  */
00721 CIPHER_0ARG_INT(key_length)
00722 /*
00723  *  call-seq:
00724  *     cipher.iv_len -> integer
00725  *
00726  *  Returns the expected length in bytes for an IV for this Cipher.
00727  */
00728 CIPHER_0ARG_INT(iv_length)
00729 /*
00730  *  call-seq:
00731  *     cipher.block_size -> integer
00732  *
00733  *  Returns the size in bytes of the blocks on which this Cipher operates on.
00734  */
00735 CIPHER_0ARG_INT(block_size)
00736 
00737 /*
00738  * INIT
00739  */
00740 void
00741 Init_ossl_cipher(void)
00742 {
00743 #if 0
00744     mOSSL = rb_define_module("OpenSSL"); /* let rdoc know about mOSSL */
00745 #endif
00746 
00747     /* Document-class: OpenSSL::Cipher
00748      *
00749      * Provides symmetric algorithms for encryption and decryption. The
00750      * algorithms that are available depend on the particular version
00751      * of OpenSSL that is installed.
00752      *
00753      * === Listing all supported algorithms
00754      *
00755      * A list of supported algorithms can be obtained by
00756      *
00757      *   puts OpenSSL::Cipher.ciphers
00758      *
00759      * === Instantiating a Cipher
00760      *
00761      * There are several ways to create a Cipher instance. Generally, a
00762      * Cipher algorithm is categorized by its name, the key length in bits
00763      * and the cipher mode to be used. The most generic way to create a
00764      * Cipher is the following
00765      *
00766      *   cipher = OpenSSL::Cipher.new('<name>-<key length>-<mode>')
00767      *
00768      * That is, a string consisting of the hyphenated concatenation of the
00769      * individual components name, key length and mode. Either all uppercase
00770      * or all lowercase strings may be used, for example:
00771      *
00772      *  cipher = OpenSSL::Cipher.new('AES-128-CBC')
00773      *
00774      * For each algorithm supported, there is a class defined under the
00775      * Cipher class that goes by the name of the cipher, e.g. to obtain an
00776      * instance of AES, you could also use
00777      *
00778      *   # these are equivalent
00779      *   cipher = OpenSSL::Cipher::AES.new(128, :CBC)
00780      *   cipher = OpenSSL::Cipher::AES.new(128, 'CBC')
00781      *   cipher = OpenSSL::Cipher::AES.new('128-CBC')
00782      *
00783      * Finally, due to its wide-spread use, there are also extra classes
00784      * defined for the different key sizes of AES
00785      *
00786      *   cipher = OpenSSL::Cipher::AES128.new(:CBC)
00787      *   cipher = OpenSSL::Cipher::AES192.new(:CBC)
00788      *   cipher = OpenSSL::Cipher::AES256.new(:CBC)
00789      *
00790      * === Choosing either encryption or decryption mode
00791      *
00792      * Encryption and decryption are often very similar operations for
00793      * symmetric algorithms, this is reflected by not having to choose
00794      * different classes for either operation, both can be done using the
00795      * same class. Still, after obtaining a Cipher instance, we need to
00796      * tell the instance what it is that we intend to do with it, so we
00797      * need to call either
00798      *
00799      *   cipher.encrypt
00800      *
00801      * or
00802      *
00803      *   cipher.decrypt
00804      *
00805      * on the Cipher instance. This should be the first call after creating
00806      * the instance, otherwise configuration that has already been set could
00807      * get lost in the process.
00808      *
00809      * === Choosing a key
00810      *
00811      * Symmetric encryption requires a key that is the same for the encrypting
00812      * and for the decrypting party and after initial key establishment should
00813      * be kept as private information. There are a lot of ways to create
00814      * insecure keys, the most notable is to simply take a password as the key
00815      * without processing the password further. A simple and secure way to
00816      * create a key for a particular Cipher is
00817      *
00818      *  cipher = OpenSSL::AES256.new(:CFB)
00819      *  cipher.encrypt
00820      *  key = cipher.random_key # also sets the generated key on the Cipher
00821      *
00822      * If you absolutely need to use passwords as encryption keys, you
00823      * should use Password-Based Key Derivation Function 2 (PBKDF2) by
00824      * generating the key with the help of the functionality provided by
00825      * OpenSSL::PKCS5.pbkdf2_hmac_sha1 or OpenSSL::PKCS5.pbkdf2_hmac.
00826      *
00827      * Although there is Cipher#pkcs5_keyivgen, its use is deprecated and
00828      * it should only be used in legacy applications because it does not use
00829      * the newer PKCS#5 v2 algorithms.
00830      *
00831      * === Choosing an IV
00832      *
00833      * The cipher modes CBC, CFB, OFB and CTR all need an "initialization
00834      * vector", or short, IV. ECB mode is the only mode that does not require
00835      * an IV, but there is almost no legitimate use case for this mode
00836      * because of the fact that it does not sufficiently hide plaintext
00837      * patterns. Therefore
00838      *
00839      * <b>You should never use ECB mode unless you are absolutely sure that
00840      * you absolutely need it</b>
00841      *
00842      * Because of this, you will end up with a mode that explicitly requires
00843      * an IV in any case. Note that for backwards compatibility reasons,
00844      * setting an IV is not explicitly mandated by the Cipher API. If not
00845      * set, OpenSSL itself defaults to an all-zeroes IV ("\\0", not the
00846      * character). Although the IV can be seen as public information, i.e.
00847      * it may be transmitted in public once generated, it should still stay
00848      * unpredictable to prevent certain kinds of attacks. Therefore, ideally
00849      *
00850      * <b>Always create a secure random IV for every encryption of your
00851      * Cipher</b>
00852      *
00853      * A new, random IV should be created for every encryption of data. Think
00854      * of the IV as a nonce (number used once) - it's public but random and
00855      * unpredictable. A secure random IV can be created as follows
00856      *
00857      *  cipher = ...
00858      *  cipher.encrypt
00859      *  key = cipher.random_key
00860      *  iv = cipher.random_iv # also sets the generated IV on the Cipher
00861      *
00862      *  Although the key is generally a random value, too, it is a bad choice
00863      *  as an IV. There are elaborate ways how an attacker can take advantage
00864      *  of such an IV. As a general rule of thumb, exposing the key directly
00865      *  or indirectly should be avoided at all cost and exceptions only be
00866      *  made with good reason.
00867      *
00868      * === Calling Cipher#final
00869      *
00870      * ECB (which should not be used) and CBC are both block-based modes.
00871      * This means that unlike for the other streaming-based modes, they
00872      * operate on fixed-size blocks of data, and therefore they require a
00873      * "finalization" step to produce or correctly decrypt the last block of
00874      * data by appropriately handling some form of padding. Therefore it is
00875      * essential to add the output of OpenSSL::Cipher#final to your
00876      * encryption/decryption buffer or you will end up with decryption errors
00877      * or truncated data.
00878      *
00879      * Although this is not really necessary for streaming-mode ciphers, it is
00880      * still recommended to apply the same pattern of adding the output of
00881      * Cipher#final there as well - it also enables you to switch between
00882      * modes more easily in the future.
00883      *
00884      * === Encrypting and decrypting some data
00885      *
00886      *   data = "Very, very confidential data"
00887      *
00888      *   cipher = OpenSSL::Cipher::AES.new(128, :CBC)
00889      *   cipher.encrypt
00890      *   key = cipher.random_key
00891      *   iv = cipher.random_iv
00892      *
00893      *   encrypted = cipher.update(data) + cipher.final
00894      *   ...
00895      *   decipher = OpenSSL::Cipher::AES.new(128, :CBC)
00896      *   decipher.decrypt
00897      *   decipher.key = key
00898      *   decipher.iv = iv
00899      *
00900      *   plain = decipher.update(encrypted) + decipher.final
00901      *
00902      *   puts data == plain #=> true
00903      *
00904      * === Authenticated Encryption and Associated Data (AEAD)
00905      *
00906      * If the OpenSSL version used supports it, an Authenticated Encryption
00907      * mode (such as GCM or CCM) should always be preferred over any
00908      * unauthenticated mode. Currently, OpenSSL supports AE only in combination
00909      * with Associated Data (AEAD) where additional associated data is included
00910      * in the encryption process to compute a tag at the end of the encryption.
00911      * This tag will also be used in the decryption process and by verifying
00912      * its validity, the authenticity of a given ciphertext is established.
00913      *
00914      * This is superior to unauthenticated modes in that it allows to detect
00915      * if somebody effectively changed the ciphertext after it had been
00916      * encrypted. This prevents malicious modifications of the ciphertext that
00917      * could otherwise be exploited to modify ciphertexts in ways beneficial to
00918      * potential attackers.
00919      *
00920      * If no associated data is needed for encryption and later decryption,
00921      * the OpenSSL library still requires a value to be set - "" may be used in
00922      * case none is available. An example using the GCM (Galois Counter Mode):
00923      *
00924      *   cipher = OpenSSL::Cipher::AES.new(128, :GCM)
00925      *   cipher.encrypt
00926      *   key = cipher.random_key
00927      *   iv = cipher.random_iv
00928      *   cipher.auth_data = ""
00929      *
00930      *   encrypted = cipher.update(data) + cipher.final
00931      *   tag = cipher.auth_tag
00932      *
00933      *   decipher = OpenSSL::Cipher::AES.new(128, :GCM)
00934      *   decipher.decrypt
00935      *   decipher.key = key
00936      *   decipher.iv = iv
00937      *   decipher.auth_tag = tag
00938      *   decipher.auth_data = ""
00939      *
00940      *   plain = decipher.update(encrypted) + decipher.final
00941      *
00942      *   puts data == plain #=> true
00943      */
00944     cCipher = rb_define_class_under(mOSSL, "Cipher", rb_cObject);
00945     eCipherError = rb_define_class_under(cCipher, "CipherError", eOSSLError);
00946 
00947     rb_define_alloc_func(cCipher, ossl_cipher_alloc);
00948     rb_define_copy_func(cCipher, ossl_cipher_copy);
00949     rb_define_module_function(cCipher, "ciphers", ossl_s_ciphers, 0);
00950     rb_define_method(cCipher, "initialize", ossl_cipher_initialize, 1);
00951     rb_define_method(cCipher, "reset", ossl_cipher_reset, 0);
00952     rb_define_method(cCipher, "encrypt", ossl_cipher_encrypt, -1);
00953     rb_define_method(cCipher, "decrypt", ossl_cipher_decrypt, -1);
00954     rb_define_method(cCipher, "pkcs5_keyivgen", ossl_cipher_pkcs5_keyivgen, -1);
00955     rb_define_method(cCipher, "update", ossl_cipher_update, -1);
00956     rb_define_method(cCipher, "final", ossl_cipher_final, 0);
00957     rb_define_method(cCipher, "name", ossl_cipher_name, 0);
00958     rb_define_method(cCipher, "key=", ossl_cipher_set_key, 1);
00959     rb_define_method(cCipher, "auth_data=", ossl_cipher_set_auth_data, 1);
00960     rb_define_method(cCipher, "auth_tag=", ossl_cipher_set_auth_tag, 1);
00961     rb_define_method(cCipher, "auth_tag", ossl_cipher_get_auth_tag, -1);
00962     rb_define_method(cCipher, "authenticated?", ossl_cipher_is_authenticated, 0);
00963     rb_define_method(cCipher, "key_len=", ossl_cipher_set_key_length, 1);
00964     rb_define_method(cCipher, "key_len", ossl_cipher_key_length, 0);
00965     rb_define_method(cCipher, "iv=", ossl_cipher_set_iv, 1);
00966     rb_define_method(cCipher, "iv_len", ossl_cipher_iv_length, 0);
00967     rb_define_method(cCipher, "block_size", ossl_cipher_block_size, 0);
00968     rb_define_method(cCipher, "padding=", ossl_cipher_set_padding, 1);
00969 }
00970 
00971