Ruby  2.4.2p198(2017-09-14revision59899)
ossl_cipher.c
Go to the documentation of this file.
1 /*
2  * 'OpenSSL for Ruby' project
3  * Copyright (C) 2001-2002 Michal Rokos <m.rokos@sh.cvut.cz>
4  * All rights reserved.
5  */
6 /*
7  * This program is licensed under the same licence as Ruby.
8  * (See the file 'LICENCE'.)
9  */
10 #include "ossl.h"
11 
12 #define NewCipher(klass) \
13  TypedData_Wrap_Struct((klass), &ossl_cipher_type, 0)
14 #define AllocCipher(obj, ctx) do { \
15  (ctx) = EVP_CIPHER_CTX_new(); \
16  if (!(ctx)) \
17  ossl_raise(rb_eRuntimeError, NULL); \
18  RTYPEDDATA_DATA(obj) = (ctx); \
19 } while (0)
20 #define GetCipherInit(obj, ctx) do { \
21  TypedData_Get_Struct((obj), EVP_CIPHER_CTX, &ossl_cipher_type, (ctx)); \
22 } while (0)
23 #define GetCipher(obj, ctx) do { \
24  GetCipherInit((obj), (ctx)); \
25  if (!(ctx)) { \
26  ossl_raise(rb_eRuntimeError, "Cipher not initialized!"); \
27  } \
28 } while (0)
29 #define SafeGetCipher(obj, ctx) do { \
30  OSSL_Check_Kind((obj), cCipher); \
31  GetCipher((obj), (ctx)); \
32 } while (0)
33 
34 /*
35  * Classes
36  */
40 
41 static VALUE ossl_cipher_alloc(VALUE klass);
42 static void ossl_cipher_free(void *ptr);
43 
45  "OpenSSL/Cipher",
46  {
48  },
50 };
51 
52 /*
53  * PUBLIC
54  */
55 const EVP_CIPHER *
57 {
58  if (rb_obj_is_kind_of(obj, cCipher)) {
59  EVP_CIPHER_CTX *ctx;
60 
61  GetCipher(obj, ctx);
62 
63  return EVP_CIPHER_CTX_cipher(ctx);
64  }
65  else {
66  const EVP_CIPHER *cipher;
67 
68  StringValueCStr(obj);
69  cipher = EVP_get_cipherbyname(RSTRING_PTR(obj));
70  if (!cipher)
72  "unsupported cipher algorithm: %"PRIsVALUE, obj);
73 
74  return cipher;
75  }
76 }
77 
78 VALUE
79 ossl_cipher_new(const EVP_CIPHER *cipher)
80 {
81  VALUE ret;
82  EVP_CIPHER_CTX *ctx;
83 
85  AllocCipher(ret, ctx);
86  if (EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, -1) != 1)
88 
89  return ret;
90 }
91 
92 /*
93  * PRIVATE
94  */
95 static void
96 ossl_cipher_free(void *ptr)
97 {
99 }
100 
101 static VALUE
103 {
104  return NewCipher(klass);
105 }
106 
107 /*
108  * call-seq:
109  * Cipher.new(string) -> cipher
110  *
111  * The string must contain a valid cipher name like "AES-128-CBC" or "3DES".
112  *
113  * A list of cipher names is available by calling OpenSSL::Cipher.ciphers.
114  */
115 static VALUE
117 {
118  EVP_CIPHER_CTX *ctx;
119  const EVP_CIPHER *cipher;
120  char *name;
121 
122  name = StringValueCStr(str);
123  GetCipherInit(self, ctx);
124  if (ctx) {
125  ossl_raise(rb_eRuntimeError, "Cipher already initialized!");
126  }
127  AllocCipher(self, ctx);
128  if (!(cipher = EVP_get_cipherbyname(name))) {
129  ossl_raise(rb_eRuntimeError, "unsupported cipher algorithm (%"PRIsVALUE")", str);
130  }
131  if (EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, -1) != 1)
133 
134  return self;
135 }
136 
137 static VALUE
139 {
140  EVP_CIPHER_CTX *ctx1, *ctx2;
141 
142  rb_check_frozen(self);
143  if (self == other) return self;
144 
145  GetCipherInit(self, ctx1);
146  if (!ctx1) {
147  AllocCipher(self, ctx1);
148  }
149  SafeGetCipher(other, ctx2);
150  if (EVP_CIPHER_CTX_copy(ctx1, ctx2) != 1)
152 
153  return self;
154 }
155 
156 static void*
157 add_cipher_name_to_ary(const OBJ_NAME *name, VALUE ary)
158 {
159  rb_ary_push(ary, rb_str_new2(name->name));
160  return NULL;
161 }
162 
163 /*
164  * call-seq:
165  * OpenSSL::Cipher.ciphers -> array[string...]
166  *
167  * Returns the names of all available ciphers in an array.
168  */
169 static VALUE
171 {
172  VALUE ary;
173 
174  ary = rb_ary_new();
175  OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH,
176  (void(*)(const OBJ_NAME*,void*))add_cipher_name_to_ary,
177  (void*)ary);
178 
179  return ary;
180 }
181 
182 /*
183  * call-seq:
184  * cipher.reset -> self
185  *
186  * Fully resets the internal state of the Cipher. By using this, the same
187  * Cipher instance may be used several times for encryption or decryption tasks.
188  *
189  * Internally calls EVP_CipherInit_ex(ctx, NULL, NULL, NULL, NULL, -1).
190  */
191 static VALUE
193 {
194  EVP_CIPHER_CTX *ctx;
195 
196  GetCipher(self, ctx);
197  if (EVP_CipherInit_ex(ctx, NULL, NULL, NULL, NULL, -1) != 1)
199 
200  return self;
201 }
202 
203 static VALUE
204 ossl_cipher_init(int argc, VALUE *argv, VALUE self, int mode)
205 {
206  EVP_CIPHER_CTX *ctx;
207  unsigned char key[EVP_MAX_KEY_LENGTH], *p_key = NULL;
208  unsigned char iv[EVP_MAX_IV_LENGTH], *p_iv = NULL;
209  VALUE pass, init_v;
210 
211  if(rb_scan_args(argc, argv, "02", &pass, &init_v) > 0){
212  /*
213  * oops. this code mistakes salt for IV.
214  * We deprecated the arguments for this method, but we decided
215  * keeping this behaviour for backward compatibility.
216  */
217  VALUE cname = rb_class_path(rb_obj_class(self));
218  rb_warn("arguments for %"PRIsVALUE"#encrypt and %"PRIsVALUE"#decrypt were deprecated; "
219  "use %"PRIsVALUE"#pkcs5_keyivgen to derive key and IV",
220  cname, cname, cname);
221  StringValue(pass);
222  GetCipher(self, ctx);
223  if (NIL_P(init_v)) memcpy(iv, "OpenSSL for Ruby rulez!", sizeof(iv));
224  else{
225  StringValue(init_v);
226  if (EVP_MAX_IV_LENGTH > RSTRING_LEN(init_v)) {
227  memset(iv, 0, EVP_MAX_IV_LENGTH);
228  memcpy(iv, RSTRING_PTR(init_v), RSTRING_LEN(init_v));
229  }
230  else memcpy(iv, RSTRING_PTR(init_v), sizeof(iv));
231  }
232  EVP_BytesToKey(EVP_CIPHER_CTX_cipher(ctx), EVP_md5(), iv,
233  (unsigned char *)RSTRING_PTR(pass), RSTRING_LENINT(pass), 1, key, NULL);
234  p_key = key;
235  p_iv = iv;
236  }
237  else {
238  GetCipher(self, ctx);
239  }
240  if (EVP_CipherInit_ex(ctx, NULL, NULL, p_key, p_iv, mode) != 1) {
242  }
243 
244  if (p_key)
245  rb_ivar_set(self, id_key_set, Qtrue);
246 
247  return self;
248 }
249 
250 /*
251  * call-seq:
252  * cipher.encrypt -> self
253  *
254  * Initializes the Cipher for encryption.
255  *
256  * Make sure to call Cipher#encrypt or Cipher#decrypt before using any of the
257  * following methods:
258  * * [#key=, #iv=, #random_key, #random_iv, #pkcs5_keyivgen]
259  *
260  * Internally calls EVP_CipherInit_ex(ctx, NULL, NULL, NULL, NULL, 1).
261  */
262 static VALUE
264 {
265  return ossl_cipher_init(argc, argv, self, 1);
266 }
267 
268 /*
269  * call-seq:
270  * cipher.decrypt -> self
271  *
272  * Initializes the Cipher for decryption.
273  *
274  * Make sure to call Cipher#encrypt or Cipher#decrypt before using any of the
275  * following methods:
276  * * [#key=, #iv=, #random_key, #random_iv, #pkcs5_keyivgen]
277  *
278  * Internally calls EVP_CipherInit_ex(ctx, NULL, NULL, NULL, NULL, 0).
279  */
280 static VALUE
282 {
283  return ossl_cipher_init(argc, argv, self, 0);
284 }
285 
286 /*
287  * call-seq:
288  * cipher.pkcs5_keyivgen(pass, salt = nil, iterations = 2048, digest = "MD5") -> nil
289  *
290  * Generates and sets the key/IV based on a password.
291  *
292  * *WARNING*: This method is only PKCS5 v1.5 compliant when using RC2, RC4-40,
293  * or DES with MD5 or SHA1. Using anything else (like AES) will generate the
294  * key/iv using an OpenSSL specific method. This method is deprecated and
295  * should no longer be used. Use a PKCS5 v2 key generation method from
296  * OpenSSL::PKCS5 instead.
297  *
298  * === Parameters
299  * * +salt+ must be an 8 byte string if provided.
300  * * +iterations+ is an integer with a default of 2048.
301  * * +digest+ is a Digest object that defaults to 'MD5'
302  *
303  * A minimum of 1000 iterations is recommended.
304  *
305  */
306 static VALUE
308 {
309  EVP_CIPHER_CTX *ctx;
310  const EVP_MD *digest;
311  VALUE vpass, vsalt, viter, vdigest;
312  unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH], *salt = NULL;
313  int iter;
314 
315  rb_scan_args(argc, argv, "13", &vpass, &vsalt, &viter, &vdigest);
316  StringValue(vpass);
317  if(!NIL_P(vsalt)){
318  StringValue(vsalt);
319  if(RSTRING_LEN(vsalt) != PKCS5_SALT_LEN)
320  ossl_raise(eCipherError, "salt must be an 8-octet string");
321  salt = (unsigned char *)RSTRING_PTR(vsalt);
322  }
323  iter = NIL_P(viter) ? 2048 : NUM2INT(viter);
324  digest = NIL_P(vdigest) ? EVP_md5() : GetDigestPtr(vdigest);
325  GetCipher(self, ctx);
326  EVP_BytesToKey(EVP_CIPHER_CTX_cipher(ctx), digest, salt,
327  (unsigned char *)RSTRING_PTR(vpass), RSTRING_LENINT(vpass), iter, key, iv);
328  if (EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, -1) != 1)
330  OPENSSL_cleanse(key, sizeof key);
331  OPENSSL_cleanse(iv, sizeof iv);
332 
333  rb_ivar_set(self, id_key_set, Qtrue);
334 
335  return Qnil;
336 }
337 
338 static int
339 ossl_cipher_update_long(EVP_CIPHER_CTX *ctx, unsigned char *out, long *out_len_ptr,
340  const unsigned char *in, long in_len)
341 {
342  int out_part_len;
343  int limit = INT_MAX / 2 + 1;
344  long out_len = 0;
345 
346  do {
347  int in_part_len = in_len > limit ? limit : (int)in_len;
348 
349  if (!EVP_CipherUpdate(ctx, out ? (out + out_len) : 0,
350  &out_part_len, in, in_part_len))
351  return 0;
352 
353  out_len += out_part_len;
354  in += in_part_len;
355  } while ((in_len -= limit) > 0);
356 
357  if (out_len_ptr)
358  *out_len_ptr = out_len;
359 
360  return 1;
361 }
362 
363 /*
364  * call-seq:
365  * cipher.update(data [, buffer]) -> string or buffer
366  *
367  * Encrypts data in a streaming fashion. Hand consecutive blocks of data
368  * to the +update+ method in order to encrypt it. Returns the encrypted
369  * data chunk. When done, the output of Cipher#final should be additionally
370  * added to the result.
371  *
372  * If +buffer+ is given, the encryption/decryption result will be written to
373  * it. +buffer+ will be resized automatically.
374  */
375 static VALUE
377 {
378  EVP_CIPHER_CTX *ctx;
379  unsigned char *in;
380  long in_len, out_len;
381  VALUE data, str;
382 
383  rb_scan_args(argc, argv, "11", &data, &str);
384 
385  if (!RTEST(rb_attr_get(self, id_key_set)))
386  ossl_raise(eCipherError, "key not set");
387 
388  StringValue(data);
389  in = (unsigned char *)RSTRING_PTR(data);
390  if ((in_len = RSTRING_LEN(data)) == 0)
391  ossl_raise(rb_eArgError, "data must not be empty");
392  GetCipher(self, ctx);
393  out_len = in_len+EVP_CIPHER_CTX_block_size(ctx);
394  if (out_len <= 0) {
396  "data too big to make output buffer: %ld bytes", in_len);
397  }
398 
399  if (NIL_P(str)) {
400  str = rb_str_new(0, out_len);
401  } else {
402  StringValue(str);
403  rb_str_resize(str, out_len);
404  }
405 
406  if (!ossl_cipher_update_long(ctx, (unsigned char *)RSTRING_PTR(str), &out_len, in, in_len))
408  assert(out_len < RSTRING_LEN(str));
409  rb_str_set_len(str, out_len);
410 
411  return str;
412 }
413 
414 /*
415  * call-seq:
416  * cipher.final -> string
417  *
418  * Returns the remaining data held in the cipher object. Further calls to
419  * Cipher#update or Cipher#final will return garbage. This call should always
420  * be made as the last call of an encryption or decryption operation, after
421  * having fed the entire plaintext or ciphertext to the Cipher instance.
422  *
423  * If an authenticated cipher was used, a CipherError is raised if the tag
424  * could not be authenticated successfully. Only call this method after
425  * setting the authentication tag and passing the entire contents of the
426  * ciphertext into the cipher.
427  */
428 static VALUE
430 {
431  EVP_CIPHER_CTX *ctx;
432  int out_len;
433  VALUE str;
434 
435  GetCipher(self, ctx);
436  str = rb_str_new(0, EVP_CIPHER_CTX_block_size(ctx));
437  if (!EVP_CipherFinal_ex(ctx, (unsigned char *)RSTRING_PTR(str), &out_len))
439  assert(out_len <= RSTRING_LEN(str));
440  rb_str_set_len(str, out_len);
441 
442  return str;
443 }
444 
445 /*
446  * call-seq:
447  * cipher.name -> string
448  *
449  * Returns the name of the cipher which may differ slightly from the original
450  * name provided.
451  */
452 static VALUE
454 {
455  EVP_CIPHER_CTX *ctx;
456 
457  GetCipher(self, ctx);
458 
459  return rb_str_new2(EVP_CIPHER_name(EVP_CIPHER_CTX_cipher(ctx)));
460 }
461 
462 /*
463  * call-seq:
464  * cipher.key = string -> string
465  *
466  * Sets the cipher key. To generate a key, you should either use a secure
467  * random byte string or, if the key is to be derived from a password, you
468  * should rely on PBKDF2 functionality provided by OpenSSL::PKCS5. To
469  * generate a secure random-based key, Cipher#random_key may be used.
470  *
471  * Only call this method after calling Cipher#encrypt or Cipher#decrypt.
472  */
473 static VALUE
475 {
476  EVP_CIPHER_CTX *ctx;
477  int key_len;
478 
479  StringValue(key);
480  GetCipher(self, ctx);
481 
482  key_len = EVP_CIPHER_CTX_key_length(ctx);
483  if (RSTRING_LEN(key) != key_len)
484  ossl_raise(rb_eArgError, "key must be %d bytes", key_len);
485 
486  if (EVP_CipherInit_ex(ctx, NULL, NULL, (unsigned char *)RSTRING_PTR(key), NULL, -1) != 1)
488 
489  rb_ivar_set(self, id_key_set, Qtrue);
490 
491  return key;
492 }
493 
494 /*
495  * call-seq:
496  * cipher.iv = string -> string
497  *
498  * Sets the cipher IV. Please note that since you should never be using ECB
499  * mode, an IV is always explicitly required and should be set prior to
500  * encryption. The IV itself can be safely transmitted in public, but it
501  * should be unpredictable to prevent certain kinds of attacks. You may use
502  * Cipher#random_iv to create a secure random IV.
503  *
504  * Only call this method after calling Cipher#encrypt or Cipher#decrypt.
505  */
506 static VALUE
508 {
509  EVP_CIPHER_CTX *ctx;
510  int iv_len = 0;
511 
512  StringValue(iv);
513  GetCipher(self, ctx);
514 
515 #if defined(HAVE_AUTHENTICATED_ENCRYPTION)
516  if (EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_FLAG_AEAD_CIPHER)
517  iv_len = (int)(VALUE)EVP_CIPHER_CTX_get_app_data(ctx);
518 #endif
519  if (!iv_len)
520  iv_len = EVP_CIPHER_CTX_iv_length(ctx);
521  if (RSTRING_LEN(iv) != iv_len)
522  ossl_raise(rb_eArgError, "iv must be %d bytes", iv_len);
523 
524  if (EVP_CipherInit_ex(ctx, NULL, NULL, NULL, (unsigned char *)RSTRING_PTR(iv), -1) != 1)
526 
527  return iv;
528 }
529 
530 /*
531  * call-seq:
532  * cipher.authenticated? -> true | false
533  *
534  * Indicated whether this Cipher instance uses an Authenticated Encryption
535  * mode.
536  */
537 static VALUE
539 {
540  EVP_CIPHER_CTX *ctx;
541 
542  GetCipher(self, ctx);
543 
544 #if defined(HAVE_AUTHENTICATED_ENCRYPTION)
545  return (EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_FLAG_AEAD_CIPHER) ? Qtrue : Qfalse;
546 #else
547  return Qfalse;
548 #endif
549 }
550 
551 #ifdef HAVE_AUTHENTICATED_ENCRYPTION
552 /*
553  * call-seq:
554  * cipher.auth_data = string -> string
555  *
556  * Sets the cipher's additional authenticated data. This field must be
557  * set when using AEAD cipher modes such as GCM or CCM. If no associated
558  * data shall be used, this method must *still* be called with a value of "".
559  * The contents of this field should be non-sensitive data which will be
560  * added to the ciphertext to generate the authentication tag which validates
561  * the contents of the ciphertext.
562  *
563  * The AAD must be set prior to encryption or decryption. In encryption mode,
564  * it must be set after calling Cipher#encrypt and setting Cipher#key= and
565  * Cipher#iv=. When decrypting, the authenticated data must be set after key,
566  * iv and especially *after* the authentication tag has been set. I.e. set it
567  * only after calling Cipher#decrypt, Cipher#key=, Cipher#iv= and
568  * Cipher#auth_tag= first.
569  */
570 static VALUE
572 {
573  EVP_CIPHER_CTX *ctx;
574  unsigned char *in;
575  long in_len, out_len;
576 
577  StringValue(data);
578 
579  in = (unsigned char *) RSTRING_PTR(data);
580  in_len = RSTRING_LEN(data);
581 
582  GetCipher(self, ctx);
583 
584  if (!ossl_cipher_update_long(ctx, NULL, &out_len, in, in_len))
585  ossl_raise(eCipherError, "couldn't set additional authenticated data");
586 
587  return data;
588 }
589 
590 /*
591  * call-seq:
592  * cipher.auth_tag(tag_len = 16) -> String
593  *
594  * Gets the authentication tag generated by Authenticated Encryption Cipher
595  * modes (GCM for example). This tag may be stored along with the ciphertext,
596  * then set on the decryption cipher to authenticate the contents of the
597  * ciphertext against changes. If the optional integer parameter +tag_len+ is
598  * given, the returned tag will be +tag_len+ bytes long. If the parameter is
599  * omitted, the default length of 16 bytes or the length previously set by
600  * #auth_tag_len= will be used. For maximum security, the longest possible
601  * should be chosen.
602  *
603  * The tag may only be retrieved after calling Cipher#final.
604  */
605 static VALUE
607 {
608  VALUE vtag_len, ret;
609  EVP_CIPHER_CTX *ctx;
610  int tag_len = 16;
611 
612  rb_scan_args(argc, argv, "01", &vtag_len);
613  if (NIL_P(vtag_len))
614  vtag_len = rb_attr_get(self, id_auth_tag_len);
615  if (!NIL_P(vtag_len))
616  tag_len = NUM2INT(vtag_len);
617 
618  GetCipher(self, ctx);
619 
620  if (!(EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_FLAG_AEAD_CIPHER))
621  ossl_raise(eCipherError, "authentication tag not supported by this cipher");
622 
623  ret = rb_str_new(NULL, tag_len);
624  if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, tag_len, RSTRING_PTR(ret)))
625  ossl_raise(eCipherError, "retrieving the authentication tag failed");
626 
627  return ret;
628 }
629 
630 /*
631  * call-seq:
632  * cipher.auth_tag = string -> string
633  *
634  * Sets the authentication tag to verify the contents of the
635  * ciphertext. The tag must be set after calling Cipher#decrypt,
636  * Cipher#key= and Cipher#iv=, but before assigning the associated
637  * authenticated data using Cipher#auth_data= and of course, before
638  * decrypting any of the ciphertext. After all decryption is
639  * performed, the tag is verified automatically in the call to
640  * Cipher#final.
641  *
642  * For OCB mode, the tag length must be supplied with #auth_tag_len=
643  * beforehand.
644  */
645 static VALUE
647 {
648  EVP_CIPHER_CTX *ctx;
649  unsigned char *tag;
650  int tag_len;
651 
652  StringValue(vtag);
653  tag = (unsigned char *) RSTRING_PTR(vtag);
654  tag_len = RSTRING_LENINT(vtag);
655 
656  GetCipher(self, ctx);
657  if (!(EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_FLAG_AEAD_CIPHER))
658  ossl_raise(eCipherError, "authentication tag not supported by this cipher");
659 
660  if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, tag_len, tag))
661  ossl_raise(eCipherError, "unable to set AEAD tag");
662 
663  return vtag;
664 }
665 
666 /*
667  * call-seq:
668  * cipher.auth_tag_len = Integer -> Integer
669  *
670  * Sets the length of the authentication tag to be generated or to be given for
671  * AEAD ciphers that requires it as in input parameter. Note that not all AEAD
672  * ciphers support this method.
673  *
674  * In OCB mode, the length must be supplied both when encrypting and when
675  * decrypting, and must be before specifying an IV.
676  */
677 static VALUE
679 {
680  int tag_len = NUM2INT(vlen);
681  EVP_CIPHER_CTX *ctx;
682 
683  GetCipher(self, ctx);
684  if (!(EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_FLAG_AEAD_CIPHER))
685  ossl_raise(eCipherError, "AEAD not supported by this cipher");
686 
687  if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, tag_len, NULL))
688  ossl_raise(eCipherError, "unable to set authentication tag length");
689 
690  /* for #auth_tag */
691  rb_ivar_set(self, id_auth_tag_len, INT2NUM(tag_len));
692 
693  return vlen;
694 }
695 
696 /*
697  * call-seq:
698  * cipher.iv_len = integer -> integer
699  *
700  * Sets the IV/nonce length of the Cipher. Normally block ciphers don't allow
701  * changing the IV length, but some make use of IV for 'nonce'. You may need
702  * this for interoperability with other applications.
703  */
704 static VALUE
705 ossl_cipher_set_iv_length(VALUE self, VALUE iv_length)
706 {
707  int len = NUM2INT(iv_length);
708  EVP_CIPHER_CTX *ctx;
709 
710  GetCipher(self, ctx);
711  if (!(EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_FLAG_AEAD_CIPHER))
712  ossl_raise(eCipherError, "cipher does not support AEAD");
713 
714  if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, len, NULL))
715  ossl_raise(eCipherError, "unable to set IV length");
716 
717  /*
718  * EVP_CIPHER_CTX_iv_length() returns the default length. So we need to save
719  * the length somewhere. Luckily currently we aren't using app_data.
720  */
721  EVP_CIPHER_CTX_set_app_data(ctx, (void *)(VALUE)len);
722 
723  return iv_length;
724 }
725 #else
726 #define ossl_cipher_set_auth_data rb_f_notimplement
727 #define ossl_cipher_get_auth_tag rb_f_notimplement
728 #define ossl_cipher_set_auth_tag rb_f_notimplement
729 #define ossl_cipher_set_auth_tag_len rb_f_notimplement
730 #define ossl_cipher_set_iv_length rb_f_notimplement
731 #endif
732 
733 /*
734  * call-seq:
735  * cipher.key_len = integer -> integer
736  *
737  * Sets the key length of the cipher. If the cipher is a fixed length cipher
738  * then attempting to set the key length to any value other than the fixed
739  * value is an error.
740  *
741  * Under normal circumstances you do not need to call this method (and probably shouldn't).
742  *
743  * See EVP_CIPHER_CTX_set_key_length for further information.
744  */
745 static VALUE
747 {
748  int len = NUM2INT(key_length);
749  EVP_CIPHER_CTX *ctx;
750 
751  GetCipher(self, ctx);
752  if (EVP_CIPHER_CTX_set_key_length(ctx, len) != 1)
754 
755  return key_length;
756 }
757 
758 /*
759  * call-seq:
760  * cipher.padding = integer -> integer
761  *
762  * Enables or disables padding. By default encryption operations are padded using standard block padding and the
763  * padding is checked and removed when decrypting. If the pad parameter is zero then no padding is performed, the
764  * total amount of data encrypted or decrypted must then be a multiple of the block size or an error will occur.
765  *
766  * See EVP_CIPHER_CTX_set_padding for further information.
767  */
768 static VALUE
770 {
771  EVP_CIPHER_CTX *ctx;
772  int pad = NUM2INT(padding);
773 
774  GetCipher(self, ctx);
775  if (EVP_CIPHER_CTX_set_padding(ctx, pad) != 1)
777  return padding;
778 }
779 
780 /*
781  * call-seq:
782  * cipher.key_len -> integer
783  *
784  * Returns the key length in bytes of the Cipher.
785  */
786 static VALUE
788 {
789  EVP_CIPHER_CTX *ctx;
790 
791  GetCipher(self, ctx);
792 
793  return INT2NUM(EVP_CIPHER_CTX_key_length(ctx));
794 }
795 
796 /*
797  * call-seq:
798  * cipher.iv_len -> integer
799  *
800  * Returns the expected length in bytes for an IV for this Cipher.
801  */
802 static VALUE
804 {
805  EVP_CIPHER_CTX *ctx;
806  int len = 0;
807 
808  GetCipher(self, ctx);
809 #if defined(HAVE_AUTHENTICATED_ENCRYPTION)
810  if (EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_FLAG_AEAD_CIPHER)
811  len = (int)(VALUE)EVP_CIPHER_CTX_get_app_data(ctx);
812 #endif
813  if (!len)
814  len = EVP_CIPHER_CTX_iv_length(ctx);
815 
816  return INT2NUM(len);
817 }
818 
819 /*
820  * call-seq:
821  * cipher.block_size -> integer
822  *
823  * Returns the size in bytes of the blocks on which this Cipher operates on.
824  */
825 static VALUE
827 {
828  EVP_CIPHER_CTX *ctx;
829 
830  GetCipher(self, ctx);
831 
832  return INT2NUM(EVP_CIPHER_CTX_block_size(ctx));
833 }
834 
835 /*
836  * INIT
837  */
838 void
840 {
841 #if 0
842  mOSSL = rb_define_module("OpenSSL");
844 #endif
845 
846  /* Document-class: OpenSSL::Cipher
847  *
848  * Provides symmetric algorithms for encryption and decryption. The
849  * algorithms that are available depend on the particular version
850  * of OpenSSL that is installed.
851  *
852  * === Listing all supported algorithms
853  *
854  * A list of supported algorithms can be obtained by
855  *
856  * puts OpenSSL::Cipher.ciphers
857  *
858  * === Instantiating a Cipher
859  *
860  * There are several ways to create a Cipher instance. Generally, a
861  * Cipher algorithm is categorized by its name, the key length in bits
862  * and the cipher mode to be used. The most generic way to create a
863  * Cipher is the following
864  *
865  * cipher = OpenSSL::Cipher.new('<name>-<key length>-<mode>')
866  *
867  * That is, a string consisting of the hyphenated concatenation of the
868  * individual components name, key length and mode. Either all uppercase
869  * or all lowercase strings may be used, for example:
870  *
871  * cipher = OpenSSL::Cipher.new('AES-128-CBC')
872  *
873  * For each algorithm supported, there is a class defined under the
874  * Cipher class that goes by the name of the cipher, e.g. to obtain an
875  * instance of AES, you could also use
876  *
877  * # these are equivalent
878  * cipher = OpenSSL::Cipher::AES.new(128, :CBC)
879  * cipher = OpenSSL::Cipher::AES.new(128, 'CBC')
880  * cipher = OpenSSL::Cipher::AES.new('128-CBC')
881  *
882  * Finally, due to its wide-spread use, there are also extra classes
883  * defined for the different key sizes of AES
884  *
885  * cipher = OpenSSL::Cipher::AES128.new(:CBC)
886  * cipher = OpenSSL::Cipher::AES192.new(:CBC)
887  * cipher = OpenSSL::Cipher::AES256.new(:CBC)
888  *
889  * === Choosing either encryption or decryption mode
890  *
891  * Encryption and decryption are often very similar operations for
892  * symmetric algorithms, this is reflected by not having to choose
893  * different classes for either operation, both can be done using the
894  * same class. Still, after obtaining a Cipher instance, we need to
895  * tell the instance what it is that we intend to do with it, so we
896  * need to call either
897  *
898  * cipher.encrypt
899  *
900  * or
901  *
902  * cipher.decrypt
903  *
904  * on the Cipher instance. This should be the first call after creating
905  * the instance, otherwise configuration that has already been set could
906  * get lost in the process.
907  *
908  * === Choosing a key
909  *
910  * Symmetric encryption requires a key that is the same for the encrypting
911  * and for the decrypting party and after initial key establishment should
912  * be kept as private information. There are a lot of ways to create
913  * insecure keys, the most notable is to simply take a password as the key
914  * without processing the password further. A simple and secure way to
915  * create a key for a particular Cipher is
916  *
917  * cipher = OpenSSL::AES256.new(:CFB)
918  * cipher.encrypt
919  * key = cipher.random_key # also sets the generated key on the Cipher
920  *
921  * If you absolutely need to use passwords as encryption keys, you
922  * should use Password-Based Key Derivation Function 2 (PBKDF2) by
923  * generating the key with the help of the functionality provided by
924  * OpenSSL::PKCS5.pbkdf2_hmac_sha1 or OpenSSL::PKCS5.pbkdf2_hmac.
925  *
926  * Although there is Cipher#pkcs5_keyivgen, its use is deprecated and
927  * it should only be used in legacy applications because it does not use
928  * the newer PKCS#5 v2 algorithms.
929  *
930  * === Choosing an IV
931  *
932  * The cipher modes CBC, CFB, OFB and CTR all need an "initialization
933  * vector", or short, IV. ECB mode is the only mode that does not require
934  * an IV, but there is almost no legitimate use case for this mode
935  * because of the fact that it does not sufficiently hide plaintext
936  * patterns. Therefore
937  *
938  * <b>You should never use ECB mode unless you are absolutely sure that
939  * you absolutely need it</b>
940  *
941  * Because of this, you will end up with a mode that explicitly requires
942  * an IV in any case. Although the IV can be seen as public information,
943  * i.e. it may be transmitted in public once generated, it should still
944  * stay unpredictable to prevent certain kinds of attacks. Therefore,
945  * ideally
946  *
947  * <b>Always create a secure random IV for every encryption of your
948  * Cipher</b>
949  *
950  * A new, random IV should be created for every encryption of data. Think
951  * of the IV as a nonce (number used once) - it's public but random and
952  * unpredictable. A secure random IV can be created as follows
953  *
954  * cipher = ...
955  * cipher.encrypt
956  * key = cipher.random_key
957  * iv = cipher.random_iv # also sets the generated IV on the Cipher
958  *
959  * Although the key is generally a random value, too, it is a bad choice
960  * as an IV. There are elaborate ways how an attacker can take advantage
961  * of such an IV. As a general rule of thumb, exposing the key directly
962  * or indirectly should be avoided at all cost and exceptions only be
963  * made with good reason.
964  *
965  * === Calling Cipher#final
966  *
967  * ECB (which should not be used) and CBC are both block-based modes.
968  * This means that unlike for the other streaming-based modes, they
969  * operate on fixed-size blocks of data, and therefore they require a
970  * "finalization" step to produce or correctly decrypt the last block of
971  * data by appropriately handling some form of padding. Therefore it is
972  * essential to add the output of OpenSSL::Cipher#final to your
973  * encryption/decryption buffer or you will end up with decryption errors
974  * or truncated data.
975  *
976  * Although this is not really necessary for streaming-mode ciphers, it is
977  * still recommended to apply the same pattern of adding the output of
978  * Cipher#final there as well - it also enables you to switch between
979  * modes more easily in the future.
980  *
981  * === Encrypting and decrypting some data
982  *
983  * data = "Very, very confidential data"
984  *
985  * cipher = OpenSSL::Cipher::AES.new(128, :CBC)
986  * cipher.encrypt
987  * key = cipher.random_key
988  * iv = cipher.random_iv
989  *
990  * encrypted = cipher.update(data) + cipher.final
991  * ...
992  * decipher = OpenSSL::Cipher::AES.new(128, :CBC)
993  * decipher.decrypt
994  * decipher.key = key
995  * decipher.iv = iv
996  *
997  * plain = decipher.update(encrypted) + decipher.final
998  *
999  * puts data == plain #=> true
1000  *
1001  * === Authenticated Encryption and Associated Data (AEAD)
1002  *
1003  * If the OpenSSL version used supports it, an Authenticated Encryption
1004  * mode (such as GCM or CCM) should always be preferred over any
1005  * unauthenticated mode. Currently, OpenSSL supports AE only in combination
1006  * with Associated Data (AEAD) where additional associated data is included
1007  * in the encryption process to compute a tag at the end of the encryption.
1008  * This tag will also be used in the decryption process and by verifying
1009  * its validity, the authenticity of a given ciphertext is established.
1010  *
1011  * This is superior to unauthenticated modes in that it allows to detect
1012  * if somebody effectively changed the ciphertext after it had been
1013  * encrypted. This prevents malicious modifications of the ciphertext that
1014  * could otherwise be exploited to modify ciphertexts in ways beneficial to
1015  * potential attackers.
1016  *
1017  * An associated data is used where there is additional information, such as
1018  * headers or some metadata, that must be also authenticated but not
1019  * necessarily need to be encrypted. If no associated data is needed for
1020  * encryption and later decryption, the OpenSSL library still requires a
1021  * value to be set - "" may be used in case none is available.
1022  *
1023  * An example using the GCM (Galois/Counter Mode). You have 16 bytes +key+,
1024  * 12 bytes (96 bits) +nonce+ and the associated data +auth_data+. Be sure
1025  * not to reuse the +key+ and +nonce+ pair. Reusing an nonce ruins the
1026  * security guarantees of GCM mode.
1027  *
1028  * cipher = OpenSSL::Cipher::AES.new(128, :GCM).encrypt
1029  * cipher.key = key
1030  * cipher.iv = nonce
1031  * cipher.auth_data = auth_data
1032  *
1033  * encrypted = cipher.update(data) + cipher.final
1034  * tag = cipher.auth_tag # produces 16 bytes tag by default
1035  *
1036  * Now you are the receiver. You know the +key+ and have received +nonce+,
1037  * +auth_data+, +encrypted+ and +tag+ through an untrusted network. Note
1038  * that GCM accepts an arbitrary length tag between 1 and 16 bytes. You may
1039  * additionally need to check that the received tag has the correct length,
1040  * or you allow attackers to forge a valid single byte tag for the tampered
1041  * ciphertext with a probability of 1/256.
1042  *
1043  * raise "tag is truncated!" unless tag.bytesize == 16
1044  * decipher = OpenSSL::Cipher::AES.new(128, :GCM).decrypt
1045  * decipher.key = key
1046  * decipher.iv = nonce
1047  * decipher.auth_tag = tag
1048  * decipher.auth_data = auth_data
1049  *
1050  * decrypted = decipher.update(encrypted) + decipher.final
1051  *
1052  * puts data == decrypted #=> true
1053  */
1056 
1060  rb_define_method(cCipher, "initialize", ossl_cipher_initialize, 1);
1062  rb_define_method(cCipher, "encrypt", ossl_cipher_encrypt, -1);
1063  rb_define_method(cCipher, "decrypt", ossl_cipher_decrypt, -1);
1064  rb_define_method(cCipher, "pkcs5_keyivgen", ossl_cipher_pkcs5_keyivgen, -1);
1073  rb_define_method(cCipher, "authenticated?", ossl_cipher_is_authenticated, 0);
1079  rb_define_method(cCipher, "block_size", ossl_cipher_block_size, 0);
1081 
1082  id_auth_tag_len = rb_intern_const("auth_tag_len");
1083  id_key_set = rb_intern_const("key_set");
1084 }
static VALUE ossl_s_ciphers(VALUE self)
Definition: ossl_cipher.c:170
static const rb_data_type_t ossl_cipher_type
Definition: ossl_cipher.c:44
static VALUE ossl_cipher_alloc(VALUE klass)
Definition: ossl_cipher.c:102
VALUE rb_eStandardError
Definition: error.c:760
#define ossl_cipher_set_auth_data
Definition: ossl_cipher.c:726
VALUE mOSSL
Definition: ossl.c:213
#define EVP_CIPHER_CTX_copy
static VALUE ossl_cipher_final(VALUE self)
Definition: ossl_cipher.c:429
#define RUBY_TYPED_FREE_IMMEDIATELY
Definition: ruby.h:1145
#define INT2NUM(x)
Definition: ruby.h:1538
#define NUM2INT(x)
Definition: ruby.h:684
static VALUE ossl_cipher_init(int argc, VALUE *argv, VALUE self, int mode)
Definition: ossl_cipher.c:204
#define Qtrue
Definition: ruby.h:437
#define AllocCipher(obj, ctx)
Definition: ossl_cipher.c:14
#define ossl_cipher_set_iv_length
Definition: ossl_cipher.c:730
VALUE rb_ary_push(VALUE ary, VALUE item)
Definition: array.c:905
static VALUE ossl_cipher_update(int argc, VALUE *argv, VALUE self)
Definition: ossl_cipher.c:376
void rb_str_set_len(VALUE, long)
Definition: string.c:2545
static void * add_cipher_name_to_ary(const OBJ_NAME *name, VALUE ary)
Definition: ossl_cipher.c:157
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition: class.c:693
void rb_define_alloc_func(VALUE, rb_alloc_func_t)
VALUE rb_obj_is_kind_of(VALUE, VALUE)
Definition: object.c:690
static VALUE ossl_cipher_block_size(VALUE self)
Definition: ossl_cipher.c:826
#define assert(x)
Definition: dlmalloc.c:1176
#define GetCipher(obj, ctx)
Definition: ossl_cipher.c:23
VALUE rb_eRangeError
Definition: error.c:766
#define EVP_CIPHER_CTX_free
static VALUE ossl_cipher_set_key_length(VALUE self, VALUE key_length)
Definition: ossl_cipher.c:746
static void ossl_cipher_free(void *ptr)
Definition: ossl_cipher.c:96
#define rb_define_copy_func(klass, func)
Definition: ruby_missing.h:13
static VALUE ossl_cipher_initialize(VALUE self, VALUE str)
Definition: ossl_cipher.c:116
VALUE ossl_cipher_new(const EVP_CIPHER *cipher)
Definition: ossl_cipher.c:79
VALUE eCipherError
Definition: ossl_cipher.c:38
#define SafeGetCipher(obj, ctx)
Definition: ossl_cipher.c:29
RUBY_EXTERN VALUE rb_cObject
Definition: ruby.h:1872
VALUE rb_eRuntimeError
Definition: error.c:761
#define ossl_cipher_get_auth_tag
Definition: ossl_cipher.c:727
VALUE rb_ary_new(void)
Definition: array.c:493
#define NIL_P(v)
Definition: ruby.h:451
const EVP_MD * GetDigestPtr(VALUE obj)
Definition: ossl_digest.c:49
VALUE eOSSLError
Definition: ossl.c:218
int argc
Definition: ruby.c:183
#define Qfalse
Definition: ruby.h:436
#define rb_str_new2
Definition: intern.h:857
const EVP_CIPHER * GetCipherPtr(VALUE obj)
Definition: ossl_cipher.c:56
static ID id_key_set
Definition: ossl_cipher.c:39
VALUE rb_str_resize(VALUE, long)
Definition: string.c:2562
#define RSTRING_LEN(str)
Definition: ruby.h:978
void rb_define_module_function(VALUE module, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a module function for module.
Definition: class.c:1731
static VALUE ossl_cipher_encrypt(int argc, VALUE *argv, VALUE self)
Definition: ossl_cipher.c:263
static int ossl_cipher_update_long(EVP_CIPHER_CTX *ctx, unsigned char *out, long *out_len_ptr, const unsigned char *in, long in_len)
Definition: ossl_cipher.c:339
VALUE rb_class_path(VALUE)
Definition: variable.c:294
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Definition: class.c:1919
VALUE rb_ivar_set(VALUE, ID, VALUE)
Definition: variable.c:1364
#define PRIsVALUE
Definition: ruby.h:135
#define NewCipher(klass)
Definition: ossl_cipher.c:12
unsigned long ID
Definition: ruby.h:86
static VALUE ossl_cipher_copy(VALUE self, VALUE other)
Definition: ossl_cipher.c:138
#define Qnil
Definition: ruby.h:438
#define ossl_cipher_set_auth_tag_len
Definition: ossl_cipher.c:729
static VALUE ossl_cipher_decrypt(int argc, VALUE *argv, VALUE self)
Definition: ossl_cipher.c:281
static VALUE ossl_cipher_key_length(VALUE self)
Definition: ossl_cipher.c:787
unsigned long VALUE
Definition: ruby.h:85
#define ossl_cipher_set_auth_tag
Definition: ossl_cipher.c:728
#define GetCipherInit(obj, ctx)
Definition: ossl_cipher.c:20
register unsigned int len
Definition: zonetab.h:51
#define StringValueCStr(v)
Definition: ruby.h:571
static VALUE ossl_cipher_pkcs5_keyivgen(int argc, VALUE *argv, VALUE self)
Definition: ossl_cipher.c:307
#define RSTRING_PTR(str)
Definition: ruby.h:982
#define RTEST(v)
Definition: ruby.h:450
void ossl_raise(VALUE exc, const char *fmt,...)
Definition: ossl.c:278
static VALUE ossl_cipher_reset(VALUE self)
Definition: ossl_cipher.c:192
const char * name
Definition: nkf.c:208
void Init_ossl_cipher(void)
Definition: ossl_cipher.c:839
static VALUE ossl_cipher_set_padding(VALUE self, VALUE padding)
Definition: ossl_cipher.c:769
#define RSTRING_LENINT(str)
Definition: ruby.h:990
#define rb_check_frozen(obj)
Definition: intern.h:276
static VALUE ossl_cipher_iv_length(VALUE self)
Definition: ossl_cipher.c:803
#define rb_intern_const(str)
Definition: ruby.h:1756
#define memcpy(d, s, n)
Definition: ffi_common.h:55
VALUE rb_define_module(const char *name)
Definition: class.c:768
VALUE cCipher
Definition: ossl_cipher.c:37
static VALUE ossl_cipher_set_key(VALUE self, VALUE key)
Definition: ossl_cipher.c:474
static VALUE ossl_cipher_name(VALUE self)
Definition: ossl_cipher.c:453
#define NULL
Definition: _sdbm.c:102
void rb_define_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Definition: class.c:1515
void rb_warn(const char *fmt,...)
Definition: error.c:221
static VALUE ossl_cipher_is_authenticated(VALUE self)
Definition: ossl_cipher.c:538
static VALUE ossl_cipher_set_iv(VALUE self, VALUE iv)
Definition: ossl_cipher.c:507
VALUE rb_eArgError
Definition: error.c:763
VALUE rb_attr_get(VALUE, ID)
Definition: variable.c:1273
static ID id_auth_tag_len
Definition: ossl_cipher.c:39
char ** argv
Definition: ruby.c:184
#define StringValue(v)
Definition: ruby.h:569
VALUE rb_str_new(const char *, long)
Definition: string.c:736
VALUE rb_obj_class(VALUE)
Definition: object.c:229