SlideShare una empresa de Scribd logo
1 de 45
Descargar para leer sin conexión
Crypto with OpenSSL
                               GUAN Zhi
                       guanzhi@infosec.pku.edu.cn




Oct. 17, 2008       Network and Information Security Lab, Peking University   Guan Zhi
Outline
   •       OpenSSL Programing

   •       Program secure code tips

   •       CPK version 0.6.8 source code organization

   •       CPK version 0.7 new features




Oct. 17, 2008          Network and Information Security Lab, Peking University   Guan Zhi
OpenSSL Programming



Oct. 17, 2008   Network and Information Security Lab, Peking University   Guan Zhi
What is OpenSSL?
   •       Cryptography tool kit.

   •       Open source implementation of SSL v2/v3 and TLS v1.

   •       PKI/CA, cryptographic command line tools.




Oct. 17, 2008           Network and Information Security Lab, Peking University   Guan Zhi
OpenSSL Includes
   •       Source code, http://www.openssl.org/source/ (release)
           or ftp://ftp.openssl.org/snapshot/ (snapshot)

   •       Include header files, #include <openssl/des.h>
           or /usr/src/include/openssl/

   •       libraries, libeay32.[lib|dll], ssleay32.[lib/dll] (Win32) or
           libcrypto.[so|a], libssl.[so|a] (Linux).

   •       executable binary: openssl[.exe]




Oct. 17, 2008            Network and Information Security Lab, Peking University   Guan Zhi
Command Line Tool
   •       The openssl program is a command line tool for using
           the various cryptography functions of OpenSSL’s crypto
           library from the shell. It can be used for
       ❖ – Creation of RSA, DH and DSA key parameters
       ❖ – Creation of X.509 certificates, CSRs and CRLs
       ❖ – Calculation of Message Digests
       ❖ – Encryption and Decryption with Ciphers
       ❖ – SSL/TLS Client and Server Tests
       ❖ – Handling of S/MIME signed or encrypted mail

Oct. 17, 2008           Network and Information Security Lab, Peking University   Guan Zhi
Supported PKI Standards
   •       ASN.1 encoding

   •       SSLv2, SSLv3, TLSv1

   •       PKCS #5, PKCS #7, PKCS #8, PKCS #12, X.509v3

   •       OCSP

   •       PEM




Oct. 17, 2008          Network and Information Security Lab, Peking University   Guan Zhi
Supported Algorithms
   •       Block ciphers: AES, DES, 3DES, Blowfish, Camellia,
           CAST, Idea, RC2, RC5.

   •       Block cipher modes: ECB, CBC, CFB, OFB, CTR ...

   •       Stream ciphers: RC4

   •       Digest algorithms: MD2, MD4, MD5, SHA-1, SHA-224,
           SHA-256, SHA-384, SHA-512, Ripemd-160.

   •       MAC: HMAC, MDC2

   •       Public key crypto-systems: DH, DSA, RSA, ECC.


