Ruby 2.7.0p0(2019-12-25revision647ee6f091eafcce70ffb75ddf7e121e192ab217)

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 */
33 VALUE cCipher;
34 VALUE eCipherError;
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 },
45 0, 0, RUBY_TYPED_FREE_IMMEDIATELY,
46 };
47
48 /*
49 * PUBLIC
50 */
51 const EVP_CIPHER *
52 ossl_evp_get_cipherbyname(VALUE obj)
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)
67 ossl_raise(rb_eArgError,
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)
83 ossl_raise(eCipherError, NULL);
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)
128 ossl_raise(eCipherError, NULL);
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)
147 ossl_raise(eCipherError, NULL);
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)
194 ossl_raise(eCipherError, NULL);
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) {
237 ossl_raise(eCipherError, NULL);
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 if (iter <= 0)
321 rb_raise(rb_eArgError, "iterations must be a positive integer");
322 digest = NIL_P(vdigest) ? EVP_md5() : ossl_evp_get_digestbyname(vdigest);
323 GetCipher(self, ctx);
324 EVP_BytesToKey(EVP_CIPHER_CTX_cipher(ctx), digest, salt,
325 (unsigned char *)RSTRING_PTR(vpass), RSTRING_LENINT(vpass), iter, key, iv);
326 if (EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, -1) != 1)
327 ossl_raise(eCipherError, NULL);
328 OPENSSL_cleanse(key, sizeof key);
329 OPENSSL_cleanse(iv, sizeof iv);
330
331 rb_ivar_set(self, id_key_set, Qtrue);
332
333 return Qnil;
334 }
335
336 static int
337 ossl_cipher_update_long(EVP_CIPHER_CTX *ctx, unsigned char *out, long *out_len_ptr,
338 const unsigned char *in, long in_len)
339 {
340 int out_part_len;
341 int limit = INT_MAX / 2 + 1;
342 long out_len = 0;
343
344 do {
345 int in_part_len = in_len > limit ? limit : (int)in_len;
346
347 if (!EVP_CipherUpdate(ctx, out ? (out + out_len) : 0,
348 &out_part_len, in, in_part_len))
349 return 0;
350
351 out_len += out_part_len;
352 in += in_part_len;
353 } while ((in_len -= limit) > 0);
354
355 if (out_len_ptr)
356 *out_len_ptr = out_len;
357
358 return 1;
359 }
360
361 /*
362 * call-seq:
363 * cipher.update(data [, buffer]) -> string or buffer
364 *
365 * Encrypts data in a streaming fashion. Hand consecutive blocks of data
366 * to the #update method in order to encrypt it. Returns the encrypted
367 * data chunk. When done, the output of Cipher#final should be additionally
368 * added to the result.
369 *
370 * If _buffer_ is given, the encryption/decryption result will be written to
371 * it. _buffer_ will be resized automatically.
372 */
373 static VALUE
374 ossl_cipher_update(int argc, VALUE *argv, VALUE self)
375 {
376 EVP_CIPHER_CTX *ctx;
377 unsigned char *in;
378 long in_len, out_len;
379 VALUE data, str;
380
381 rb_scan_args(argc, argv, "11", &data, &str);
382
383 if (!RTEST(rb_attr_get(self, id_key_set)))
384 ossl_raise(eCipherError, "key not set");
385
386 StringValue(data);
387 in = (unsigned char *)RSTRING_PTR(data);
388 if ((in_len = RSTRING_LEN(data)) == 0)
389 ossl_raise(rb_eArgError, "data must not be empty");
390 GetCipher(self, ctx);
391 out_len = in_len+EVP_CIPHER_CTX_block_size(ctx);
392 if (out_len <= 0) {
393 ossl_raise(rb_eRangeError,
394 "data too big to make output buffer: %ld bytes", in_len);
395 }
396
397 if (NIL_P(str)) {
398 str = rb_str_new(0, out_len);
399 } else {
400 StringValue(str);
401 rb_str_resize(str, out_len);
402 }
403
404 if (!ossl_cipher_update_long(ctx, (unsigned char *)RSTRING_PTR(str), &out_len, in, in_len))
405 ossl_raise(eCipherError, NULL);
406 assert(out_len < RSTRING_LEN(str));
407 rb_str_set_len(str, out_len);
408
409 return str;
410 }
411
412 /*
413 * call-seq:
414 * cipher.final -> string
415 *
416 * Returns the remaining data held in the cipher object. Further calls to
417 * Cipher#update or Cipher#final will return garbage. This call should always
418 * be made as the last call of an encryption or decryption operation, after
419 * having fed the entire plaintext or ciphertext to the Cipher instance.
420 *
421 * If an authenticated cipher was used, a CipherError is raised if the tag
422 * could not be authenticated successfully. Only call this method after
423 * setting the authentication tag and passing the entire contents of the
424 * ciphertext into the cipher.
425 */
426 static VALUE
427 ossl_cipher_final(VALUE self)
428 {
429 EVP_CIPHER_CTX *ctx;
430 int out_len;
431 VALUE str;
432
433 GetCipher(self, ctx);
434 str = rb_str_new(0, EVP_CIPHER_CTX_block_size(ctx));
435 if (!EVP_CipherFinal_ex(ctx, (unsigned char *)RSTRING_PTR(str), &out_len))
436 ossl_raise(eCipherError, NULL);
437 assert(out_len <= RSTRING_LEN(str));
438 rb_str_set_len(str, out_len);
439
440 return str;
441 }
442
443 /*
444 * call-seq:
445 * cipher.name -> string
446 *
447 * Returns the name of the cipher which may differ slightly from the original
448 * name provided.
449 */
450 static VALUE
451 ossl_cipher_name(VALUE self)
452 {
453 EVP_CIPHER_CTX *ctx;
454
455 GetCipher(self, ctx);
456
457 return rb_str_new2(EVP_CIPHER_name(EVP_CIPHER_CTX_cipher(ctx)));
458 }
459
460 /*
461 * call-seq:
462 * cipher.key = string -> string
463 *
464 * Sets the cipher key. To generate a key, you should either use a secure
465 * random byte string or, if the key is to be derived from a password, you
466 * should rely on PBKDF2 functionality provided by OpenSSL::PKCS5. To
467 * generate a secure random-based key, Cipher#random_key may be used.
468 *
469 * Only call this method after calling Cipher#encrypt or Cipher#decrypt.
470 */
471 static VALUE
472 ossl_cipher_set_key(VALUE self, VALUE key)
473 {
474 EVP_CIPHER_CTX *ctx;
475 int key_len;
476
477 StringValue(key);
478 GetCipher(self, ctx);
479
480 key_len = EVP_CIPHER_CTX_key_length(ctx);
481 if (RSTRING_LEN(key) != key_len)
482 ossl_raise(rb_eArgError, "key must be %d bytes", key_len);
483
484 if (EVP_CipherInit_ex(ctx, NULL, NULL, (unsigned char *)RSTRING_PTR(key), NULL, -1) != 1)
485 ossl_raise(eCipherError, NULL);
486
487 rb_ivar_set(self, id_key_set, Qtrue);
488
489 return key;
490 }
491
492 /*
493 * call-seq:
494 * cipher.iv = string -> string
495 *
496 * Sets the cipher IV. Please note that since you should never be using ECB
497 * mode, an IV is always explicitly required and should be set prior to
498 * encryption. The IV itself can be safely transmitted in public, but it
499 * should be unpredictable to prevent certain kinds of attacks. You may use
500 * Cipher#random_iv to create a secure random IV.
501 *
502 * Only call this method after calling Cipher#encrypt or Cipher#decrypt.
503 */
504 static VALUE
505 ossl_cipher_set_iv(VALUE self, VALUE iv)
506 {
507 EVP_CIPHER_CTX *ctx;
508 int iv_len = 0;
509
510 StringValue(iv);
511 GetCipher(self, ctx);
512
513 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ctx)) & EVP_CIPH_FLAG_AEAD_CIPHER)
514 iv_len = (int)(VALUE)EVP_CIPHER_CTX_get_app_data(ctx);
515 if (!iv_len)
516 iv_len = EVP_CIPHER_CTX_iv_length(ctx);
517 if (RSTRING_LEN(iv) != iv_len)
518 ossl_raise(rb_eArgError, "iv must be %d bytes", iv_len);
519
520 if (EVP_CipherInit_ex(ctx, NULL, NULL, NULL, (unsigned char *)RSTRING_PTR(iv), -1) != 1)
521 ossl_raise(eCipherError, NULL);
522
523 return iv;
524 }
525
526 /*
527 * call-seq:
528 * cipher.authenticated? -> true | false
529 *
530 * Indicated whether this Cipher instance uses an Authenticated Encryption
531 * mode.
532 */
533 static VALUE
534 ossl_cipher_is_authenticated(VALUE self)
535 {
536 EVP_CIPHER_CTX *ctx;
537
538 GetCipher(self, ctx);
539
540 return (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ctx)) & EVP_CIPH_FLAG_AEAD_CIPHER) ? Qtrue : Qfalse;
541 }
542
543 /*
544 * call-seq:
545 * cipher.auth_data = string -> string
546 *
547 * Sets the cipher's additional authenticated data. This field must be
548 * set when using AEAD cipher modes such as GCM or CCM. If no associated
549 * data shall be used, this method must *still* be called with a value of "".
550 * The contents of this field should be non-sensitive data which will be
551 * added to the ciphertext to generate the authentication tag which validates
552 * the contents of the ciphertext.
553 *
554 * The AAD must be set prior to encryption or decryption. In encryption mode,
555 * it must be set after calling Cipher#encrypt and setting Cipher#key= and
556 * Cipher#iv=. When decrypting, the authenticated data must be set after key,
557 * iv and especially *after* the authentication tag has been set. I.e. set it
558 * only after calling Cipher#decrypt, Cipher#key=, Cipher#iv= and
559 * Cipher#auth_tag= first.
560 */
561 static VALUE
562 ossl_cipher_set_auth_data(VALUE self, VALUE data)
563 {
564 EVP_CIPHER_CTX *ctx;
565 unsigned char *in;
566 long in_len, out_len;
567
568 StringValue(data);
569
570 in = (unsigned char *) RSTRING_PTR(data);
571 in_len = RSTRING_LEN(data);
572
573 GetCipher(self, ctx);
574 if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ctx)) & EVP_CIPH_FLAG_AEAD_CIPHER))
575 ossl_raise(eCipherError, "AEAD not supported by this cipher");
576
577 if (!ossl_cipher_update_long(ctx, NULL, &out_len, in, in_len))
578 ossl_raise(eCipherError, "couldn't set additional authenticated data");
579
580 return data;
581 }
582
583 /*
584 * call-seq:
585 * cipher.auth_tag(tag_len = 16) -> String
586 *
587 * Gets the authentication tag generated by Authenticated Encryption Cipher
588 * modes (GCM for example). This tag may be stored along with the ciphertext,
589 * then set on the decryption cipher to authenticate the contents of the
590 * ciphertext against changes. If the optional integer parameter _tag_len_ is
591 * given, the returned tag will be _tag_len_ bytes long. If the parameter is
592 * omitted, the default length of 16 bytes or the length previously set by
593 * #auth_tag_len= will be used. For maximum security, the longest possible
594 * should be chosen.
595 *
596 * The tag may only be retrieved after calling Cipher#final.
597 */
598 static VALUE
599 ossl_cipher_get_auth_tag(int argc, VALUE *argv, VALUE self)
600 {
601 VALUE vtag_len, ret;
602 EVP_CIPHER_CTX *ctx;
603 int tag_len = 16;
604
605 rb_scan_args(argc, argv, "01", &vtag_len);
606 if (NIL_P(vtag_len))
607 vtag_len = rb_attr_get(self, id_auth_tag_len);
608 if (!NIL_P(vtag_len))
609 tag_len = NUM2INT(vtag_len);
610
611 GetCipher(self, ctx);
612
613 if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ctx)) & EVP_CIPH_FLAG_AEAD_CIPHER))
614 ossl_raise(eCipherError, "authentication tag not supported by this cipher");
615
616 ret = rb_str_new(NULL, tag_len);
617 if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, tag_len, RSTRING_PTR(ret)))
618 ossl_raise(eCipherError, "retrieving the authentication tag failed");
619
620 return ret;
621 }
622
623 /*
624 * call-seq:
625 * cipher.auth_tag = string -> string
626 *
627 * Sets the authentication tag to verify the integrity of the ciphertext.
628 * This can be called only when the cipher supports AE. The tag must be set
629 * after calling Cipher#decrypt, Cipher#key= and Cipher#iv=, but before
630 * calling Cipher#final. After all decryption is performed, the tag is
631 * verified automatically in the call to Cipher#final.
632 *
633 * For OCB mode, the tag length must be supplied with #auth_tag_len=
634 * beforehand.
635 */
636 static VALUE
637 ossl_cipher_set_auth_tag(VALUE self, VALUE vtag)
638 {
639 EVP_CIPHER_CTX *ctx;
640 unsigned char *tag;
641 int tag_len;
642
643 StringValue(vtag);
644 tag = (unsigned char *) RSTRING_PTR(vtag);
645 tag_len = RSTRING_LENINT(vtag);
646
647 GetCipher(self, ctx);
648 if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ctx)) & EVP_CIPH_FLAG_AEAD_CIPHER))
649 ossl_raise(eCipherError, "authentication tag not supported by this cipher");
650
651 if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, tag_len, tag))
652 ossl_raise(eCipherError, "unable to set AEAD tag");
653
654 return vtag;
655 }
656
657 /*
658 * call-seq:
659 * cipher.auth_tag_len = Integer -> Integer
660 *
661 * Sets the length of the authentication tag to be generated or to be given for
662 * AEAD ciphers that requires it as in input parameter. Note that not all AEAD
663 * ciphers support this method.
664 *
665 * In OCB mode, the length must be supplied both when encrypting and when
666 * decrypting, and must be before specifying an IV.
667 */
668 static VALUE
669 ossl_cipher_set_auth_tag_len(VALUE self, VALUE vlen)
670 {
671 int tag_len = NUM2INT(vlen);
672 EVP_CIPHER_CTX *ctx;
673
674 GetCipher(self, ctx);
675 if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ctx)) & EVP_CIPH_FLAG_AEAD_CIPHER))
676 ossl_raise(eCipherError, "AEAD not supported by this cipher");
677
678 if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, tag_len, NULL))
679 ossl_raise(eCipherError, "unable to set authentication tag length");
680
681 /* for #auth_tag */
682 rb_ivar_set(self, id_auth_tag_len, INT2NUM(tag_len));
683
684 return vlen;
685 }
686
687 /*
688 * call-seq:
689 * cipher.iv_len = integer -> integer
690 *
691 * Sets the IV/nonce length of the Cipher. Normally block ciphers don't allow
692 * changing the IV length, but some make use of IV for 'nonce'. You may need
693 * this for interoperability with other applications.
694 */
695 static VALUE
696 ossl_cipher_set_iv_length(VALUE self, VALUE iv_length)
697 {
698 int len = NUM2INT(iv_length);
699 EVP_CIPHER_CTX *ctx;
700
701 GetCipher(self, ctx);
702 if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ctx)) & EVP_CIPH_FLAG_AEAD_CIPHER))
703 ossl_raise(eCipherError, "cipher does not support AEAD");
704
705 if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, len, NULL))
706 ossl_raise(eCipherError, "unable to set IV length");
707
708 /*
709 * EVP_CIPHER_CTX_iv_length() returns the default length. So we need to save
710 * the length somewhere. Luckily currently we aren't using app_data.
711 */
712 EVP_CIPHER_CTX_set_app_data(ctx, (void *)(VALUE)len);
713
714 return iv_length;
715 }
716
717 /*
718 * call-seq:
719 * cipher.key_len = integer -> integer
720 *
721 * Sets the key length of the cipher. If the cipher is a fixed length cipher
722 * then attempting to set the key length to any value other than the fixed
723 * value is an error.
724 *
725 * Under normal circumstances you do not need to call this method (and probably shouldn't).
726 *
727 * See EVP_CIPHER_CTX_set_key_length for further information.
728 */
729 static VALUE
730 ossl_cipher_set_key_length(VALUE self, VALUE key_length)
731 {
732 int len = NUM2INT(key_length);
733 EVP_CIPHER_CTX *ctx;
734
735 GetCipher(self, ctx);
736 if (EVP_CIPHER_CTX_set_key_length(ctx, len) != 1)
737 ossl_raise(eCipherError, NULL);
738
739 return key_length;
740 }
741
742 /*
743 * call-seq:
744 * cipher.padding = integer -> integer
745 *
746 * Enables or disables padding. By default encryption operations are padded using standard block padding and the
747 * padding is checked and removed when decrypting. If the pad parameter is zero then no padding is performed, the
748 * total amount of data encrypted or decrypted must then be a multiple of the block size or an error will occur.
749 *
750 * See EVP_CIPHER_CTX_set_padding for further information.
751 */
752 static VALUE
753 ossl_cipher_set_padding(VALUE self, VALUE padding)
754 {
755 EVP_CIPHER_CTX *ctx;
756 int pad = NUM2INT(padding);
757
758 GetCipher(self, ctx);
759 if (EVP_CIPHER_CTX_set_padding(ctx, pad) != 1)
760 ossl_raise(eCipherError, NULL);
761 return padding;
762 }
763
764 /*
765 * call-seq:
766 * cipher.key_len -> integer
767 *
768 * Returns the key length in bytes of the Cipher.
769 */
770 static VALUE
771 ossl_cipher_key_length(VALUE self)
772 {
773 EVP_CIPHER_CTX *ctx;
774
775 GetCipher(self, ctx);
776
777 return INT2NUM(EVP_CIPHER_CTX_key_length(ctx));
778 }
779
780 /*
781 * call-seq:
782 * cipher.iv_len -> integer
783 *
784 * Returns the expected length in bytes for an IV for this Cipher.
785 */
786 static VALUE
787 ossl_cipher_iv_length(VALUE self)
788 {
789 EVP_CIPHER_CTX *ctx;
790 int len = 0;
791
792 GetCipher(self, ctx);
793 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ctx)) & EVP_CIPH_FLAG_AEAD_CIPHER)
794 len = (int)(VALUE)EVP_CIPHER_CTX_get_app_data(ctx);
795 if (!len)
796 len = EVP_CIPHER_CTX_iv_length(ctx);
797
798 return INT2NUM(len);
799 }
800
801 /*
802 * call-seq:
803 * cipher.block_size -> integer
804 *
805 * Returns the size in bytes of the blocks on which this Cipher operates on.
806 */
807 static VALUE
808 ossl_cipher_block_size(VALUE self)
809 {
810 EVP_CIPHER_CTX *ctx;
811
812 GetCipher(self, ctx);
813
814 return INT2NUM(EVP_CIPHER_CTX_block_size(ctx));
815 }
816
817 /*
818 * INIT
819 */
820 void
821 Init_ossl_cipher(void)
822 {
823 #if 0
824 mOSSL = rb_define_module("OpenSSL");
825 eOSSLError = rb_define_class_under(mOSSL, "OpenSSLError", rb_eStandardError);
826 #endif
827
828 /* Document-class: OpenSSL::Cipher
829 *
830 * Provides symmetric algorithms for encryption and decryption. The
831 * algorithms that are available depend on the particular version
832 * of OpenSSL that is installed.
833 *
834 * === Listing all supported algorithms
835 *
836 * A list of supported algorithms can be obtained by
837 *
838 * puts OpenSSL::Cipher.ciphers
839 *
840 * === Instantiating a Cipher
841 *
842 * There are several ways to create a Cipher instance. Generally, a
843 * Cipher algorithm is categorized by its name, the key length in bits
844 * and the cipher mode to be used. The most generic way to create a
845 * Cipher is the following
846 *
847 * cipher = OpenSSL::Cipher.new('<name>-<key length>-<mode>')
848 *
849 * That is, a string consisting of the hyphenated concatenation of the
850 * individual components name, key length and mode. Either all uppercase
851 * or all lowercase strings may be used, for example:
852 *
853 * cipher = OpenSSL::Cipher.new('AES-128-CBC')
854 *
855 * For each algorithm supported, there is a class defined under the
856 * Cipher class that goes by the name of the cipher, e.g. to obtain an
857 * instance of AES, you could also use
858 *
859 * # these are equivalent
860 * cipher = OpenSSL::Cipher::AES.new(128, :CBC)
861 * cipher = OpenSSL::Cipher::AES.new(128, 'CBC')
862 * cipher = OpenSSL::Cipher::AES.new('128-CBC')
863 *
864 * Finally, due to its wide-spread use, there are also extra classes
865 * defined for the different key sizes of AES
866 *
867 * cipher = OpenSSL::Cipher::AES128.new(:CBC)
868 * cipher = OpenSSL::Cipher::AES192.new(:CBC)
869 * cipher = OpenSSL::Cipher::AES256.new(:CBC)
870 *
871 * === Choosing either encryption or decryption mode
872 *
873 * Encryption and decryption are often very similar operations for
874 * symmetric algorithms, this is reflected by not having to choose
875 * different classes for either operation, both can be done using the
876 * same class. Still, after obtaining a Cipher instance, we need to
877 * tell the instance what it is that we intend to do with it, so we
878 * need to call either
879 *
880 * cipher.encrypt
881 *
882 * or
883 *
884 * cipher.decrypt
885 *
886 * on the Cipher instance. This should be the first call after creating
887 * the instance, otherwise configuration that has already been set could
888 * get lost in the process.
889 *
890 * === Choosing a key
891 *
892 * Symmetric encryption requires a key that is the same for the encrypting
893 * and for the decrypting party and after initial key establishment should
894 * be kept as private information. There are a lot of ways to create
895 * insecure keys, the most notable is to simply take a password as the key
896 * without processing the password further. A simple and secure way to
897 * create a key for a particular Cipher is
898 *
899 * cipher = OpenSSL::AES256.new(:CFB)
900 * cipher.encrypt
901 * key = cipher.random_key # also sets the generated key on the Cipher
902 *
903 * If you absolutely need to use passwords as encryption keys, you
904 * should use Password-Based Key Derivation Function 2 (PBKDF2) by
905 * generating the key with the help of the functionality provided by
906 * OpenSSL::PKCS5.pbkdf2_hmac_sha1 or OpenSSL::PKCS5.pbkdf2_hmac.
907 *
908 * Although there is Cipher#pkcs5_keyivgen, its use is deprecated and
909 * it should only be used in legacy applications because it does not use
910 * the newer PKCS#5 v2 algorithms.
911 *
912 * === Choosing an IV
913 *
914 * The cipher modes CBC, CFB, OFB and CTR all need an "initialization
915 * vector", or short, IV. ECB mode is the only mode that does not require
916 * an IV, but there is almost no legitimate use case for this mode
917 * because of the fact that it does not sufficiently hide plaintext
918 * patterns. Therefore
919 *
920 * <b>You should never use ECB mode unless you are absolutely sure that
921 * you absolutely need it</b>
922 *
923 * Because of this, you will end up with a mode that explicitly requires
924 * an IV in any case. Although the IV can be seen as public information,
925 * i.e. it may be transmitted in public once generated, it should still
926 * stay unpredictable to prevent certain kinds of attacks. Therefore,
927 * ideally
928 *
929 * <b>Always create a secure random IV for every encryption of your
930 * Cipher</b>
931 *
932 * A new, random IV should be created for every encryption of data. Think
933 * of the IV as a nonce (number used once) - it's public but random and
934 * unpredictable. A secure random IV can be created as follows
935 *
936 * cipher = ...
937 * cipher.encrypt
938 * key = cipher.random_key
939 * iv = cipher.random_iv # also sets the generated IV on the Cipher
940 *
941 * Although the key is generally a random value, too, it is a bad choice
942 * as an IV. There are elaborate ways how an attacker can take advantage
943 * of such an IV. As a general rule of thumb, exposing the key directly
944 * or indirectly should be avoided at all cost and exceptions only be
945 * made with good reason.
946 *
947 * === Calling Cipher#final
948 *
949 * ECB (which should not be used) and CBC are both block-based modes.
950 * This means that unlike for the other streaming-based modes, they
951 * operate on fixed-size blocks of data, and therefore they require a
952 * "finalization" step to produce or correctly decrypt the last block of
953 * data by appropriately handling some form of padding. Therefore it is
954 * essential to add the output of OpenSSL::Cipher#final to your
955 * encryption/decryption buffer or you will end up with decryption errors
956 * or truncated data.
957 *
958 * Although this is not really necessary for streaming-mode ciphers, it is
959 * still recommended to apply the same pattern of adding the output of
960 * Cipher#final there as well - it also enables you to switch between
961 * modes more easily in the future.
962 *
963 * === Encrypting and decrypting some data
964 *
965 * data = "Very, very confidential data"
966 *
967 * cipher = OpenSSL::Cipher::AES.new(128, :CBC)
968 * cipher.encrypt
969 * key = cipher.random_key
970 * iv = cipher.random_iv
971 *
972 * encrypted = cipher.update(data) + cipher.final
973 * ...
974 * decipher = OpenSSL::Cipher::AES.new(128, :CBC)
975 * decipher.decrypt
976 * decipher.key = key
977 * decipher.iv = iv
978 *
979 * plain = decipher.update(encrypted) + decipher.final
980 *
981 * puts data == plain #=> true
982 *
983 * === Authenticated Encryption and Associated Data (AEAD)
984 *
985 * If the OpenSSL version used supports it, an Authenticated Encryption
986 * mode (such as GCM or CCM) should always be preferred over any
987 * unauthenticated mode. Currently, OpenSSL supports AE only in combination
988 * with Associated Data (AEAD) where additional associated data is included
989 * in the encryption process to compute a tag at the end of the encryption.
990 * This tag will also be used in the decryption process and by verifying
991 * its validity, the authenticity of a given ciphertext is established.
992 *
993 * This is superior to unauthenticated modes in that it allows to detect
994 * if somebody effectively changed the ciphertext after it had been
995 * encrypted. This prevents malicious modifications of the ciphertext that
996 * could otherwise be exploited to modify ciphertexts in ways beneficial to
997 * potential attackers.
998 *
999 * An associated data is used where there is additional information, such as
1000 * headers or some metadata, that must be also authenticated but not
1001 * necessarily need to be encrypted. If no associated data is needed for
1002 * encryption and later decryption, the OpenSSL library still requires a
1003 * value to be set - "" may be used in case none is available.
1004 *
1005 * An example using the GCM (Galois/Counter Mode). You have 16 bytes _key_,
1006 * 12 bytes (96 bits) _nonce_ and the associated data _auth_data_. Be sure
1007 * not to reuse the _key_ and _nonce_ pair. Reusing an nonce ruins the
1008 * security guarantees of GCM mode.
1009 *
1010 * cipher = OpenSSL::Cipher::AES.new(128, :GCM).encrypt
1011 * cipher.key = key
1012 * cipher.iv = nonce
1013 * cipher.auth_data = auth_data
1014 *
1015 * encrypted = cipher.update(data) + cipher.final
1016 * tag = cipher.auth_tag # produces 16 bytes tag by default
1017 *
1018 * Now you are the receiver. You know the _key_ and have received _nonce_,
1019 * _auth_data_, _encrypted_ and _tag_ through an untrusted network. Note
1020 * that GCM accepts an arbitrary length tag between 1 and 16 bytes. You may
1021 * additionally need to check that the received tag has the correct length,
1022 * or you allow attackers to forge a valid single byte tag for the tampered
1023 * ciphertext with a probability of 1/256.
1024 *
1025 * raise "tag is truncated!" unless tag.bytesize == 16
1026 * decipher = OpenSSL::Cipher::AES.new(128, :GCM).decrypt
1027 * decipher.key = key
1028 * decipher.iv = nonce
1029 * decipher.auth_tag = tag
1030 * decipher.auth_data = auth_data
1031 *
1032 * decrypted = decipher.update(encrypted) + decipher.final
1033 *
1034 * puts data == decrypted #=> true
1035 */
1036 cCipher = rb_define_class_under(mOSSL, "Cipher", rb_cObject);
1037 eCipherError = rb_define_class_under(cCipher, "CipherError", eOSSLError);
1038
1039 rb_define_alloc_func(cCipher, ossl_cipher_alloc);
1040 rb_define_method(cCipher, "initialize_copy", ossl_cipher_copy, 1);
1041 rb_define_module_function(cCipher, "ciphers", ossl_s_ciphers, 0);
1042 rb_define_method(cCipher, "initialize", ossl_cipher_initialize, 1);
1043 rb_define_method(cCipher, "reset", ossl_cipher_reset, 0);
1044 rb_define_method(cCipher, "encrypt", ossl_cipher_encrypt, -1);
1045 rb_define_method(cCipher, "decrypt", ossl_cipher_decrypt, -1);
1046 rb_define_method(cCipher, "pkcs5_keyivgen", ossl_cipher_pkcs5_keyivgen, -1);
1047 rb_define_method(cCipher, "update", ossl_cipher_update, -1);
1048 rb_define_method(cCipher, "final", ossl_cipher_final, 0);
1049 rb_define_method(cCipher, "name", ossl_cipher_name, 0);
1050 rb_define_method(cCipher, "key=", ossl_cipher_set_key, 1);
1051 rb_define_method(cCipher, "auth_data=", ossl_cipher_set_auth_data, 1);
1052 rb_define_method(cCipher, "auth_tag=", ossl_cipher_set_auth_tag, 1);
1053 rb_define_method(cCipher, "auth_tag", ossl_cipher_get_auth_tag, -1);
1054 rb_define_method(cCipher, "auth_tag_len=", ossl_cipher_set_auth_tag_len, 1);
1055 rb_define_method(cCipher, "authenticated?", ossl_cipher_is_authenticated, 0);
1056 rb_define_method(cCipher, "key_len=", ossl_cipher_set_key_length, 1);
1057 rb_define_method(cCipher, "key_len", ossl_cipher_key_length, 0);
1058 rb_define_method(cCipher, "iv=", ossl_cipher_set_iv, 1);
1059 rb_define_method(cCipher, "iv_len=", ossl_cipher_set_iv_length, 1);
1060 rb_define_method(cCipher, "iv_len", ossl_cipher_iv_length, 0);
1061 rb_define_method(cCipher, "block_size", ossl_cipher_block_size, 0);
1062 rb_define_method(cCipher, "padding=", ossl_cipher_set_padding, 1);
1063
1064 id_auth_tag_len = rb_intern_const("auth_tag_len");
1065 id_key_set = rb_intern_const("key_set");
1066 }
ID
unsigned long ID
Definition: ruby.h:103
rb_str_new2
#define rb_str_new2
Definition: intern.h:903
assert
#define assert(x)
Definition: dlmalloc.c:1176
rb_warn
void rb_warn(const char *fmt,...)
Definition: error.c:313
memset
void * memset(void *, int, size_t)
rb_scan_args
#define rb_scan_args(argc, argvp, fmt,...)
Definition: rb_mjit_min_header-2.7.0.h:6372
GetCipherInit
#define GetCipherInit(obj, ctx)
Definition: ossl_cipher.c:20
RSTRING_PTR
#define RSTRING_PTR(str)
Definition: ruby.h:1009
rb_attr_get
VALUE rb_attr_get(VALUE, ID)
Definition: variable.c:1084
NewCipher
#define NewCipher(klass)
Definition: ossl_cipher.c:12
VALUE
unsigned long VALUE
Definition: ruby.h:102
rb_eArgError
VALUE rb_eArgError
Definition: error.c:923
rb_intern_const
#define rb_intern_const(str)
Definition: ruby.h:1879
RSTRING_LENINT
#define RSTRING_LENINT(str)
Definition: ruby.h:1017
int
__inline__ int
Definition: rb_mjit_min_header-2.7.0.h:2839
rb_define_module
VALUE rb_define_module(const char *name)
Definition: class.c:772
ossl.h
StringValue
use StringValue() instead")))
rb_define_method
void rb_define_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Definition: class.c:1551
INT2NUM
#define INT2NUM(x)
Definition: ruby.h:1609
ptr
struct RIMemo * ptr
Definition: debug.c:74
EVP_CTRL_AEAD_GET_TAG
#define EVP_CTRL_AEAD_GET_TAG
Qfalse
#define Qfalse
Definition: ruby.h:467
NULL
#define NULL
Definition: _sdbm.c:101
PRIsVALUE
#define PRIsVALUE
Definition: ruby.h:166
Init_ossl_cipher
void Init_ossl_cipher(void)
Definition: ossl_cipher.c:821
rb_str_resize
VALUE rb_str_resize(VALUE, long)
Definition: string.c:2709
cCipher
VALUE cCipher
Definition: ossl_cipher.c:33
rb_raise
void rb_raise(VALUE exc, const char *fmt,...)
Definition: error.c:2669
rb_eRangeError
VALUE rb_eRangeError
Definition: error.c:926
obj
const VALUE VALUE obj
Definition: rb_mjit_min_header-2.7.0.h:5742
rb_obj_class
VALUE rb_obj_class(VALUE)
Equivalent to Object#class in Ruby.
Definition: object.c:217
memcpy
void * memcpy(void *__restrict, const void *__restrict, size_t)
mOSSL
VALUE mOSSL
Definition: ossl.c:231
rb_check_frozen
#define rb_check_frozen(obj)
Definition: intern.h:319
INT_MAX
#define INT_MAX
Definition: rb_mjit_min_header-2.7.0.h:4052
rb_ary_push
VALUE rb_ary_push(VALUE ary, VALUE item)
Definition: array.c:1195
ossl_raise
void ossl_raise(VALUE exc, const char *fmt,...)
Definition: ossl.c:293
rb_eRuntimeError
VALUE rb_eRuntimeError
Definition: error.c:920
rb_str_set_len
void rb_str_set_len(VALUE, long)
Definition: string.c:2692
StringValueCStr
#define StringValueCStr(v)
Definition: ruby.h:604
key
key
Definition: openssl_missing.h:181
rb_define_module_function
void rb_define_module_function(VALUE module, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a module function for module.
Definition: class.c:1771
rb_cObject
RUBY_EXTERN VALUE rb_cObject
Definition: ruby.h:2010
argv
char ** argv
Definition: ruby.c:223
AllocCipher
#define AllocCipher(obj, ctx)
Definition: ossl_cipher.c:14
klass
VALUE klass
Definition: rb_mjit_min_header-2.7.0.h:13254
str
char str[HTML_ESCAPE_MAX_LEN+1]
Definition: escape.c:18
GetCipher
#define GetCipher(obj, ctx)
Definition: ossl_cipher.c:23
RUBY_TYPED_FREE_IMMEDIATELY
#define RUBY_TYPED_FREE_IMMEDIATELY
Definition: ruby.h:1207
NIL_P
#define NIL_P(v)
Definition: ruby.h:482
EVP_CTRL_AEAD_SET_TAG
#define EVP_CTRL_AEAD_SET_TAG
argc
int argc
Definition: ruby.c:222
rb_data_type_struct
Definition: ruby.h:1148
rb_str_new
#define rb_str_new(str, len)
Definition: rb_mjit_min_header-2.7.0.h:6116
Qtrue
#define Qtrue
Definition: ruby.h:468
len
uint8_t len
Definition: escape.c:17
eCipherError
VALUE eCipherError
Definition: ossl_cipher.c:34
rb_class_path
VALUE rb_class_path(VALUE)
Definition: variable.c:153
eOSSLError
VALUE eOSSLError
Definition: ossl.c:236
rb_ivar_set
VALUE rb_ivar_set(VALUE, ID, VALUE)
Definition: variable.c:1300
rb_define_class_under
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition: class.c:698
ossl_evp_get_cipherbyname
const EVP_CIPHER * ossl_evp_get_cipherbyname(VALUE obj)
Definition: ossl_cipher.c:52
rb_ary_new
VALUE rb_ary_new(void)
Definition: array.c:723
NUM2INT
#define NUM2INT(x)
Definition: ruby.h:715
Qnil
#define Qnil
Definition: ruby.h:469
ossl_evp_get_digestbyname
const EVP_MD * ossl_evp_get_digestbyname(VALUE obj)
Definition: ossl_digest.c:45
ossl_cipher_new
VALUE ossl_cipher_new(const EVP_CIPHER *cipher)
Definition: ossl_cipher.c:75
rb_eStandardError
VALUE rb_eStandardError
Definition: error.c:919
RSTRING_LEN
#define RSTRING_LEN(str)
Definition: ruby.h:1005
EVP_CTRL_AEAD_SET_IVLEN
#define EVP_CTRL_AEAD_SET_IVLEN
rb_obj_is_kind_of
VALUE rb_obj_is_kind_of(VALUE, VALUE)
Determines if obj is a kind of c.
Definition: object.c:692
rb_define_alloc_func
void rb_define_alloc_func(VALUE, rb_alloc_func_t)
RTEST
#define RTEST(v)
Definition: ruby.h:481
name
const char * name
Definition: nkf.c:208