Top Banner
Guan Zhi Network and Information Security Lab, Peking University Oct. 17, 2008 Crypto with OpenSSL GUAN Zhi [email protected]
67
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

Crypto with OpenSSLGUAN Zhi

[email protected]

Page 2: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

Outline

• OpenSSL Programing

• Program secure code tips

• CPK version 0.6.8 source code organization

• CPK version 0.7 new features

Page 3: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

OpenSSL Programming

Page 4: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

What is OpenSSL?

• Cryptography tool kit.

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

• PKI/CA, cryptographic command line tools.

Page 5: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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]

Page 6: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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

Page 7: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

Supported PKI Standards

• ASN.1 encoding

• SSLv2, SSLv3, TLSv1

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

• OCSP

• PEM

Page 8: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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.

Page 9: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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:

❖ "This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/)"

Page 10: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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.

Page 11: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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

Page 12: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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

Page 13: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

hmac

md2

md4

md5

mdc2

ripemd

sha

aes

bf

camellia

cast

des

idea

rc2

rc4

rc5

Ciphers

Hash Algors and MACs

bn

dh

dsa

dso

ec

ecdh

ecdsa

rsa

Public Key Crypto

asn1

krb5

objects

ocsp

pem

pkcs7

pkcs12

x509

x509v3

PKI

bio

engine

err

evp

threads

Utilitiesbuffer

lhash

pqueue

stack

store

txt_db

Data Structure

ssl

SSL/TLS

seed

rand

ui

conf

comp

RNG

CLI

Compression