Oct. 17, 2008          Network and Information Security Lab, Peking University   Guan Zhi
OpenSSL License
   •       OpenSSL is licensed under Apache style license, free to
           get and use it for commercial and non-commercial
           purposes subject to some simple license conditions.

   •       Redistributions of any form what so ever must retain
           the following acknowledgment:
       ❖ quot;This product includes software developed by the
                OpenSSL Project for use in the OpenSSL Toolkit
                (http://www.openssl.org/)quot;




Oct. 17, 2008             Network and Information Security Lab, Peking University   Guan Zhi
Download, Build and Install
       ❖ $ ./config
       ❖ $ make
       ❖ $ make test
       ❖ $ make install

   •       Download the source code from *official* openssl
           homepage.

   •       The *make test* step is very important! In some
           platforms this step may fail.


Oct. 17, 2008          Network and Information Security Lab, Peking University   Guan Zhi
Source Code
   •       openssl/apps/ openssl command line tool

   •       openssl/crypto/ libcrypto crypto library

   •       openssl/ssl/ libssl SSL/TLS library

   •       openssl/demos/ some examples

   •       openssl/docs/ man pages and howtos

   •       openssl/engines/ hardware crypto accelerator drivers

   •       openssl/include/ include header files



Oct. 17, 2008            Network and Information Security Lab, Peking University   Guan Zhi
Source Code
   •       openssl/MACOS,ms,Netware,os2,VMS/ platform
           specific

   •       openssl/test/ code for make test, important.

   •       openssl/times/ code for ``openssl speed’’ benchmark

   •       openssl/tools/

   •       openssl/util/ perl shells for C code generation




Oct. 17, 2008           Network and Information Security Lab, Peking University   Guan Zhi
openssl/crypto/*

                              Public Key Crypto
  Ciphers
                                                                       Data Structure                         RNG
                                                           PKI
                                       bn
   aes                                                                                         Utilities
                                                                             buffer
                 Hash Algors and                                                                              seed
                                                          asn1
                     MACs              dh
    bf
                                                                             lhash               bio          rand
                                                          krb5
                     hmac              dsa
 camellia
                                                                            pqueue             engine
                                                        objects
                      md2              dso
   cast                                                                                                        CLI
                                                                             stack               err
                                                          ocsp
                                                                                                               ui
                      md4               ec
   des
                                                                             store               evp
                                                          pem
                                                                                                              conf
                      md5             ecdh
   idea
                                                                            txt_db             threads
                                                         pkcs7
                     mdc2             ecdsa
    rc2
                                                        pkcs12                                             Compression
                     ripemd                                                          SSL/TLS
                                       rsa
    rc4
                                                         x509                                                 comp
                                                                                       ssl
                      sha
    rc5
                                                        x509v3


 Oct. 17, 2008                     Network and Information Security Lab, Peking University                     Guan Zhi
Architecture of OpenSSL

                                           Command Line Interface

                                                                              SSL/TLS
                           EVP Crypto API

                                                                             BIO
                                                                 ERR Error                     Data
                                                                           Abstract
                                                                 Handling                    Structure
                Soft Crypto Impl            Engine API                       I/O


                                          Hard Crypto
                                          Accelerator




Oct. 17, 2008                      Network and Information Security Lab, Peking University               Guan Zhi
Crypto API
   •       Microsoft Crypto API

   •       RSA PKCS #11: Cryptographic Token Interface Standard

   •       OpenGroup Common Security: CDSA and CSSM

   •       OpenSSL EVP interface
       ❖ Change different cipher algorithms without change
                the source code.




Oct. 17, 2008             Network and Information Security Lab, Peking University   Guan Zhi
EVP Symmetric Encryption
                #include <openssl/evp.h>

                EVP_CIPHER_CTX ctx;
                EVP_CIPHER_CTX_init(&ctx);
                const EVP_CIPHER *cipher = EVP_aes_128_cbc();

                EVP_EncryptInit(&ctx, cipher, key, iv);
                EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen);
                EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen);
                ...
                EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen);
                EVP_EncryptFinal(&ctx, out, &outlen);

                EVP_CIPHER_CTX_cleanup(&ctx);




Oct. 17, 2008         Network and Information Security Lab, Peking University   Guan Zhi
EVP Symmetric Encryption
                #include <openssl/evp.h>

                EVP_CIPHER_CTX ctx;
                EVP_CIPHER_CTX_init(&ctx);
                const EVP_CIPHER *cipher = EVP_aes_128_cbc();

                EVP_EncryptInit(&ctx, cipher, key, iv);
                EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen);
                EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen);
                ...
                EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen);
                EVP_EncryptFinal(&ctx, out, &outlen);

                EVP_CIPHER_CTX_cleanup(&ctx);




Oct. 17, 2008         Network and Information Security Lab, Peking University   Guan Zhi
EVP Symmetric Encryption
                #include <openssl/evp.h>

                EVP_CIPHER_CTX ctx;
                EVP_CIPHER_CTX_init(&ctx);
                const EVP_CIPHER *cipher = EVP_aes_256_ofb();

                EVP_EncryptInit(&ctx, cipher, key, iv);
                EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen);
                EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen);
                ...
                EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen);
                EVP_EncryptFinal(&ctx, out, &outlen);

                EVP_CIPHER_CTX_cleanup(&ctx);




Oct. 17, 2008         Network and Information Security Lab, Peking University   Guan Zhi
EVP Symmetric Encryption
                #include <openssl/evp.h>

                EVP_CIPHER_CTX ctx;
                EVP_CIPHER_CTX_init(&ctx);
                const EVP_CIPHER *cipher = EVP_aes_128_cbc();

                EVP_EncryptInit(&ctx, cipher, key, iv);
                EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen);
                EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen);
                ...
                EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen);
                EVP_EncryptFinal(&ctx, out, &outlen);

                EVP_CIPHER_CTX_cleanup(&ctx);




Oct. 17, 2008         Network and Information Security Lab, Peking University   Guan Zhi
EVP Symmetric Decryption
   #include <openssl/evp.h>

   EVP_CIPHER_CTX ctx;
   EVP_CIPHER_CTX_init(&ctx);
   const EVP_CIPHER *cipher = EVP_aes_128_cbc();

   EVP_DecryptInit(&ctx, cipher, key, iv);
   EVP_DecryptUpdate(&ctx, out, &outlen, in, inlen);
   EVP_DecryptUpdate(&ctx, out, &outlen, in, inlen);
   ...
   EVP_DecryptUpdate(&ctx, out, &outlen, in, inlen);
   EVP_DecryptFinal(&ctx, out, &outlen);

   EVP_CIPHER_CTX_cleanup(&ctx);




Oct. 17, 2008                 Network and Information Security Lab, Peking University   Guan Zhi
EVP With Engine
   #include <openssl/evp.h>

   EVP_CIPHER_CTX ctx;
   EVP_CIPHER_CTX_init(&ctx);
   const EVP_CIPHER *cipher = EVP_aes_128_cbc();

   EVP_EncryptInit_ex(&ctx, cipher, engine, key, iv);
   EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen);
   EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen);
   ...
   EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen);
   EVP_EncryptFinal_ex(&ctx, out, &outlen);

   EVP_CIPHER_CTX_cleanup(&ctx);




Oct. 17, 2008                  Network and Information Security Lab, Peking University   Guan Zhi
EVP_CIPHER Interface
  struct evp_cipher_st {
  
     int nid;
  
     int block_size;
  
     int key_len;
        int iv_len;
  
     unsigned long flags;
  
     int (*init)(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc);
  
     int (*do_cipher)(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, unsigned int inl);
  
     int (*cleanup)(EVP_CIPHER_CTX *);
  
     int ctx_size;
  
     int (*set_asn1_parameters)(EVP_CIPHER_CTX *, ASN1_TYPE *);
  
     int (*get_asn1_parameters)(EVP_CIPHER_CTX *, ASN1_TYPE *);
  
     int (*ctrl)(EVP_CIPHER_CTX *, int type, int arg, void *ptr);
  
     void *app_data;
  } EVP_CIPHER;



Oct. 17, 2008                Network and Information Security Lab, Peking University          Guan Zhi
EVP_CIPHER Interface
  struct evp_cipher_st {
  
     int nid;
  
     int block_size;
  
     int key_len;
        int iv_len;
  
     unsigned long flags;
  
     int (*init)(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc);
  
     int (*do_cipher)(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, unsigned int inl);
  
     int (*cleanup)(EVP_CIPHER_CTX *);
  
     int ctx_size;
  
     int (*set_asn1_parameters)(EVP_CIPHER_CTX *, ASN1_TYPE *);
  
     int (*get_asn1_parameters)(EVP_CIPHER_CTX *, ASN1_TYPE *);
  
     int (*ctrl)(EVP_CIPHER_CTX *, int type, int arg, void *ptr);
  
     void *app_data;
  } EVP_CIPHER;



Oct. 17, 2008                Network and Information Security Lab, Peking University          Guan Zhi
EVP Digest
   #include <openssl/evp.h>

   EVP_MD_CTX ctx;
   EVP_MD_CTX_init(&ctx);
   const EVP_MD *md = EVP_sha1();

   EVP_DigestInit(&ctx, md);
   EVP_DigestUpdate(&ctx, in, inlen);
   EVP_DigestUpdate(&ctx, in, inlen);
   ...
   EVP_DigestUpdate(&ctx, in, inlen);
   EVP_DigestFinal(&ctx, digest, &digest_len);

   EVP_MD_CTX_cleanup(&ctx);




Oct. 17, 2008                 Network and Information Security Lab, Peking University   Guan Zhi
EVP_MD
   struct env_md_st {
   
     int type;
   
     int pkey_type;
   
     int md_size;
   
     unsigned long flags;
   
     int (*init)(EVP_MD_CTX *ctx);
   
     int (*update)(EVP_MD_CTX *ctx,const void *data,size_t count);
   
     int (*final)(EVP_MD_CTX *ctx,unsigned char *md);
   
     int (*copy)(EVP_MD_CTX *to,const EVP_MD_CTX *from);
   
     int (*cleanup)(EVP_MD_CTX *ctx);
   
     int required_pkey_type[5];
   
     int block_size;
   
     int ctx_size;
   } EVP_MD;




Oct. 17, 2008                Network and Information Security Lab, Peking University   Guan Zhi
EVP Public Key API
    EVP_SignInit_ex()
    EVP_SignInit()
    EVP_SignUpdate()
    EVP_SingFinal()

    EVP_VerifyInit_ex()
    EVP_VerifyInit()
    EVP_VerifyUpdate()
    EVP_VerifyFinal()




Oct. 17, 2008             Network and Information Security Lab, Peking University   Guan Zhi
Error Stack

      Push Error               Pop Error




                   . Error n
                     ......
                   Error 2
                   Error 1

                Error Stack




Oct. 17, 2008                    Network and Information Security Lab, Peking University   Guan Zhi
BIO: Abstract IO Interface
                   Input                 BIO_s_mem(),
                                         BIO_s_file(), BIO_s_fd()
                Source BIO               BIO_s_socket(), BIO_s_accept(), BIO_s_connect()
                                         BIO_s_bio(), BIO_s_null()
                Filter BIO 1


                                        BIO_f_base64(), BIO_f_buffer(), BIO_f_cipher()
                Filter BIO n
                                        BIO_f_md(), BIO_f_null(), BIO_f_ssl()

                 Sink BIO


                  Output




Oct. 17, 2008                  Network and Information Security Lab, Peking University     Guan Zhi
BIO Example, Base64

                BIO *bio, *b64;
                char message[] = quot;Hello World nquot;;

                b64 = BIO_new(BIO_f_base64());
                bio = BIO_new_fp(stdout, BIO_NOCLOSE);
                bio = BIO_push(b64, bio);
                BIO_write(bio, message, strlen(message));
                BIO_flush(bio);

                BIO_free_all(bio);




Oct. 17, 2008         Network and Information Security Lab, Peking University   Guan Zhi
Program Secure Code



Oct. 17, 2008   Network and Information Security Lab, Peking University   Guan Zhi
Random Numbers
   •       Random numbers are widely used in cryptography:
       ❖ public key generation, symmetric encryption keys,
                MAC keys, symmetric encryption initial vector
                (IV)salt, nonce

   •       Random numbers must be generated from
           Cryptographic Random Number Generator (RNG), not
           C rand() function!

   •       OpenSSL RNG,




Oct. 17, 2008             Network and Information Security Lab, Peking University   Guan Zhi
Random Numbers (cont.)
   •       TRNG service from operating system, CryptGenRandom
       ❖ /dev/random on Linux (NOT /dev/urandom)
       ❖ CryptGenRandom() on Windows

   •       TRNG service from hardware device, such as from USB
           tokens, crypto accelerators and smart cards through
           PKCS #11 or MS Crypto API interface.

   •       TRNG service from OpenSSL rand interface.




Oct. 17, 2008          Network and Information Security Lab, Peking University   Guan Zhi
Recommended Key Length
   •       Symmetric encryption, AES, 128-bit

   •       Digest algorithm, SHA-256

   •       HMAC key, same to digest algorithm, 256-bit

   •       RSA 1024-bit or 2048-bit

   •       ECC 192-bit




Oct. 17, 2008            Network and Information Security Lab, Peking University   Guan Zhi
Keep Secrets in Memory
   •       Never hard code secrets in a program.

   •       Secret data of one process/user may be read by other
           process or user. The live time of a session key should be
           as short as possible.

   •       Data may be swapped to disk. Use system calls to lock
           the key’s memory.

   •       Data remain in memory even after the RAM is
           powered off for 5 minutes. After the cryptographic
           operation, the keys should be securely cleaned from the
           memory.

Oct. 17, 2008           Network and Information Security Lab, Peking University   Guan Zhi
Frozen Attack



      Figure 5: Before powering off the computer, we spray an upside-down canister of multipurpose duster directly onto the
      memory chips, cooling them to 50 C. At this temperature, the data will persist for several minutes after power loss
      with minimal error, even if we remove the DIMM from the computer.


      Simple reboots The simplest attack is to reboot the            the target machine and place it into the secondary DIMM
      machine and configure the BIOS to boot the imaging              slot (in the same machine or another machine), effectively
      tool. A warm boot, invoked with the operating system’s         remapping the data to be imaged into a different part of
      restart procedure, will normally ensure that the memory        the address space.
      has no chance to decay, though software will have an
      opportunity to wipe sensitive data prior to shutdown. A
                                                                     5 Key Reconstruction
      cold boot, initiated using the system’s restart switch or by
      briefly removing and restoring power, will result in little
                                                                     Our experiments (see Section 3) show that it is possible
      or no decay depending on the memory’s retention time.
                                                                     to recover memory contents with few bit errors even af-
      Restarting the system in this way denies the operating
                                                                     ter cutting power to the system for a brief time, but the
      system and applications any chance to scrub memory
                                                                     presence of even a small amount of error complicates
      before shutting down.
                                                                     the process of extracting correct cryptographic keys. In
                          after              5 seconds                  30 seconds                 60 seconds                     5 minutes
     Transferring DRAM modules Even if an attacker can-              this section we present algorithms for correcting errors
                                    Figure 4: We loaded a bitmap image into memory on Machine A, then cut power for varying lengths of time. After 5
      not force a target system to boot memory-imaging tools,        in symmetric and private keys. These algorithms can cor-
                                    seconds (left), the image is indistinguishable from the original. It gradually becomes more degraded, as shown after
      or if the target employs countermeasures that erase mem-       rect most errors quickly even in the presence of relatively
                                    30 seconds, 60 seconds, and 5 minutes.
      ory contents during boot, DIMM modules can be phys-            high bit error probabilities in the range of 5% to 50%,
      ically removed and their contents imaged using another         depending on the type of key.
                                    4 Imaging Residual Memory ıve approach to key connected to the targetbrute- via an Ethernet crossover
      computer selected by the attacker.                                A na¨                      error correction is to machine
                                                                     force search over keys with a low Hamming distance TFTP servers as well as a simple
                                                                                                   cable runs DHCP and from
         Some memory modules exhibit far faster decay than
                                    Imaging residual memoryacontentsdecayed key that was
                                                                     the requires no special
Oct. 17, 2008as we discussitin Section 3.2decay sufficientlyandboots, the memory con- retrievedevenmemoryfor but this rates up to 300data. We have
                                                                       Information Security Lab, fromwithUniversity the memory Mb/s (around
                                                                                                               memory, receiving
                                                                                                   client application
      others, but                              above, cooling
                                                    Network                                               Peking a images at                               Guan Zhi
      module before powering off can slow When the system is computationally burdensome
                                    equipment.                                                                        moderate
                                                                                                   extracted
Lock and Clean Memory
   •       Preventing memory from being paged to disk, mlock()
           on Linux, and VirtualLock() on Windows.

   •       Erasing data from memory securely and as soon as
           possible, use handwrite clean_memory() instead of
           standard libc memset().
                volatile void clean_memory( volatile void *dst, size_t len )
                {
                    volatile unsigned char *p;
                    for (p = (volatile unsigned char *)dst; len; p[--len] = 0)
                         ;
                }




Oct. 17, 2008                      Network and Information Security Lab, Peking University   Guan Zhi
Keep Secrets on Disk
   •       Never write the plaintext secrets to disk.

   •       Use cryptographic tools to encrypt the secrets with a
           password or a public key/certificate.




Oct. 17, 2008           Network and Information Security Lab, Peking University   Guan Zhi
Protect Secret Files
   •       Protect secret files with symmetric key cryptography.
       ❖ Standard: PKCS #5 password based encryption and
                MAC.
       ❖ Tools: GnuPG, OpenSSL command line tool.

   •       Protect secret files with public key cryptography.
       ❖ Standard: PKCS #7, PKCS #12
       ❖ Tools: GnuPG




Oct. 17, 2008           Network and Information Security Lab, Peking University   Guan Zhi
With Tools
   •       GunPG, an open source implementation of PGP.
       ❖ gpg -c plaintext.txt

   •       TrueCrypt, Disk encryption

   •       OpenSSL (not recommended).




Oct. 17, 2008           Network and Information Security Lab, Peking University   Guan Zhi
Wipe a File
   •       It’s hard to destroy a file on disk, even impossible.

   •       For some file systems, files are never deleted.

   •       A deleted file can be recovered even after the sector is
           written 23 times.

   •       Some tools:
       ❖ gnupg, Linux
       ❖ PGP, Windows
       ❖ ......


Oct. 17, 2008            Network and Information Security Lab, Peking University   Guan Zhi
Encrypt with Password
   •       Select a secure password.

   •       Check the validity of this password.

   •       Derive a encryption key and a MAC key from the
           password.

   •       Encrypt the plaintext with the encryption key.

   •       Generate a HMAC of the plaintext with the MAC key.

   •       Clean the plaintext, keys and password.



Oct. 17, 2008           Network and Information Security Lab, Peking University   Guan Zhi
Deriving Keys from a Password
                #include <evp.h>
                #include <openssl/rand.h>

                char *passwd = “secret password”;
                unsigned char salt[8];
                unsigned char iv[16];
                int iter = 65535;
                unsigned char key[16];
                RAND_bytes(salt, sizeof(salt));
                RAND_bytes(iv, sizeof(iv));
                PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd),
                     salt, sizeof(salt), iter, sizeof(key), key);

                AES_KEY aes_key;
                AES_set_encrypt_key(key, 128, aes_key);
                // AES encrypt routines ...



Oct. 17, 2008               Network and Information Security Lab, Peking University   Guan Zhi
Serialization Code Generation
   typedef struct privkey_st {
   
    long
 
    
            ver;
   
    ASN1_OBJECT

          *ecoid;
   
    ASN1_UTF8STRING *matrixid;
   
    ASN1_UTF8STRING
*keyid;
   
    ASN1_INTEGER
 *keydata;
   } PRIVKEY;

   ASN1_SEQUENCE(PRIVKEY) = {
   
    ASN1_SIMPLE(PRIVKEY, ver, LONG),
   
    ASN1_SIMPLE(PRIVKEY, ecoid, ASN1_OBJECT),
   
    ASN1_SIMPLE(PRIVKEY, matrixid, ASN1_UTF8STRING),
   
    ASN1_SIMPLE(PRIVKEY, keyid, ASN1_UTF8STRING),
   
    ASN1_SIMPLE(PRIVKEY, keydata, ASN1_INTEGER),
   } ASN1_SEQUENCE_END(PRIVKEY);
   IMPLEMENT_ASN1_FUNCTIONS(PRIVKEY);



Oct. 17, 2008               Network and Information Security Lab, Peking University   Guan Zhi
CPK 0.6.8
   •       A command line tool, written in C, base on OpenSSL.

   •       Provide CPK system setup, identity-based public key
           encryption/decryption, digital signature generation and
           verification.

   •       Support data types serialization, encoding with ASN.1
           syntax and DER format.

   •       The source code style is similar to openssl.




Oct. 17, 2008           Network and Information Security Lab, Peking University   Guan Zhi
E

Más contenido relacionado

La actualidad más candente

Dss digital signature standard and dsa algorithm
Dss  digital signature standard and dsa algorithmDss  digital signature standard and dsa algorithm
Dss digital signature standard and dsa algorithm
Abhishek Kesharwani
 
Network Security Nmap N Nessus
Network Security Nmap N NessusNetwork Security Nmap N Nessus
Network Security Nmap N Nessus
Utkarsh Verma
 

La actualidad más candente (20)

5. message authentication and hash function
5. message authentication and hash function5. message authentication and hash function
5. message authentication and hash function
 
Ipsec
IpsecIpsec
Ipsec
 
IP security
IP securityIP security
IP security
 
Dss digital signature standard and dsa algorithm
Dss  digital signature standard and dsa algorithmDss  digital signature standard and dsa algorithm
Dss digital signature standard and dsa algorithm
 
Email security
Email securityEmail security
Email security
 
Pgp
PgpPgp
Pgp
 
Email Security : PGP & SMIME
Email Security : PGP & SMIMEEmail Security : PGP & SMIME
Email Security : PGP & SMIME
 
Lecture 5 ip security
Lecture 5 ip securityLecture 5 ip security
Lecture 5 ip security
 
Ssh (The Secure Shell)
Ssh (The Secure Shell)Ssh (The Secure Shell)
Ssh (The Secure Shell)
 
Message Authentication
Message AuthenticationMessage Authentication
Message Authentication
 
Network Security and Cryptography
Network Security and CryptographyNetwork Security and Cryptography
Network Security and Cryptography
 
Introduction to Cryptography
Introduction to CryptographyIntroduction to Cryptography
Introduction to Cryptography
 
MD5 ALGORITHM.pptx
MD5 ALGORITHM.pptxMD5 ALGORITHM.pptx
MD5 ALGORITHM.pptx
 
Cryptography and Network Security William Stallings Lawrie Brown
Cryptography and Network Security William Stallings Lawrie BrownCryptography and Network Security William Stallings Lawrie Brown
Cryptography and Network Security William Stallings Lawrie Brown
 
Transport Layer Security (TLS)
Transport Layer Security (TLS)Transport Layer Security (TLS)
Transport Layer Security (TLS)
 
Network Security Nmap N Nessus
Network Security Nmap N NessusNetwork Security Nmap N Nessus
Network Security Nmap N Nessus
 
Openssl
OpensslOpenssl
Openssl
 
Transport layer security
Transport layer securityTransport layer security
Transport layer security
 
Traditional symmetric-key cipher
Traditional symmetric-key cipherTraditional symmetric-key cipher
Traditional symmetric-key cipher
 
Message Authentication Requirement-MAC
Message Authentication Requirement-MACMessage Authentication Requirement-MAC
Message Authentication Requirement-MAC
 

Similar a Crypto With OpenSSL

State of Crypto in Python (OSCON)
State of Crypto in Python (OSCON)State of Crypto in Python (OSCON)
State of Crypto in Python (OSCON)
jarito030506
 
CETH for XDP [Linux Meetup Santa Clara | July 2016]
CETH for XDP [Linux Meetup Santa Clara | July 2016] CETH for XDP [Linux Meetup Santa Clara | July 2016]
CETH for XDP [Linux Meetup Santa Clara | July 2016]
IO Visor Project
 
MMLSpark: Lessons from Building a SparkML-Compatible Machine Learning Library...
MMLSpark: Lessons from Building a SparkML-Compatible Machine Learning Library...MMLSpark: Lessons from Building a SparkML-Compatible Machine Learning Library...
MMLSpark: Lessons from Building a SparkML-Compatible Machine Learning Library...
Spark Summit
 

Similar a Crypto With OpenSSL (20)

OpenStack and OpenFlow Demos
OpenStack and OpenFlow DemosOpenStack and OpenFlow Demos
OpenStack and OpenFlow Demos
 
Software Defined Data Centers - June 2012
Software Defined Data Centers - June 2012Software Defined Data Centers - June 2012
Software Defined Data Centers - June 2012
 
8 Ways Network Engineers use Snabb (RIPE 77)
8 Ways Network Engineers use Snabb (RIPE 77)8 Ways Network Engineers use Snabb (RIPE 77)
8 Ways Network Engineers use Snabb (RIPE 77)
 
QsNetIII, An HPC Interconnect For Peta Scale Systems
QsNetIII, An HPC Interconnect For Peta Scale SystemsQsNetIII, An HPC Interconnect For Peta Scale Systems
QsNetIII, An HPC Interconnect For Peta Scale Systems
 
Node.js Explained
Node.js ExplainedNode.js Explained
Node.js Explained
 
Scaling the Container Dataplane
Scaling the Container Dataplane Scaling the Container Dataplane
Scaling the Container Dataplane
 
The Potential Impact of Software Defined Networking SDN on Security
The Potential Impact of Software Defined Networking SDN on SecurityThe Potential Impact of Software Defined Networking SDN on Security
The Potential Impact of Software Defined Networking SDN on Security
 
Tomcat openssl
Tomcat opensslTomcat openssl
Tomcat openssl
 
Learning the basics of Apache NiFi for iot OSS Europe 2020
Learning the basics of Apache NiFi for iot OSS Europe 2020Learning the basics of Apache NiFi for iot OSS Europe 2020
Learning the basics of Apache NiFi for iot OSS Europe 2020
 
State of Crypto in Python (OSCON)
State of Crypto in Python (OSCON)State of Crypto in Python (OSCON)
State of Crypto in Python (OSCON)
 
Porting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to RustPorting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to Rust
 
CETH for XDP [Linux Meetup Santa Clara | July 2016]
CETH for XDP [Linux Meetup Santa Clara | July 2016] CETH for XDP [Linux Meetup Santa Clara | July 2016]
CETH for XDP [Linux Meetup Santa Clara | July 2016]
 
Introduction to DPDK
Introduction to DPDKIntroduction to DPDK
Introduction to DPDK
 
Elixir Berlin 2019: Dominic Letz on Doing Blockchain with Elixir
Elixir Berlin 2019: Dominic Letz on Doing Blockchain with ElixirElixir Berlin 2019: Dominic Letz on Doing Blockchain with Elixir
Elixir Berlin 2019: Dominic Letz on Doing Blockchain with Elixir
 
6 open capi_meetup_in_japan_final
6 open capi_meetup_in_japan_final6 open capi_meetup_in_japan_final
6 open capi_meetup_in_japan_final
 
MMLSpark: Lessons from Building a SparkML-Compatible Machine Learning Library...
MMLSpark: Lessons from Building a SparkML-Compatible Machine Learning Library...MMLSpark: Lessons from Building a SparkML-Compatible Machine Learning Library...
MMLSpark: Lessons from Building a SparkML-Compatible Machine Learning Library...
 
Network Stack in Userspace (NUSE)
Network Stack in Userspace (NUSE)Network Stack in Userspace (NUSE)
Network Stack in Userspace (NUSE)
 
Network Programming: Data Plane Development Kit (DPDK)
Network Programming: Data Plane Development Kit (DPDK)Network Programming: Data Plane Development Kit (DPDK)
Network Programming: Data Plane Development Kit (DPDK)
 
Dataplane networking acceleration with OpenDataplane / Максим Уваров (Linaro)
Dataplane networking acceleration with OpenDataplane / Максим Уваров (Linaro)Dataplane networking acceleration with OpenDataplane / Максим Уваров (Linaro)
Dataplane networking acceleration with OpenDataplane / Максим Уваров (Linaro)
 
OSS EU: Deep Dive into Building Streaming Applications with Apache Pulsar
OSS EU:  Deep Dive into Building Streaming Applications with Apache PulsarOSS EU:  Deep Dive into Building Streaming Applications with Apache Pulsar
OSS EU: Deep Dive into Building Streaming Applications with Apache Pulsar
 

Más de Zhi Guan

USB Token Design and Implementation
USB Token Design and ImplementationUSB Token Design and Implementation
USB Token Design and Implementation
Zhi Guan
 
CPK Theory And Parctice
CPK Theory And ParcticeCPK Theory And Parctice
CPK Theory And Parctice
Zhi Guan
 
CPK Cryptosystem In Solaris
CPK Cryptosystem In SolarisCPK Cryptosystem In Solaris
CPK Cryptosystem In Solaris
Zhi Guan
 
Graphical Passwords
Graphical PasswordsGraphical Passwords
Graphical Passwords
Zhi Guan
 
CPK in Eurocrypt 2007 Rump Session
CPK in Eurocrypt 2007 Rump SessionCPK in Eurocrypt 2007 Rump Session
CPK in Eurocrypt 2007 Rump Session
Zhi Guan
 
A Survey of Identity-Based Encryption
A Survey of Identity-Based EncryptionA Survey of Identity-Based Encryption
A Survey of Identity-Based Encryption
Zhi Guan
 
Ph D Proposal, Cloud Computing Security
Ph D Proposal, Cloud Computing SecurityPh D Proposal, Cloud Computing Security
Ph D Proposal, Cloud Computing Security
Zhi Guan
 
Red Office Documents Security Proposal
Red Office Documents Security ProposalRed Office Documents Security Proposal
Red Office Documents Security Proposal
Zhi Guan
 
ICDCS‘08 WebIBC
ICDCS‘08 WebIBCICDCS‘08 WebIBC
ICDCS‘08 WebIBC
Zhi Guan
 
Code Signing with CPK
Code Signing with CPKCode Signing with CPK
Code Signing with CPK
Zhi Guan
 

Más de Zhi Guan (11)

USB Token Design and Implementation
USB Token Design and ImplementationUSB Token Design and Implementation
USB Token Design and Implementation
 
CPK Theory And Parctice
CPK Theory And ParcticeCPK Theory And Parctice
CPK Theory And Parctice
 
CPK Cryptosystem In Solaris
CPK Cryptosystem In SolarisCPK Cryptosystem In Solaris
CPK Cryptosystem In Solaris
 
Easy CPK
Easy CPKEasy CPK
Easy CPK
 
Graphical Passwords
Graphical PasswordsGraphical Passwords
Graphical Passwords
 
CPK in Eurocrypt 2007 Rump Session
CPK in Eurocrypt 2007 Rump SessionCPK in Eurocrypt 2007 Rump Session
CPK in Eurocrypt 2007 Rump Session
 
A Survey of Identity-Based Encryption
A Survey of Identity-Based EncryptionA Survey of Identity-Based Encryption
A Survey of Identity-Based Encryption
 
Ph D Proposal, Cloud Computing Security
Ph D Proposal, Cloud Computing SecurityPh D Proposal, Cloud Computing Security
Ph D Proposal, Cloud Computing Security
 
Red Office Documents Security Proposal
Red Office Documents Security ProposalRed Office Documents Security Proposal
Red Office Documents Security Proposal
 
ICDCS‘08 WebIBC
ICDCS‘08 WebIBCICDCS‘08 WebIBC
ICDCS‘08 WebIBC
 
Code Signing with CPK
Code Signing with CPKCode Signing with CPK
Code Signing with CPK
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 

Crypto With OpenSSL

  • 1. Crypto with OpenSSL GUAN Zhi guanzhi@infosec.pku.edu.cn Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 2. Outline • OpenSSL Programing • Program secure code tips • CPK version 0.6.8 source code organization • CPK version 0.7 new features Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 3. OpenSSL Programming Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 4. What is OpenSSL? • Cryptography tool kit. • Open source implementation of SSL v2/v3 and TLS v1. • PKI/CA, cryptographic command line tools. Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 5. OpenSSL Includes • Source code, http://www.openssl.org/source/ (release) or ftp://ftp.openssl.org/snapshot/ (snapshot) • Include header files, #include <openssl/des.h> or /usr/src/include/openssl/ • libraries, libeay32.[lib|dll], ssleay32.[lib/dll] (Win32) or libcrypto.[so|a], libssl.[so|a] (Linux). • executable binary: openssl[.exe] Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 6. Command Line Tool • The openssl program is a command line tool for using the various cryptography functions of OpenSSL’s crypto library from the shell. It can be used for ❖ – Creation of RSA, DH and DSA key parameters ❖ – Creation of X.509 certificates, CSRs and CRLs ❖ – Calculation of Message Digests ❖ – Encryption and Decryption with Ciphers ❖ – SSL/TLS Client and Server Tests ❖ – Handling of S/MIME signed or encrypted mail Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 7. Supported PKI Standards • ASN.1 encoding • SSLv2, SSLv3, TLSv1 • PKCS #5, PKCS #7, PKCS #8, PKCS #12, X.509v3 • OCSP • PEM Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 8. Supported Algorithms • Block ciphers: AES, DES, 3DES, Blowfish, Camellia, CAST, Idea, RC2, RC5. • Block cipher modes: ECB, CBC, CFB, OFB, CTR ... • Stream ciphers: RC4 • Digest algorithms: MD2, MD4, MD5, SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, Ripemd-160. • MAC: HMAC, MDC2 • Public key crypto-systems: DH, DSA, RSA, ECC. Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 9. OpenSSL License • OpenSSL is licensed under Apache style license, free to get and use it for commercial and non-commercial purposes subject to some simple license conditions. • Redistributions of any form what so ever must retain the following acknowledgment: ❖ quot;This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/)quot; Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 10. Download, Build and Install ❖ $ ./config ❖ $ make ❖ $ make test ❖ $ make install • Download the source code from *official* openssl homepage. • The *make test* step is very important! In some platforms this step may fail. Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 11. Source Code • openssl/apps/ openssl command line tool • openssl/crypto/ libcrypto crypto library • openssl/ssl/ libssl SSL/TLS library • openssl/demos/ some examples • openssl/docs/ man pages and howtos • openssl/engines/ hardware crypto accelerator drivers • openssl/include/ include header files Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 12. Source Code • openssl/MACOS,ms,Netware,os2,VMS/ platform specific • openssl/test/ code for make test, important. • openssl/times/ code for ``openssl speed’’ benchmark • openssl/tools/ • openssl/util/ perl shells for C code generation Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 13. openssl/crypto/* Public Key Crypto Ciphers Data Structure RNG PKI bn aes Utilities buffer Hash Algors and seed asn1 MACs dh bf lhash bio rand krb5 hmac dsa camellia pqueue engine objects md2 dso cast CLI stack err ocsp ui md4 ec des store evp pem conf md5 ecdh idea txt_db threads pkcs7 mdc2 ecdsa rc2 pkcs12 Compression ripemd SSL/TLS rsa rc4 x509 comp ssl sha rc5 x509v3 Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 14. Architecture of OpenSSL Command Line Interface SSL/TLS EVP Crypto API BIO ERR Error Data Abstract Handling Structure Soft Crypto Impl Engine API I/O Hard Crypto Accelerator Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 15. Crypto API • Microsoft Crypto API • RSA PKCS #11: Cryptographic Token Interface Standard • OpenGroup Common Security: CDSA and CSSM • OpenSSL EVP interface ❖ Change different cipher algorithms without change the source code. Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 16. EVP Symmetric Encryption #include <openssl/evp.h> EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_init(&ctx); const EVP_CIPHER *cipher = EVP_aes_128_cbc(); EVP_EncryptInit(&ctx, cipher, key, iv); EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen); EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen); ... EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen); EVP_EncryptFinal(&ctx, out, &outlen); EVP_CIPHER_CTX_cleanup(&ctx); Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 17. EVP Symmetric Encryption #include <openssl/evp.h> EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_init(&ctx); const EVP_CIPHER *cipher = EVP_aes_128_cbc(); EVP_EncryptInit(&ctx, cipher, key, iv); EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen); EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen); ... EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen); EVP_EncryptFinal(&ctx, out, &outlen); EVP_CIPHER_CTX_cleanup(&ctx); Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 18. EVP Symmetric Encryption #include <openssl/evp.h> EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_init(&ctx); const EVP_CIPHER *cipher = EVP_aes_256_ofb(); EVP_EncryptInit(&ctx, cipher, key, iv); EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen); EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen); ... EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen); EVP_EncryptFinal(&ctx, out, &outlen); EVP_CIPHER_CTX_cleanup(&ctx); Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 19. EVP Symmetric Encryption #include <openssl/evp.h> EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_init(&ctx); const EVP_CIPHER *cipher = EVP_aes_128_cbc(); EVP_EncryptInit(&ctx, cipher, key, iv); EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen); EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen); ... EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen); EVP_EncryptFinal(&ctx, out, &outlen); EVP_CIPHER_CTX_cleanup(&ctx); Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 20. EVP Symmetric Decryption #include <openssl/evp.h> EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_init(&ctx); const EVP_CIPHER *cipher = EVP_aes_128_cbc(); EVP_DecryptInit(&ctx, cipher, key, iv); EVP_DecryptUpdate(&ctx, out, &outlen, in, inlen); EVP_DecryptUpdate(&ctx, out, &outlen, in, inlen); ... EVP_DecryptUpdate(&ctx, out, &outlen, in, inlen); EVP_DecryptFinal(&ctx, out, &outlen); EVP_CIPHER_CTX_cleanup(&ctx); Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 21. EVP With Engine #include <openssl/evp.h> EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_init(&ctx); const EVP_CIPHER *cipher = EVP_aes_128_cbc(); EVP_EncryptInit_ex(&ctx, cipher, engine, key, iv); EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen); EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen); ... EVP_EncryptUpdate(&ctx, out, &outlen, in, inlen); EVP_EncryptFinal_ex(&ctx, out, &outlen); EVP_CIPHER_CTX_cleanup(&ctx); Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 22. EVP_CIPHER Interface struct evp_cipher_st { int nid; int block_size; int key_len; int iv_len; unsigned long flags; int (*init)(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); int (*do_cipher)(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, unsigned int inl); int (*cleanup)(EVP_CIPHER_CTX *); int ctx_size; int (*set_asn1_parameters)(EVP_CIPHER_CTX *, ASN1_TYPE *); int (*get_asn1_parameters)(EVP_CIPHER_CTX *, ASN1_TYPE *); int (*ctrl)(EVP_CIPHER_CTX *, int type, int arg, void *ptr); void *app_data; } EVP_CIPHER; Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 23. EVP_CIPHER Interface struct evp_cipher_st { int nid; int block_size; int key_len; int iv_len; unsigned long flags; int (*init)(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); int (*do_cipher)(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, unsigned int inl); int (*cleanup)(EVP_CIPHER_CTX *); int ctx_size; int (*set_asn1_parameters)(EVP_CIPHER_CTX *, ASN1_TYPE *); int (*get_asn1_parameters)(EVP_CIPHER_CTX *, ASN1_TYPE *); int (*ctrl)(EVP_CIPHER_CTX *, int type, int arg, void *ptr); void *app_data; } EVP_CIPHER; Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 24. EVP Digest #include <openssl/evp.h> EVP_MD_CTX ctx; EVP_MD_CTX_init(&ctx); const EVP_MD *md = EVP_sha1(); EVP_DigestInit(&ctx, md); EVP_DigestUpdate(&ctx, in, inlen); EVP_DigestUpdate(&ctx, in, inlen); ... EVP_DigestUpdate(&ctx, in, inlen); EVP_DigestFinal(&ctx, digest, &digest_len); EVP_MD_CTX_cleanup(&ctx); Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 25. EVP_MD struct env_md_st { int type; int pkey_type; int md_size; unsigned long flags; int (*init)(EVP_MD_CTX *ctx); int (*update)(EVP_MD_CTX *ctx,const void *data,size_t count); int (*final)(EVP_MD_CTX *ctx,unsigned char *md); int (*copy)(EVP_MD_CTX *to,const EVP_MD_CTX *from); int (*cleanup)(EVP_MD_CTX *ctx); int required_pkey_type[5]; int block_size; int ctx_size; } EVP_MD; Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 26. EVP Public Key API EVP_SignInit_ex() EVP_SignInit() EVP_SignUpdate() EVP_SingFinal() EVP_VerifyInit_ex() EVP_VerifyInit() EVP_VerifyUpdate() EVP_VerifyFinal() Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 27. Error Stack Push Error Pop Error . Error n ...... Error 2 Error 1 Error Stack Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 28. BIO: Abstract IO Interface Input BIO_s_mem(), BIO_s_file(), BIO_s_fd() Source BIO BIO_s_socket(), BIO_s_accept(), BIO_s_connect() BIO_s_bio(), BIO_s_null() Filter BIO 1 BIO_f_base64(), BIO_f_buffer(), BIO_f_cipher() Filter BIO n BIO_f_md(), BIO_f_null(), BIO_f_ssl() Sink BIO Output Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 29. BIO Example, Base64 BIO *bio, *b64; char message[] = quot;Hello World nquot;; b64 = BIO_new(BIO_f_base64()); bio = BIO_new_fp(stdout, BIO_NOCLOSE); bio = BIO_push(b64, bio); BIO_write(bio, message, strlen(message)); BIO_flush(bio); BIO_free_all(bio); Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 30. Program Secure Code Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 31. Random Numbers • Random numbers are widely used in cryptography: ❖ public key generation, symmetric encryption keys, MAC keys, symmetric encryption initial vector (IV)salt, nonce • Random numbers must be generated from Cryptographic Random Number Generator (RNG), not C rand() function! • OpenSSL RNG, Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 32. Random Numbers (cont.) • TRNG service from operating system, CryptGenRandom ❖ /dev/random on Linux (NOT /dev/urandom) ❖ CryptGenRandom() on Windows • TRNG service from hardware device, such as from USB tokens, crypto accelerators and smart cards through PKCS #11 or MS Crypto API interface. • TRNG service from OpenSSL rand interface. Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 33. Recommended Key Length • Symmetric encryption, AES, 128-bit • Digest algorithm, SHA-256 • HMAC key, same to digest algorithm, 256-bit • RSA 1024-bit or 2048-bit • ECC 192-bit Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 34. Keep Secrets in Memory • Never hard code secrets in a program. • Secret data of one process/user may be read by other process or user. The live time of a session key should be as short as possible. • Data may be swapped to disk. Use system calls to lock the key’s memory. • Data remain in memory even after the RAM is powered off for 5 minutes. After the cryptographic operation, the keys should be securely cleaned from the memory. Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 35. Frozen Attack Figure 5: Before powering off the computer, we spray an upside-down canister of multipurpose duster directly onto the memory chips, cooling them to 50 C. At this temperature, the data will persist for several minutes after power loss with minimal error, even if we remove the DIMM from the computer. Simple reboots The simplest attack is to reboot the the target machine and place it into the secondary DIMM machine and configure the BIOS to boot the imaging slot (in the same machine or another machine), effectively tool. A warm boot, invoked with the operating system’s remapping the data to be imaged into a different part of restart procedure, will normally ensure that the memory the address space. has no chance to decay, though software will have an opportunity to wipe sensitive data prior to shutdown. A 5 Key Reconstruction cold boot, initiated using the system’s restart switch or by briefly removing and restoring power, will result in little Our experiments (see Section 3) show that it is possible or no decay depending on the memory’s retention time. to recover memory contents with few bit errors even af- Restarting the system in this way denies the operating ter cutting power to the system for a brief time, but the system and applications any chance to scrub memory presence of even a small amount of error complicates before shutting down. the process of extracting correct cryptographic keys. In after 5 seconds 30 seconds 60 seconds 5 minutes Transferring DRAM modules Even if an attacker can- this section we present algorithms for correcting errors Figure 4: We loaded a bitmap image into memory on Machine A, then cut power for varying lengths of time. After 5 not force a target system to boot memory-imaging tools, in symmetric and private keys. These algorithms can cor- seconds (left), the image is indistinguishable from the original. It gradually becomes more degraded, as shown after or if the target employs countermeasures that erase mem- rect most errors quickly even in the presence of relatively 30 seconds, 60 seconds, and 5 minutes. ory contents during boot, DIMM modules can be phys- high bit error probabilities in the range of 5% to 50%, ically removed and their contents imaged using another depending on the type of key. 4 Imaging Residual Memory ıve approach to key connected to the targetbrute- via an Ethernet crossover computer selected by the attacker. A na¨ error correction is to machine force search over keys with a low Hamming distance TFTP servers as well as a simple cable runs DHCP and from Some memory modules exhibit far faster decay than Imaging residual memoryacontentsdecayed key that was the requires no special Oct. 17, 2008as we discussitin Section 3.2decay sufficientlyandboots, the memory con- retrievedevenmemoryfor but this rates up to 300data. We have Information Security Lab, fromwithUniversity the memory Mb/s (around memory, receiving client application others, but above, cooling Network Peking a images at Guan Zhi module before powering off can slow When the system is computationally burdensome equipment. moderate extracted
  • 36. Lock and Clean Memory • Preventing memory from being paged to disk, mlock() on Linux, and VirtualLock() on Windows. • Erasing data from memory securely and as soon as possible, use handwrite clean_memory() instead of standard libc memset(). volatile void clean_memory( volatile void *dst, size_t len ) { volatile unsigned char *p; for (p = (volatile unsigned char *)dst; len; p[--len] = 0) ; } Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 37. Keep Secrets on Disk • Never write the plaintext secrets to disk. • Use cryptographic tools to encrypt the secrets with a password or a public key/certificate. Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 38. Protect Secret Files • Protect secret files with symmetric key cryptography. ❖ Standard: PKCS #5 password based encryption and MAC. ❖ Tools: GnuPG, OpenSSL command line tool. • Protect secret files with public key cryptography. ❖ Standard: PKCS #7, PKCS #12 ❖ Tools: GnuPG Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 39. With Tools • GunPG, an open source implementation of PGP. ❖ gpg -c plaintext.txt • TrueCrypt, Disk encryption • OpenSSL (not recommended). Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 40. Wipe a File • It’s hard to destroy a file on disk, even impossible. • For some file systems, files are never deleted. • A deleted file can be recovered even after the sector is written 23 times. • Some tools: ❖ gnupg, Linux ❖ PGP, Windows ❖ ...... Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 41. Encrypt with Password • Select a secure password. • Check the validity of this password. • Derive a encryption key and a MAC key from the password. • Encrypt the plaintext with the encryption key. • Generate a HMAC of the plaintext with the MAC key. • Clean the plaintext, keys and password. Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 42. Deriving Keys from a Password #include <evp.h> #include <openssl/rand.h> char *passwd = “secret password”; unsigned char salt[8]; unsigned char iv[16]; int iter = 65535; unsigned char key[16]; RAND_bytes(salt, sizeof(salt)); RAND_bytes(iv, sizeof(iv)); PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, sizeof(salt), iter, sizeof(key), key); AES_KEY aes_key; AES_set_encrypt_key(key, 128, aes_key); // AES encrypt routines ... Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 43. Serialization Code Generation typedef struct privkey_st { long ver; ASN1_OBJECT *ecoid; ASN1_UTF8STRING *matrixid; ASN1_UTF8STRING *keyid; ASN1_INTEGER *keydata; } PRIVKEY; ASN1_SEQUENCE(PRIVKEY) = { ASN1_SIMPLE(PRIVKEY, ver, LONG), ASN1_SIMPLE(PRIVKEY, ecoid, ASN1_OBJECT), ASN1_SIMPLE(PRIVKEY, matrixid, ASN1_UTF8STRING), ASN1_SIMPLE(PRIVKEY, keyid, ASN1_UTF8STRING), ASN1_SIMPLE(PRIVKEY, keydata, ASN1_INTEGER), } ASN1_SEQUENCE_END(PRIVKEY); IMPLEMENT_ASN1_FUNCTIONS(PRIVKEY); Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 44. CPK 0.6.8 • A command line tool, written in C, base on OpenSSL. • Provide CPK system setup, identity-based public key encryption/decryption, digital signature generation and verification. • Support data types serialization, encoding with ASN.1 syntax and DER format. • The source code style is similar to openssl. Oct. 17, 2008 Network and Information Security Lab, Peking University Guan Zhi
  • 45. E