1/* 2 * $Id: ossl.c 45472 2014-03-30 14:50:41Z nagachika $ 3 * 'OpenSSL for Ruby' project 4 * Copyright (C) 2001-2002 Michal Rokos <m.rokos@sh.cvut.cz> 5 * All rights reserved. 6 */ 7/* 8 * This program is licenced under the same licence as Ruby. 9 * (See the file 'LICENCE'.) 10 */ 11#include "ossl.h" 12#include <stdarg.h> /* for ossl_raise */ 13 14/* 15 * String to HEXString conversion 16 */ 17int 18string2hex(const unsigned char *buf, int buf_len, char **hexbuf, int *hexbuf_len) 19{ 20 static const char hex[]="0123456789abcdef"; 21 int i, len = 2 * buf_len; 22 23 if (buf_len < 0 || len < buf_len) { /* PARANOIA? */ 24 return -1; 25 } 26 if (!hexbuf) { /* if no buf, return calculated len */ 27 if (hexbuf_len) { 28 *hexbuf_len = len; 29 } 30 return len; 31 } 32 if (!(*hexbuf = OPENSSL_malloc(len + 1))) { 33 return -1; 34 } 35 for (i = 0; i < buf_len; i++) { 36 (*hexbuf)[2 * i] = hex[((unsigned char)buf[i]) >> 4]; 37 (*hexbuf)[2 * i + 1] = hex[buf[i] & 0x0f]; 38 } 39 (*hexbuf)[2 * i] = '\0'; 40 41 if (hexbuf_len) { 42 *hexbuf_len = len; 43 } 44 return len; 45} 46 47/* 48 * Data Conversion 49 */ 50#define OSSL_IMPL_ARY2SK(name, type, expected_class, dup) \ 51STACK_OF(type) * \ 52ossl_##name##_ary2sk0(VALUE ary) \ 53{ \ 54 STACK_OF(type) *sk; \ 55 VALUE val; \ 56 type *x; \ 57 int i; \ 58 \ 59 Check_Type(ary, T_ARRAY); \ 60 sk = sk_##type##_new_null(); \ 61 if (!sk) ossl_raise(eOSSLError, NULL); \ 62 \ 63 for (i = 0; i < RARRAY_LEN(ary); i++) { \ 64 val = rb_ary_entry(ary, i); \ 65 if (!rb_obj_is_kind_of(val, expected_class)) { \ 66 sk_##type##_pop_free(sk, type##_free); \ 67 ossl_raise(eOSSLError, "object in array not" \ 68 " of class ##type##"); \ 69 } \ 70 x = dup(val); /* NEED TO DUP */ \ 71 sk_##type##_push(sk, x); \ 72 } \ 73 return sk; \ 74} \ 75 \ 76STACK_OF(type) * \ 77ossl_protect_##name##_ary2sk(VALUE ary, int *status) \ 78{ \ 79 return (STACK_OF(type)*)rb_protect( \ 80 (VALUE(*)_((VALUE)))ossl_##name##_ary2sk0, \ 81 ary, \ 82 status); \ 83} \ 84 \ 85STACK_OF(type) * \ 86ossl_##name##_ary2sk(VALUE ary) \ 87{ \ 88 STACK_OF(type) *sk; \ 89 int status = 0; \ 90 \ 91 sk = ossl_protect_##name##_ary2sk(ary, &status); \ 92 if (status) rb_jump_tag(status); \ 93 \ 94 return sk; \ 95} 96OSSL_IMPL_ARY2SK(x509, X509, cX509Cert, DupX509CertPtr) 97 98#define OSSL_IMPL_SK2ARY(name, type) \ 99VALUE \ 100ossl_##name##_sk2ary(STACK_OF(type) *sk) \ 101{ \ 102 type *t; \ 103 int i, num; \ 104 VALUE ary; \ 105 \ 106 if (!sk) { \ 107 OSSL_Debug("empty sk!"); \ 108 return Qnil; \ 109 } \ 110 num = sk_##type##_num(sk); \ 111 if (num < 0) { \ 112 OSSL_Debug("items in sk < -1???"); \ 113 return rb_ary_new(); \ 114 } \ 115 ary = rb_ary_new2(num); \ 116 \ 117 for (i=0; i<num; i++) { \ 118 t = sk_##type##_value(sk, i); \ 119 rb_ary_push(ary, ossl_##name##_new(t)); \ 120 } \ 121 return ary; \ 122} 123OSSL_IMPL_SK2ARY(x509, X509) 124OSSL_IMPL_SK2ARY(x509crl, X509_CRL) 125OSSL_IMPL_SK2ARY(x509name, X509_NAME) 126 127static VALUE 128ossl_str_new(int size) 129{ 130 return rb_str_new(0, size); 131} 132 133VALUE 134ossl_buf2str(char *buf, int len) 135{ 136 VALUE str; 137 int status = 0; 138 139 str = rb_protect((VALUE(*)_((VALUE)))ossl_str_new, len, &status); 140 if(!NIL_P(str)) memcpy(RSTRING_PTR(str), buf, len); 141 OPENSSL_free(buf); 142 if(status) rb_jump_tag(status); 143 144 return str; 145} 146 147/* 148 * our default PEM callback 149 */ 150static VALUE 151ossl_pem_passwd_cb0(VALUE flag) 152{ 153 VALUE pass; 154 155 pass = rb_yield(flag); 156 SafeStringValue(pass); 157 158 return pass; 159} 160 161int 162ossl_pem_passwd_cb(char *buf, int max_len, int flag, void *pwd) 163{ 164 int len, status = 0; 165 VALUE rflag, pass; 166 167 if (pwd || !rb_block_given_p()) 168 return PEM_def_callback(buf, max_len, flag, pwd); 169 170 while (1) { 171 /* 172 * when the flag is nonzero, this passphrase 173 * will be used to perform encryption; otherwise it will 174 * be used to perform decryption. 175 */ 176 rflag = flag ? Qtrue : Qfalse; 177 pass = rb_protect(ossl_pem_passwd_cb0, rflag, &status); 178 if (status) { 179 /* ignore an exception raised. */ 180 rb_set_errinfo(Qnil); 181 return -1; 182 } 183 len = RSTRING_LENINT(pass); 184 if (len < 4) { /* 4 is OpenSSL hardcoded limit */ 185 rb_warning("password must be longer than 4 bytes"); 186 continue; 187 } 188 if (len > max_len) { 189 rb_warning("password must be shorter then %d bytes", max_len-1); 190 continue; 191 } 192 memcpy(buf, RSTRING_PTR(pass), len); 193 break; 194 } 195 return len; 196} 197 198/* 199 * Verify callback 200 */ 201int ossl_verify_cb_idx; 202 203VALUE 204ossl_call_verify_cb_proc(struct ossl_verify_cb_args *args) 205{ 206 return rb_funcall(args->proc, rb_intern("call"), 2, 207 args->preverify_ok, args->store_ctx); 208} 209 210int 211ossl_verify_cb(int ok, X509_STORE_CTX *ctx) 212{ 213 VALUE proc, rctx, ret; 214 struct ossl_verify_cb_args args; 215 int state = 0; 216 217 proc = (VALUE)X509_STORE_CTX_get_ex_data(ctx, ossl_verify_cb_idx); 218 if ((void*)proc == 0) 219 proc = (VALUE)X509_STORE_get_ex_data(ctx->ctx, ossl_verify_cb_idx); 220 if ((void*)proc == 0) 221 return ok; 222 if (!NIL_P(proc)) { 223 ret = Qfalse; 224 rctx = rb_protect((VALUE(*)(VALUE))ossl_x509stctx_new, 225 (VALUE)ctx, &state); 226 if (state) { 227 rb_set_errinfo(Qnil); 228 rb_warn("StoreContext initialization failure"); 229 } 230 else { 231 args.proc = proc; 232 args.preverify_ok = ok ? Qtrue : Qfalse; 233 args.store_ctx = rctx; 234 ret = rb_protect((VALUE(*)(VALUE))ossl_call_verify_cb_proc, (VALUE)&args, &state); 235 if (state) { 236 rb_set_errinfo(Qnil); 237 rb_warn("exception in verify_callback is ignored"); 238 } 239 ossl_x509stctx_clear_ptr(rctx); 240 } 241 if (ret == Qtrue) { 242 X509_STORE_CTX_set_error(ctx, X509_V_OK); 243 ok = 1; 244 } 245 else{ 246 if (X509_STORE_CTX_get_error(ctx) == X509_V_OK) { 247 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_REJECTED); 248 } 249 ok = 0; 250 } 251 } 252 253 return ok; 254} 255 256/* 257 * main module 258 */ 259VALUE mOSSL; 260 261/* 262 * OpenSSLError < StandardError 263 */ 264VALUE eOSSLError; 265 266/* 267 * Convert to DER string 268 */ 269ID ossl_s_to_der; 270 271VALUE 272ossl_to_der(VALUE obj) 273{ 274 VALUE tmp; 275 276 tmp = rb_funcall(obj, ossl_s_to_der, 0); 277 StringValue(tmp); 278 279 return tmp; 280} 281 282VALUE 283ossl_to_der_if_possible(VALUE obj) 284{ 285 if(rb_respond_to(obj, ossl_s_to_der)) 286 return ossl_to_der(obj); 287 return obj; 288} 289 290/* 291 * Errors 292 */ 293static VALUE 294ossl_make_error(VALUE exc, const char *fmt, va_list args) 295{ 296 VALUE str = Qnil; 297 const char *msg; 298 long e; 299 300#ifdef HAVE_ERR_PEEK_LAST_ERROR 301 e = ERR_peek_last_error(); 302#else 303 e = ERR_peek_error(); 304#endif 305 if (fmt) { 306 str = rb_vsprintf(fmt, args); 307 } 308 if (e) { 309 if (dOSSL == Qtrue) /* FULL INFO */ 310 msg = ERR_error_string(e, NULL); 311 else 312 msg = ERR_reason_error_string(e); 313 if (NIL_P(str)) { 314 if (msg) str = rb_str_new_cstr(msg); 315 } 316 else { 317 if (RSTRING_LEN(str)) rb_str_cat2(str, ": "); 318 rb_str_cat2(str, msg ? msg : "(null)"); 319 } 320 } 321 if (dOSSL == Qtrue){ /* show all errors on the stack */ 322 while ((e = ERR_get_error()) != 0){ 323 rb_warn("error on stack: %s", ERR_error_string(e, NULL)); 324 } 325 } 326 ERR_clear_error(); 327 328 if (NIL_P(str)) str = rb_str_new(0, 0); 329 return rb_exc_new3(exc, str); 330} 331 332void 333ossl_raise(VALUE exc, const char *fmt, ...) 334{ 335 va_list args; 336 VALUE err; 337 va_start(args, fmt); 338 err = ossl_make_error(exc, fmt, args); 339 va_end(args); 340 rb_exc_raise(err); 341} 342 343VALUE 344ossl_exc_new(VALUE exc, const char *fmt, ...) 345{ 346 va_list args; 347 VALUE err; 348 va_start(args, fmt); 349 err = ossl_make_error(exc, fmt, args); 350 va_end(args); 351 return err; 352} 353 354/* 355 * call-seq: 356 * OpenSSL.errors -> [String...] 357 * 358 * See any remaining errors held in queue. 359 * 360 * Any errors you see here are probably due to a bug in ruby's OpenSSL implementation. 361 */ 362VALUE 363ossl_get_errors() 364{ 365 VALUE ary; 366 long e; 367 368 ary = rb_ary_new(); 369 while ((e = ERR_get_error()) != 0){ 370 rb_ary_push(ary, rb_str_new2(ERR_error_string(e, NULL))); 371 } 372 373 return ary; 374} 375 376/* 377 * Debug 378 */ 379VALUE dOSSL; 380 381#if !defined(HAVE_VA_ARGS_MACRO) 382void 383ossl_debug(const char *fmt, ...) 384{ 385 va_list args; 386 387 if (dOSSL == Qtrue) { 388 fprintf(stderr, "OSSL_DEBUG: "); 389 va_start(args, fmt); 390 vfprintf(stderr, fmt, args); 391 va_end(args); 392 fprintf(stderr, " [CONTEXT N/A]\n"); 393 } 394} 395#endif 396 397/* 398 * call-seq: 399 * OpenSSL.debug -> true | false 400 */ 401static VALUE 402ossl_debug_get(VALUE self) 403{ 404 return dOSSL; 405} 406 407/* 408 * call-seq: 409 * OpenSSL.debug = boolean -> boolean 410 * 411 * Turns on or off CRYPTO_MEM_CHECK. 412 * Also shows some debugging message on stderr. 413 */ 414static VALUE 415ossl_debug_set(VALUE self, VALUE val) 416{ 417 VALUE old = dOSSL; 418 dOSSL = val; 419 420 if (old != dOSSL) { 421 if (dOSSL == Qtrue) { 422 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); 423 fprintf(stderr, "OSSL_DEBUG: IS NOW ON!\n"); 424 } else if (old == Qtrue) { 425 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_OFF); 426 fprintf(stderr, "OSSL_DEBUG: IS NOW OFF!\n"); 427 } 428 } 429 return val; 430} 431 432/* 433 * call-seq: 434 * OpenSSL.fips_mode = boolean -> boolean 435 * 436 * Turns FIPS mode on or off. Turning on FIPS mode will obviously only have an 437 * effect for FIPS-capable installations of the OpenSSL library. Trying to do 438 * so otherwise will result in an error. 439 * 440 * === Examples 441 * 442 * OpenSSL.fips_mode = true # turn FIPS mode on 443 * OpenSSL.fips_mode = false # and off again 444 */ 445static VALUE 446ossl_fips_mode_set(VALUE self, VALUE enabled) 447{ 448 449#ifdef HAVE_OPENSSL_FIPS 450 if (RTEST(enabled)) { 451 int mode = FIPS_mode(); 452 if(!mode && !FIPS_mode_set(1)) /* turning on twice leads to an error */ 453 ossl_raise(eOSSLError, "Turning on FIPS mode failed"); 454 } else { 455 if(!FIPS_mode_set(0)) /* turning off twice is OK */ 456 ossl_raise(eOSSLError, "Turning off FIPS mode failed"); 457 } 458 return enabled; 459#else 460 if (RTEST(enabled)) 461 ossl_raise(eOSSLError, "This version of OpenSSL does not support FIPS mode"); 462 return enabled; 463#endif 464} 465 466/* 467 * OpenSSL provides SSL, TLS and general purpose cryptography. It wraps the 468 * OpenSSL[http://www.openssl.org/] library. 469 * 470 * = Examples 471 * 472 * All examples assume you have loaded OpenSSL with: 473 * 474 * require 'openssl' 475 * 476 * These examples build atop each other. For example the key created in the 477 * next is used in throughout these examples. 478 * 479 * == Keys 480 * 481 * === Creating a Key 482 * 483 * This example creates a 2048 bit RSA keypair and writes it to the current 484 * directory. 485 * 486 * key = OpenSSL::PKey::RSA.new 2048 487 * 488 * open 'private_key.pem', 'w' do |io| io.write key.to_pem end 489 * open 'public_key.pem', 'w' do |io| io.write key.public_key.to_pem end 490 * 491 * === Exporting a Key 492 * 493 * Keys saved to disk without encryption are not secure as anyone who gets 494 * ahold of the key may use it unless it is encrypted. In order to securely 495 * export a key you may export it with a pass phrase. 496 * 497 * cipher = OpenSSL::Cipher.new 'AES-128-CBC' 498 * pass_phrase = 'my secure pass phrase goes here' 499 * 500 * key_secure = key.export cipher, pass_phrase 501 * 502 * open 'private.secure.pem', 'w' do |io| 503 * io.write key_secure 504 * end 505 * 506 * OpenSSL::Cipher.ciphers returns a list of available ciphers. 507 * 508 * === Loading a Key 509 * 510 * A key can also be loaded from a file. 511 * 512 * key2 = OpenSSL::PKey::RSA.new File.read 'private_key.pem' 513 * key2.public? # => true 514 * 515 * or 516 * 517 * key3 = OpenSSL::PKey::RSA.new File.read 'public_key.pem' 518 * key3.private? # => false 519 * 520 * === Loading an Encrypted Key 521 * 522 * OpenSSL will prompt you for your pass phrase when loading an encrypted key. 523 * If you will not be able to type in the pass phrase you may provide it when 524 * loading the key: 525 * 526 * key4_pem = File.read 'private.secure.pem' 527 * key4 = OpenSSL::PKey::RSA.new key4_pem, pass_phrase 528 * 529 * == RSA Encryption 530 * 531 * RSA provides encryption and decryption using the public and private keys. 532 * You can use a variety of padding methods depending upon the intended use of 533 * encrypted data. 534 * 535 * === Encryption & Decryption 536 * 537 * Asymmetric public/private key encryption is slow and victim to attack in 538 * cases where it is used without padding or directly to encrypt larger chunks 539 * of data. Typical use cases for RSA encryption involve "wrapping" a symmetric 540 * key with the public key of the recipient who would "unwrap" that symmetric 541 * key again using their private key. 542 * The following illustrates a simplified example of such a key transport 543 * scheme. It shouldn't be used in practice, though, standardized protocols 544 * should always be preferred. 545 * 546 * wrapped_key = key.public_encrypt key 547 * 548 * A symmetric key encrypted with the public key can only be decrypted with 549 * the corresponding private key of the recipient. 550 * 551 * original_key = key.private_decrypt wrapped_key 552 * 553 * By default PKCS#1 padding will be used, but it is also possible to use 554 * other forms of padding, see PKey::RSA for further details. 555 * 556 * === Signatures 557 * 558 * Using "private_encrypt" to encrypt some data with the private key is 559 * equivalent to applying a digital signature to the data. A verifying 560 * party may validate the signature by comparing the result of decrypting 561 * the signature with "public_decrypt" to the original data. However, 562 * OpenSSL::PKey already has methods "sign" and "verify" that handle 563 * digital signatures in a standardized way - "private_encrypt" and 564 * "public_decrypt" shouldn't be used in practice. 565 * 566 * To sign a document, a cryptographically secure hash of the document is 567 * computed first, which is then signed using the private key. 568 * 569 * digest = OpenSSL::Digest::SHA256.new 570 * signature = key.sign digest, document 571 * 572 * To validate the signature, again a hash of the document is computed and 573 * the signature is decrypted using the public key. The result is then 574 * compared to the hash just computed, if they are equal the signature was 575 * valid. 576 * 577 * digest = OpenSSL::Digest::SHA256.new 578 * if key.verify digest, signature, document 579 * puts 'Valid' 580 * else 581 * puts 'Invalid' 582 * end 583 * 584 * == PBKDF2 Password-based Encryption 585 * 586 * If supported by the underlying OpenSSL version used, Password-based 587 * Encryption should use the features of PKCS5. If not supported or if 588 * required by legacy applications, the older, less secure methods specified 589 * in RFC 2898 are also supported (see below). 590 * 591 * PKCS5 supports PBKDF2 as it was specified in PKCS#5 592 * v2.0[http://www.rsa.com/rsalabs/node.asp?id=2127]. It still uses a 593 * password, a salt, and additionally a number of iterations that will 594 * slow the key derivation process down. The slower this is, the more work 595 * it requires being able to brute-force the resulting key. 596 * 597 * === Encryption 598 * 599 * The strategy is to first instantiate a Cipher for encryption, and 600 * then to generate a random IV plus a key derived from the password 601 * using PBKDF2. PKCS #5 v2.0 recommends at least 8 bytes for the salt, 602 * the number of iterations largely depends on the hardware being used. 603 * 604 * cipher = OpenSSL::Cipher.new 'AES-128-CBC' 605 * cipher.encrypt 606 * iv = cipher.random_iv 607 * 608 * pwd = 'some hopefully not to easily guessable password' 609 * salt = OpenSSL::Random.random_bytes 16 610 * iter = 20000 611 * key_len = cipher.key_len 612 * digest = OpenSSL::Digest::SHA256.new 613 * 614 * key = OpenSSL::PKCS5.pbkdf2_hmac(pwd, salt, iter, key_len, digest) 615 * cipher.key = key 616 * 617 * Now encrypt the data: 618 * 619 * encrypted = cipher.update document 620 * encrypted << cipher.final 621 * 622 * === Decryption 623 * 624 * Use the same steps as before to derive the symmetric AES key, this time 625 * setting the Cipher up for decryption. 626 * 627 * cipher = OpenSSL::Cipher.new 'AES-128-CBC' 628 * cipher.decrypt 629 * cipher.iv = iv # the one generated with #random_iv 630 * 631 * pwd = 'some hopefully not to easily guessable password' 632 * salt = ... # the one generated above 633 * iter = 20000 634 * key_len = cipher.key_len 635 * digest = OpenSSL::Digest::SHA256.new 636 * 637 * key = OpenSSL::PKCS5.pbkdf2_hmac(pwd, salt, iter, key_len, digest) 638 * cipher.key = key 639 * 640 * Now decrypt the data: 641 * 642 * decrypted = cipher.update encrypted 643 * decrypted << cipher.final 644 * 645 * == PKCS #5 Password-based Encryption 646 * 647 * PKCS #5 is a password-based encryption standard documented at 648 * RFC2898[http://www.ietf.org/rfc/rfc2898.txt]. It allows a short password or 649 * passphrase to be used to create a secure encryption key. If possible, PBKDF2 650 * as described above should be used if the circumstances allow it. 651 * 652 * PKCS #5 uses a Cipher, a pass phrase and a salt to generate an encryption 653 * key. 654 * 655 * pass_phrase = 'my secure pass phrase goes here' 656 * salt = '8 octets' 657 * 658 * === Encryption 659 * 660 * First set up the cipher for encryption 661 * 662 * encrypter = OpenSSL::Cipher.new 'AES-128-CBC' 663 * encrypter.encrypt 664 * encrypter.pkcs5_keyivgen pass_phrase, salt 665 * 666 * Then pass the data you want to encrypt through 667 * 668 * encrypted = encrypter.update 'top secret document' 669 * encrypted << encrypter.final 670 * 671 * === Decryption 672 * 673 * Use a new Cipher instance set up for decryption 674 * 675 * decrypter = OpenSSL::Cipher.new 'AES-128-CBC' 676 * decrypter.decrypt 677 * decrypter.pkcs5_keyivgen pass_phrase, salt 678 * 679 * Then pass the data you want to decrypt through 680 * 681 * plain = decrypter.update encrypted 682 * plain << decrypter.final 683 * 684 * == X509 Certificates 685 * 686 * === Creating a Certificate 687 * 688 * This example creates a self-signed certificate using an RSA key and a SHA1 689 * signature. 690 * 691 * name = OpenSSL::X509::Name.parse 'CN=nobody/DC=example' 692 * 693 * cert = OpenSSL::X509::Certificate.new 694 * cert.version = 2 695 * cert.serial = 0 696 * cert.not_before = Time.now 697 * cert.not_after = Time.now + 3600 698 * 699 * cert.public_key = key.public_key 700 * cert.subject = name 701 * 702 * === Certificate Extensions 703 * 704 * You can add extensions to the certificate with 705 * OpenSSL::SSL::ExtensionFactory to indicate the purpose of the certificate. 706 * 707 * extension_factory = OpenSSL::X509::ExtensionFactory.new nil, cert 708 * 709 * cert.add_extension \ 710 * extension_factory.create_extension('basicConstraints', 'CA:FALSE', true) 711 * 712 * cert.add_extension \ 713 * extension_factory.create_extension( 714 * 'keyUsage', 'keyEncipherment,dataEncipherment,digitalSignature') 715 * 716 * cert.add_extension \ 717 * extension_factory.create_extension('subjectKeyIdentifier', 'hash') 718 * 719 * The list of supported extensions (and in some cases their possible values) 720 * can be derived from the "objects.h" file in the OpenSSL source code. 721 * 722 * === Signing a Certificate 723 * 724 * To sign a certificate set the issuer and use OpenSSL::X509::Certificate#sign 725 * with a digest algorithm. This creates a self-signed cert because we're using 726 * the same name and key to sign the certificate as was used to create the 727 * certificate. 728 * 729 * cert.issuer = name 730 * cert.sign key, OpenSSL::Digest::SHA1.new 731 * 732 * open 'certificate.pem', 'w' do |io| io.write cert.to_pem end 733 * 734 * === Loading a Certificate 735 * 736 * Like a key, a cert can also be loaded from a file. 737 * 738 * cert2 = OpenSSL::X509::Certificate.new File.read 'certificate.pem' 739 * 740 * === Verifying a Certificate 741 * 742 * Certificate#verify will return true when a certificate was signed with the 743 * given public key. 744 * 745 * raise 'certificate can not be verified' unless cert2.verify key 746 * 747 * == Certificate Authority 748 * 749 * A certificate authority (CA) is a trusted third party that allows you to 750 * verify the ownership of unknown certificates. The CA issues key signatures 751 * that indicate it trusts the user of that key. A user encountering the key 752 * can verify the signature by using the CA's public key. 753 * 754 * === CA Key 755 * 756 * CA keys are valuable, so we encrypt and save it to disk and make sure it is 757 * not readable by other users. 758 * 759 * ca_key = OpenSSL::PKey::RSA.new 2048 760 * 761 * cipher = OpenSSL::Cipher::Cipher.new 'AES-128-CBC' 762 * 763 * open 'ca_key.pem', 'w', 0400 do |io| 764 * io.write key.export(cipher, pass_phrase) 765 * end 766 * 767 * === CA Certificate 768 * 769 * A CA certificate is created the same way we created a certificate above, but 770 * with different extensions. 771 * 772 * ca_name = OpenSSL::X509::Name.parse 'CN=ca/DC=example' 773 * 774 * ca_cert = OpenSSL::X509::Certificate.new 775 * ca_cert.serial = 0 776 * ca_cert.version = 2 777 * ca_cert.not_before = Time.now 778 * ca_cert.not_after = Time.now + 86400 779 * 780 * ca_cert.public_key = ca_key.public_key 781 * ca_cert.subject = ca_name 782 * ca_cert.issuer = ca_name 783 * 784 * extension_factory = OpenSSL::X509::ExtensionFactory.new 785 * extension_factory.subject_certificate = ca_cert 786 * extension_factory.issuer_certificate = ca_cert 787 * 788 * ca_cert.add_extension \ 789 * extension_factory.create_extension('subjectKeyIdentifier', 'hash') 790 * 791 * This extension indicates the CA's key may be used as a CA. 792 * 793 * ca_cert.add_extension \ 794 * extension_factory.create_extension('basicConstraints', 'CA:TRUE', true) 795 * 796 * This extension indicates the CA's key may be used to verify signatures on 797 * both certificates and certificate revocations. 798 * 799 * ca_cert.add_extension \ 800 * extension_factory.create_extension( 801 * 'keyUsage', 'cRLSign,keyCertSign', true) 802 * 803 * Root CA certificates are self-signed. 804 * 805 * ca_cert.sign ca_key, OpenSSL::Digest::SHA1.new 806 * 807 * The CA certificate is saved to disk so it may be distributed to all the 808 * users of the keys this CA will sign. 809 * 810 * open 'ca_cert.pem', 'w' do |io| 811 * io.write ca_cert.to_pem 812 * end 813 * 814 * === Certificate Signing Request 815 * 816 * The CA signs keys through a Certificate Signing Request (CSR). The CSR 817 * contains the information necessary to identify the key. 818 * 819 * csr = OpenSSL::X509::Request.new 820 * csr.version = 0 821 * csr.subject = name 822 * csr.public_key = key.public_key 823 * csr.sign key, OpenSSL::Digest::SHA1.new 824 * 825 * A CSR is saved to disk and sent to the CA for signing. 826 * 827 * open 'csr.pem', 'w' do |io| 828 * io.write csr.to_pem 829 * end 830 * 831 * === Creating a Certificate from a CSR 832 * 833 * Upon receiving a CSR the CA will verify it before signing it. A minimal 834 * verification would be to check the CSR's signature. 835 * 836 * csr = OpenSSL::X509::Request.new File.read 'csr.pem' 837 * 838 * raise 'CSR can not be verified' unless csr.verify csr.public_key 839 * 840 * After verification a certificate is created, marked for various usages, 841 * signed with the CA key and returned to the requester. 842 * 843 * csr_cert = OpenSSL::X509::Certificate.new 844 * csr_cert.serial = 0 845 * csr_cert.version = 2 846 * csr_cert.not_before = Time.now 847 * csr_cert.not_after = Time.now + 600 848 * 849 * csr_cert.subject = csr.subject 850 * csr_cert.public_key = csr.public_key 851 * csr_cert.issuer = ca_cert.subject 852 * 853 * extension_factory = OpenSSL::X509::ExtensionFactory.new 854 * extension_factory.subject_certificate = csr_cert 855 * extension_factory.issuer_certificate = ca_cert 856 * 857 * csr_cert.add_extension \ 858 * extension_factory.create_extension('basicConstraints', 'CA:FALSE') 859 * 860 * csr_cert.add_extension \ 861 * extension_factory.create_extension( 862 * 'keyUsage', 'keyEncipherment,dataEncipherment,digitalSignature') 863 * 864 * csr_cert.add_extension \ 865 * extension_factory.create_extension('subjectKeyIdentifier', 'hash') 866 * 867 * csr_cert.sign ca_key, OpenSSL::Digest::SHA1.new 868 * 869 * open 'csr_cert.pem', 'w' do |io| 870 * io.write csr_cert.to_pem 871 * end 872 * 873 * == SSL and TLS Connections 874 * 875 * Using our created key and certificate we can create an SSL or TLS connection. 876 * An SSLContext is used to set up an SSL session. 877 * 878 * context = OpenSSL::SSL::SSLContext.new 879 * 880 * === SSL Server 881 * 882 * An SSL server requires the certificate and private key to communicate 883 * securely with its clients: 884 * 885 * context.cert = cert 886 * context.key = key 887 * 888 * Then create an SSLServer with a TCP server socket and the context. Use the 889 * SSLServer like an ordinary TCP server. 890 * 891 * require 'socket' 892 * 893 * tcp_server = TCPServer.new 5000 894 * ssl_server = OpenSSL::SSL::SSLServer.new tcp_server, context 895 * 896 * loop do 897 * ssl_connection = ssl_server.accept 898 * 899 * data = connection.gets 900 * 901 * response = "I got #{data.dump}" 902 * puts response 903 * 904 * connection.puts "I got #{data.dump}" 905 * connection.close 906 * end 907 * 908 * === SSL client 909 * 910 * An SSL client is created with a TCP socket and the context. 911 * SSLSocket#connect must be called to initiate the SSL handshake and start 912 * encryption. A key and certificate are not required for the client socket. 913 * 914 * require 'socket' 915 * 916 * tcp_client = TCPSocket.new 'localhost', 5000 917 * ssl_client = OpenSSL::SSL::SSLSocket.new client_socket, context 918 * ssl_client.connect 919 * 920 * ssl_client.puts "hello server!" 921 * puts ssl_client.gets 922 * 923 * === Peer Verification 924 * 925 * An unverified SSL connection does not provide much security. For enhanced 926 * security the client or server can verify the certificate of its peer. 927 * 928 * The client can be modified to verify the server's certificate against the 929 * certificate authority's certificate: 930 * 931 * context.ca_file = 'ca_cert.pem' 932 * context.verify_mode = OpenSSL::SSL::VERIFY_PEER 933 * 934 * require 'socket' 935 * 936 * tcp_client = TCPSocket.new 'localhost', 5000 937 * ssl_client = OpenSSL::SSL::SSLSocket.new client_socket, context 938 * ssl_client.connect 939 * 940 * ssl_client.puts "hello server!" 941 * puts ssl_client.gets 942 * 943 * If the server certificate is invalid or <tt>context.ca_file</tt> is not set 944 * when verifying peers an OpenSSL::SSL::SSLError will be raised. 945 * 946 */ 947void 948Init_openssl() 949{ 950 /* 951 * Init timezone info 952 */ 953#if 0 954 tzset(); 955#endif 956 957 /* 958 * Init all digests, ciphers 959 */ 960 /* CRYPTO_malloc_init(); */ 961 /* ENGINE_load_builtin_engines(); */ 962 OpenSSL_add_ssl_algorithms(); 963 OpenSSL_add_all_algorithms(); 964 ERR_load_crypto_strings(); 965 SSL_load_error_strings(); 966 967 /* 968 * FIXME: 969 * On unload do: 970 */ 971#if 0 972 CONF_modules_unload(1); 973 destroy_ui_method(); 974 EVP_cleanup(); 975 ENGINE_cleanup(); 976 CRYPTO_cleanup_all_ex_data(); 977 ERR_remove_state(0); 978 ERR_free_strings(); 979#endif 980 981 /* 982 * Init main module 983 */ 984 mOSSL = rb_define_module("OpenSSL"); 985 986 /* 987 * OpenSSL ruby extension version 988 */ 989 rb_define_const(mOSSL, "VERSION", rb_str_new2(OSSL_VERSION)); 990 991 /* 992 * Version of OpenSSL the ruby OpenSSL extension was built with 993 */ 994 rb_define_const(mOSSL, "OPENSSL_VERSION", rb_str_new2(OPENSSL_VERSION_TEXT)); 995 996 /* 997 * Version number of OpenSSL the ruby OpenSSL extension was built with 998 * (base 16) 999 */ 1000 rb_define_const(mOSSL, "OPENSSL_VERSION_NUMBER", INT2NUM(OPENSSL_VERSION_NUMBER)); 1001 1002 /* 1003 * Boolean indicating whether OpenSSL is FIPS-enabled or not 1004 */ 1005#ifdef HAVE_OPENSSL_FIPS 1006 rb_define_const(mOSSL, "OPENSSL_FIPS", Qtrue); 1007#else 1008 rb_define_const(mOSSL, "OPENSSL_FIPS", Qfalse); 1009#endif 1010 rb_define_module_function(mOSSL, "fips_mode=", ossl_fips_mode_set, 1); 1011 1012 /* 1013 * Generic error, 1014 * common for all classes under OpenSSL module 1015 */ 1016 eOSSLError = rb_define_class_under(mOSSL,"OpenSSLError",rb_eStandardError); 1017 1018 /* 1019 * Verify callback Proc index for ext-data 1020 */ 1021 if ((ossl_verify_cb_idx = X509_STORE_CTX_get_ex_new_index(0, (void *)"ossl_verify_cb_idx", 0, 0, 0)) < 0) 1022 ossl_raise(eOSSLError, "X509_STORE_CTX_get_ex_new_index"); 1023 1024 /* 1025 * Init debug core 1026 */ 1027 dOSSL = Qfalse; 1028 rb_define_module_function(mOSSL, "debug", ossl_debug_get, 0); 1029 rb_define_module_function(mOSSL, "debug=", ossl_debug_set, 1); 1030 rb_define_module_function(mOSSL, "errors", ossl_get_errors, 0); 1031 1032 /* 1033 * Get ID of to_der 1034 */ 1035 ossl_s_to_der = rb_intern("to_der"); 1036 1037 /* 1038 * Init components 1039 */ 1040 Init_ossl_bn(); 1041 Init_ossl_cipher(); 1042 Init_ossl_config(); 1043 Init_ossl_digest(); 1044 Init_ossl_hmac(); 1045 Init_ossl_ns_spki(); 1046 Init_ossl_pkcs12(); 1047 Init_ossl_pkcs7(); 1048 Init_ossl_pkcs5(); 1049 Init_ossl_pkey(); 1050 Init_ossl_rand(); 1051 Init_ossl_ssl(); 1052 Init_ossl_x509(); 1053 Init_ossl_ocsp(); 1054 Init_ossl_engine(); 1055 Init_ossl_asn1(); 1056} 1057 1058#if defined(OSSL_DEBUG) 1059/* 1060 * Check if all symbols are OK with 'make LDSHARED=gcc all' 1061 */ 1062int 1063main(int argc, char *argv[]) 1064{ 1065 return 0; 1066} 1067#endif /* OSSL_DEBUG */ 1068 1069