openssl/crypto/*

Page 14: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

Architecture of OpenSSL

Command Line Interface

EVP Crypto API

ERR Error HandlingSoft Crypto Impl Engine API

BIO Abstract

I/O

Data Structure

SSL/TLS

Hard Crypto Accelerator

Page 15: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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.

Page 16: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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);

Page 17: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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);

Page 18: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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);

Page 19: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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);

Page 20: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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);

Page 21: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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);

Page 22: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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;

EVP_CIPHER Interface

Page 23: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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;

EVP_CIPHER Interface

Page 24: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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);

Page 25: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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;

Page 26: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

EVP Public Key APIEVP_SignInit_ex()EVP_SignInit()EVP_SignUpdate()EVP_SingFinal()

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

Page 27: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

Error Stack

. Error n

......

Error 2

Error 1

Error Stack

Push Error Pop Error

Page 28: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

BIO: Abstract IO Interface

Source BIO

Filter BIO 1

Filter BIO n

Sink BIO

Input

Output

BIO_s_mem(),

BIO_f_base64(), BIO_f_buffer(), BIO_f_cipher()

BIO_f_md(), BIO_f_null(), BIO_f_ssl()

BIO_s_file(), BIO_s_fd()

BIO_s_socket(), BIO_s_accept(), BIO_s_connect()

BIO_s_bio(), BIO_s_null()

Page 29: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

BIO Example, Base64

BIO *bio, *b64; char message[] = "Hello World \n";

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);

Page 30: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

Program Secure Code

Page 31: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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,

Page 32: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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.

Page 33: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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

Page 34: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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.

Page 35: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

Frozen Attack

USENIX Association 17th USENIX Security Symposium 51

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

Simple reboots The simplest attack is to reboot themachine and configure the BIOS to boot the imagingtool. A warm boot, invoked with the operating system’srestart procedure, will normally ensure that the memoryhas no chance to decay, though software will have anopportunity to wipe sensitive data prior to shutdown. Acold boot, initiated using the system’s restart switch or bybriefly removing and restoring power, will result in littleor no decay depending on the memory’s retention time.Restarting the system in this way denies the operatingsystem and applications any chance to scrub memorybefore shutting down.

Transferring DRAM modules Even if an attacker can-not force a target system to boot memory-imaging tools,or if the target employs countermeasures that erase mem-ory contents during boot, DIMM modules can be phys-ically removed and their contents imaged using anothercomputer selected by the attacker.

Some memory modules exhibit far faster decay thanothers, but as we discuss in Section 3.2 above, cooling amodule before powering it off can slow decay sufficientlyto allow it to be transferred to another machine with mini-mal decay. Widely-available “canned air” dusters, usuallycontaining a compressed fluorohydrocarbon refrigerant,can easily be used for this purpose. When the can is dis-charged in an inverted position, as shown in Figure 5, itdispenses its contents in liquid form instead of as a gas.The rapid drop in pressure inside the can lowers the tem-perature of the discharge, and the subsequent evaporationof the refrigerant causes a further chilling. By sprayingthe contents directly onto memory chips, we can cool theirsurfaces to 50 C and below. If the DRAM is cooled tothis temperature before power is cut and kept cold, wecan achieve nearly lossless data recovery even after thechip is out of the computer for several minutes.

Removing the memory modules can also allow theattacker to image memory in address regions where stan-dards BIOSes load their own code during boot. The at-tacker could remove the primary memory module from

the target machine and place it into the secondary DIMMslot (in the same machine or another machine), effectivelyremapping the data to be imaged into a different part ofthe address space.

5 Key Reconstruction

Our experiments (see Section 3) show that it is possibleto recover memory contents with few bit errors even af-ter cutting power to the system for a brief time, but thepresence of even a small amount of error complicatesthe process of extracting correct cryptographic keys. Inthis section we present algorithms for correcting errorsin symmetric and private keys. These algorithms can cor-rect most errors quickly even in the presence of relativelyhigh bit error probabilities in the range of 5% to 50%,depending on the type of key.

A naı̈ve approach to key error correction is to brute-force search over keys with a low Hamming distance fromthe decayed key that was retrieved from memory, but thisis computationally burdensome even with a moderateamount of unidirectional error. As an example, if only10% of the ones have decayed to zeros in our memoryimage, the data recovered from a 256-bit key with an equalnumber of ones and zeroes has an expected Hammingdistance of 12 from the actual key, and the number ofsuch keys is 128 12

12 256.Our algorithms achieve significantly better perfor-

mance by considering data other than the raw form ofthe key. Most encryption programs speed up computationby storing data precomputed from the encryption keys—for block ciphers, this is most often a key schedule, withsubkeys for each round; for RSA, this is an extended formof the private key which includes the primes p and q andseveral other values derived from d. This data containsmuch more structure than the key itself, and we can usethis structure to efficiently reconstruct the original keyeven in the presence of errors.

These results imply an interesting trade-off between

50 17th USENIX Security Symposium USENIX Association

Figure 4: We loaded a bitmap image into memory on Machine A, then cut power for varying lengths of time. After 5seconds (left), the image is indistinguishable from the original. It gradually becomes more degraded, as shown after30 seconds, 60 seconds, and 5 minutes.

4 Imaging Residual Memory

Imaging residual memory contents requires no specialequipment. When the system boots, the memory con-troller begins refreshing the DRAM, reading and rewritingeach bit value. At this point, the values are fixed, decayhalts, and programs running on the system can read anydata present using normal memory-access instructions.

4.1 Imaging tools

One challenge is that booting the system will necessarilyoverwrite some portions of memory. Loading a full oper-ating system would be very destructive. Our approach isto use tiny special-purpose programs that, when bootedfrom either a warm or cold reset state, produce accuratedumps of memory contents to some external medium.These programs use only trivial amounts of RAM, andtheir memory offsets used can be adjusted to some extentto ensure that data structures of interest are unaffected.

Our memory-imaging tools make use of several differ-ent attack vectors to boot a system and extract the contentsof its memory. For simplicity, each saves memory imagesto the medium from which it was booted.

PXE network boot Most modern PCs support net-work booting via Intel’s Preboot Execution Environment(PXE) [25], which provides rudimentary startup and net-work services. We implemented a tiny (9 KB) standaloneapplication that can be booted via PXE and whose onlyfunction is streaming the contents of system RAM viaa UDP-based protocol. Since PXE provides a universalAPI for accessing the underlying network hardware, thesame binary image will work unmodified on any PC sys-tem with PXE support. In a typical attack setup, a laptop

connected to the target machine via an Ethernet crossovercable runs DHCP and TFTP servers as well as a simpleclient application for receiving the memory data. We haveextracted memory images at rates up to 300 Mb/s (around30 seconds for a 1 GB RAM) with gigabit Ethernet cards.

USB drives Alternatively, most PCs can boot from anexternal USB device such as a USB hard drive or flashdevice. We implemented a small (10 KB) plug-in for theSYSLINUX bootloader [3] that can be booted from anexternal USB device or a regular hard disk. It saves thecontents of system RAM into a designated data partitionon this device. We succeeded in dumping 1 GB of RAMto a flash drive in approximately 4 minutes.

EFI boot Some recent computers, including all Intel-based Macintosh computers, implement the ExtensibleFirmware Interface (EFI) instead of a PC BIOS. We havealso implemented a memory dumper as an EFI netbootapplication. We have achieved memory extraction speedsup to 136 Mb/s, and we expect it will be possible toincrease this throughput with further optimizations.

iPods We have installed memory imaging tools on anApple iPod so that it can be used to covertly capturememory dumps without impacting its functionality as amusic player. This provides a plausible way to concealthe attack in the wild.

4.2 Imaging attacks

An attacker could use imaging tools like ours in a numberof ways, depending on his level of access to the systemand the countermeasures employed by hardware and soft-ware.

5 seconds 30 seconds 60 seconds 5 minutesafter

Page 36: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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)

;}

Page 37: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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.

Page 38: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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

Page 39: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

With Tools

• GunPG, an open source implementation of PGP.

❖ gpg -c plaintext.txt

• TrueCrypt, Disk encryption

• OpenSSL (not recommended).

Page 40: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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

❖ ......

Page 41: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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.

Page 42: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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 ...

Page 43: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

Serialization Code Generationtypedef 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);

Page 44: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

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.

Page 45: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

Elliptic Curve Cryptography

• ECC basic types:

❖ Private key, big integer, BIGNUM

❖ Public key, elliptic curve point, EC_POINT

❖ Elliptic curve parameters, EC_GROUP

• ECC algorithms:

❖ ECDH, Elliptic Curve Diffie-Hellman Key Exchange

❖ ECDSA, Elliptic Curve Digital Signature Algorithm

❖ ECIES, Elliptic Curve Integrated Encryption Scheme

Page 46: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

Select an Elliptic Curve

• OpenSSL embeds a set of elliptic curves.

❖ EC_GROUP *ec = EC_GROUP_new_by_curve_name(OBJ_txt2nid(“secp192k1”));

Page 47: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

Map Identity to Matrix Indexes

• Use a Key Derive Function (KDF) to derive a fixed length output from a variable length input.

• typedef void *(*KDF)(const void *in, size_t inlen, void *out, size_t *outlen);

• X9.63 KDF

❖ x9_63_kdf_sha1()

❖ x9_63_kdf_sha256()

❖ .......

Page 48: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

Setup

• The authority generates a pair of matrix, at first the private matrix, and the corresponding public matrix from the private matrix. The public matrix is published publicly, and the private matrix is kept secretly inside the authority.

❖ PRIVMATRIX_create() ⇒ PRIVMATRIX

❖ PRIVMATRIX_gen_pubmat( PRIVMATRIX ) ⇒ PUBMATRIX

• Given a user’s identity string, the authority generates the user’s private key.

❖ PRIVMATRIX_gen_privkey( PRIVMATRIX, ID) ⇒ PRIVKEY

Page 49: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

Encrypt and Decrypt

• The sender takes recipient’s identity string and the public matrix to encrypt a message.

❖ PUBMATRIX_encrypt( PUBMATRIX, ID, PlainText ) ⇒ RCPTINFO

• The recipient use his private key to decrypt the encrypted message.

❖ PRIVKEY_decrypt( PRIVKEY, RCPTINFO ) ⇒ PlainText

Page 50: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

Sign and Verify

• The sender takes his private key to generate a signature of a message.

❖ PRIVKEY_sign( PRIVKEY, MessageDigest ) ⇒ SIGINFO

• The recipient use sender’s identity string and the public matrix to verify the signature of the message.

❖ PUBMATRIX_verify( PUBMATRIX, MessageDigest, SIGINFO) ⇒ Yes/No

Page 51: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

Serialization

• Serialization data types to/from memory

❖ int i2d_TYPE(TYPE *, unsigned char **);

❖ int d2i_TYPE(TYPE *, const unsigned char **, int);

• Serialization data types to/from files

❖ int i2f_TYPE( TYPE, filename );

❖ int f2i_TYPE(TYPE, filename );

Page 52: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

Data Structures

• PUBMATRIX the public matrix

• PRIVMATRIX the private matrix

• ASN1_UTF8STRING the public key, aka, identity string, this is a data type provided by OpenSSL.

• PRIVKEY the private key, with key owner’s information

• SIGINFO generated signature, with signer’s information

• RCPTINFO encrypted data, with recipient’s information. This encrypted data should only be short data, e.g. keys.

Page 53: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

Related Techniques

• ASN.1 encoding

• TLV: Type-Length-Value

• DER encoding

• openssl asn1parse

Page 54: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

TLV18 - Basic Encoding Rules (BER) 395

T L V

Tag Length Contentoctets octets octets

(a) Triplet TLV

T L T L T L V T L V

(b) Recursive principle

7654321001011001

(c) Bit weights

Figure 18.1: BER transfer syntax (TLV format)

no. 0 for all octets but the first one, whose five lower-order bits equal11111. The bottom of Figure 18.2 on the next page shows that for alloctets but the last one, the bit no. 7 equals 1. If the tag is not encodedon a number of bits that is a multiple of 7, some of the bits from no. 1to 6 of the second octet are unused and filled with padding 0s. In thesetwo forms, the bit no. 5 of the first octet indicates whether the value(i.e. the V field) is encoded in basic or constructed form. These twoforms are used in the next section.

The length octets represent the length of the value that is actuallyencoded, i.e. the number of content octets used in the V part of theTLV triplet. If the bit no. 5 of the first tag octet indicates a primitiveencoding form (see Figure 18.2 on the following page), the length isencoded in definite form. If the bit indicates a constructed encodingform, the sender may choose to code the length in definite or indefiniteform.

As shown on Figure 18.3 on the next page, the definite form can beshort (if the length of the V field is shorter than 127) or long, dependingon the sender. This liberty allows, for example, the protocol layer toencode all the length fields on a fixed number of octets, for specific needsof two communicating systems. If the sender should not be allowed tochoose the form of the length field, the CER or DER encoding rules,derived from BER, can be used (see Table 19.1 on page 420).

Page 55: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

CPK Crypto Library 0.7

• PKCS #11 API supported with thread safe.

• PKCS #7 crypto message syntax standard supported.

• SECG ver.1.7 ECC bulk encryption supported.

• ASN.1 and DER encoding supported.

• OpenSSL buffered IO, include memory, file, socket ...

• OpenSSL error stack supported.

• All platforms supported, Linux, Solaris, Windows, Mac.

Page 56: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

CPK with OpenSolaris

• Solaris, the most secure operation system with great security features, include cryptography framework, key management framework, filesystem encryption and hardware crypto accelerator.

• Solaris Crypto Framework (SCF) supports: extensible cryptographic interfaces, vendor hardware and software, default supports AES, 3DES, RSA, ECC, SHA-1, and CPK.

• Free and open source.

Page 57: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

Solaris Crypto Framework

!"#$%&'()*+*,--.*/01*2&3%"4$4)5647*8139 :;

