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