!"#$%&'()*+,'"-.+/

!"#$

%&'(

)'*

+

,'"

&#-#.

%&'+

,'"

&(/%0

#1%&

#23

0!12034"5

6778930

797:

45

56 7

!8

9#:

'+&6

;9

<

,=

7;

6;9

<

;,<,=4;>1

>,?

!"2

$#1'

"

>+#?(.&+,?@A5$*+,'"-.+/

52-&@%"',"*A&2(!0B:6#3

5C%"&,%"1

!0B:6#3 7',+($>,+B*+,'"-.+/

D%"1@%"',"*A&2(!0B:6#3

EB&B"'("'0'%+'

520%"#+(FG

!"#2"(&2(520%"#+(FG

85/(83&'"-%.'+

,202"(831'H

%

%

%

)'"

I'"2

+

!BI

0#.()

'*

!"#$%&'()"*+&,#-(.&*/,#"*#+&"

55J7"5C+"7@"DD

Page 58: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

Key Management Framework

!"#$%&$'()*+(),,-

!"#$%&'$(&)*+,-

.-)+,-$.-)+,-$

./-00./-001!21!2

!-3$"454'-6-5*$#,46-78,9!-3$"454'-6-5*$#,46-78,9

.:.;.:.;

..;..;

<4=4>?<4=4>?

<@:<@:

<@:

<@:

(,8=&A-,

(,8=&A-,

B..C:(1

B..C:(1

D&'-?*C"DE

D& '-?*C"DE

@F:"C"DE

@F:"C"DE

!"#!"#

D-=-08G6-5*D-=-08G6-5*

@-,*&H&)4*-@-,*&H&)4*-

I40&A4*&85I40&A4*&85

(,8=&A-,?(,8=&A-,?

!-3!-3

"'6*"'6*

(,8=&A-,?(,8=&A-,?

B..C:(1B..C:(1

$$ (!$!-,J-,8?

(!$!-,J-,8?

(+J0&)$!-3

(+J0&)$!-3

(!KLL;(!KLL;

([email protected]([email protected] N..N.. #&0-?#&0-? L@.(L@.( @F;@F; (!1O(!1O

25,8006-5*25,8006-5*

(,8=&A-,?(,8=&A-,?

!"#$%#&'()*

(,8',466&5'$:(1

#+*+,-$#+*+,-$

15*-',4*&85$7&*/15*-',4*&85$7&*/

!"#!"#CPK

Page 59: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

Web Services Security Platform

!"#$%&'()*+*,--.*/01*2&3%"4$4)5647*8139 ::

!"#$%&'()*+,'-.%/)-.%)0"1)!"%2&#"3

!"#"$%&$&'(#'()

!*%%$+,-."/-'() !"#"$011)

!"#"+"(23"(24"('&'56(/.7$8,269'

:,#;.$011(,#'2$+(71.,

&&<

!"#"$%!&'

!+%

=(,

#/2'

(

&()*+,-("*./012("345,(6

&,>.4"('+(71.,$=96?@/-

&A"(.+"(2

=96?@/- 73"(+1&"(82("345,(6

3"(24"('+(71.,$=96?@/-

!"#"$%!77'

!"#"$B'C$&#5)

94)1:-3+;2("345,(6

=(/#

".'$

D'7

)

+'(

./>/ 5

".')

+'(

.$E"9

/2".

/,-

Java Web Svcs J2EE Containers Java Apps

Java ES Servers

Hard Crypto Mod JavaCardHard Crypto Module Gov’s Algor Module Java Card

Page 60: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

ZFS Filesystem Encryption

• Support keys and crypto operations in hardware.

• Support local (USBKey, smart card, TPM, password) or remote key manager.

• Support secure delete by “key destruction”

• Confidentiality : All application data, POSIX layer data (permissions, owner) and directory structure are encrypted with AES in CCM/GCM mode.

• Integrity: integrity protection of data and metadata by Fletcher or SHA256.

Page 61: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

Crypto Accelerator Board

• About 13,000 operations per second with 1,024 bit modular exponentiation, accelerate CPK based on DLP.

• Up to 1000 Mbps AES bulk encryption.

• Tamper-proof key storage.

• PKCS #11 API and PCI-E interface.

• Support Solaris and Linux.

• Price $1,350

Page 62: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

IDE

Page 63: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

IDE

Page 64: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

IDE

Page 65: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

IDE

Page 66: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

IDE

Sun Studio C/C++ IDE

Page 67: Crypto With OpenSSL

Guan ZhiNetwork and Information Security Lab, Peking UniversityOct. 17, 2008

Thanks! Any Questions?