126
Copyright © 1997 -1999 Institute for Applied Information Processing and Communications, Graz University of Technology Today, the Internet yet has intruded nearly into all domains of the human society. Regardless of only sitting at home on the PC and surfing the World Wide Web, taking some business transaction or visiting an electronic shop, everyone who has access to some provider may use the various possibilities offered by the Internet. The great amount of personal data transfered over the Internet every day claims for particular security mechanism making it difficult for some non-authorized eavesdropper to access and manipulate the data. The standard protocols used by the Internet itself offer a highly insufficient protection against any data attack to be expected. One of the meanwhile leading protocols for providing a secure data transfer over the Internet has been developed by the Netscape Communications Corporation when introducing their Secure Sockets Layer (SSL) protocol for supporting peer authentication, data encryption and data integrity. This paper introduces iSaSiLk , which implements the currently actual third Version of the Secure Sockets Layer protocol - SSLv3 . iSaSiLk is written in Java programming language and has been developed at the Institute for Applied Information Processing and Communications of the University of Technology in Graz, Austria. The paper is divided into three main parts. The first part gives a short overview of the Secure Sockets Layer protocol concentrating on the cipher suite concept used for negotiating security settings throughout an initial client- server handshake dialogue. The second part is a glossary summarizing the most usual terms that may arise within the iSaSiLk SSLv3 environment. Thethird part actually introduces the main features of iSaSiLk..

Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

Embed Size (px)

Citation preview

Page 1: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

Copyright © 1997 -1999 Institute for Applied Information Processing and Communications,Graz University of Technology

Today, the Internet yet has intruded nearly into all domains of the human society. Regardlessof only sitting at home on the PC and surfing the World Wide Web, taking some businesstransaction or visiting an electronic shop, everyone who has access to some provider may use thevarious possibilities offered by the Internet.

The great amount of personal data transfered over the Internet every day claims for particularsecurity mechanism making it difficult for some non-authorized eavesdropper to access andmanipulate the data. The standard protocols used by the Internet itself offer a highly insufficientprotection against any data attack to be expected.

One of the meanwhile leading protocols for providing a secure data transfer over the Internethas been developed by the Netscape Communications Corporation when introducing their SecureSockets Layer (SSL) protocol for supporting peer authentication, data encryption and dataintegrity.

This paper introduces iSaSiLk, which implements the currently actual third Version of theSecure Sockets Layer protocol - SSLv3.

iSaSiLk is written in Java programming language and has been developed at the Institute forApplied Information Processing and Communications of the University of Technology in Graz,Austria.

The paper is divided into three main parts. The first part gives a short overview of the SecureSockets Layer protocol concentrating on the cipher suite concept used for negotiating securitysettings throughout an initial client- server handshake dialogue.

The second part is a glossary summarizing the most usual terms that may arise within theiSaSiLk SSLv3 environment. Thethird part actually introduces the main features of iSaSiLk..

Page 2: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

SSL Overview

2

Introduction

Today, the Internet yet has intruded nearly into all domains of the human society.Regardless of only sitting at home on the PC and surfing the World Wide Web, takingsome business transaction or visiting an electronic shop, everyone who has access to someprovider may use the various possibilities offered by the Internet.

The great amount of personal data transfered over the Internet every day claims forparticular security mechanism making it difficult for some non-authorized eavesdropper toaccess and manipulate the data. The standard protocols used by the Internet itself offer ahighly insufficient protection against any data attack to be expected.

One of the meanwhile leading protocols for providing a secure data transfer over theInternet has been developed by the Netscape Communications Corporation whenintroducing their Secure Sockets Layer (SSL) protocol for supporting peer authentication,data encryption and data integrity.

This paper introduces iSaSiLk, which implements the currently actual third Version ofthe Secure Sockets Layer protocol - SSLv3.

iSaSiLk is written in Java programming language and has been developed at theInstitute for Applied Information Processing and Communications of the University ofTechnology in Graz, Austria.

The paper is divided into three main parts. The first part gives a short overview of theSecure Sockets Layer protocol concentrating on the cipher suite concept used fornegotiating security settings throughout an initial client- server handshake dialogue.

The second part is a glossary summarizing the most usual terms that may arise withinthe iSaSiLk SSLv3 environment.

The third part actually introduces the main features of the iSaSiLk SSLv3implementation. Based on many program code examples, guidelines are presented forhelping the user to realize her/his own SSLClient/SSLServer implementation.

Spelling Conventions

Normal text is written in Times New Roman, and program code examples are presentedusing Courier New. Classes, variables and methods declarations inherent to the iSaSiLkIAIK-SSL package may be recognized by the Arial font. Screen Outputs also are shownusing the Arial font.

Page 3: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

SSL Overview

3

Table Of Contents1 SSL - AN OVERVIEW................................................................................................................. 4

1.1 THE INITIAL HANDSHAKE PROCEDURE.................................................................................... 41.1.1 CIPHER SUITES .......................................................................................................................... 6

2 GLOSSARY................................................................................................................................. 11

3 INTRODUCTION TO ISASILK ............................................................................................... 17

3.1 SSLCLIENT: FROM SOCKET TO SSLSOCKET........................................................................ 173.2 SSLSERVER: FROM SERVERSOCKET TO SSLSERVERSOCKET ............................................ 203.3 BASIC REQUIREMENTS............................................................................................................. 263.3.1 PROVIDER HANDLING ............................................................................................................. 263.3.2 CERTIFICATES, KEYS AND PARAMETERS................................................................................ 343.4 SSL SOCKET AND SSL CONTEXT CLASSES............................................................................ 393.4.1 THE SSLCONTEXT CLASS....................................................................................................... 393.4.1.1 The SSLClientContext Class ............................................................................................... 423.4.1.1.1 Random Number Generator .............................................................................................. 423.4.1.1.2 Enabled Cipher Suites....................................................................................................... 443.4.1.1.3 Enabled Compression Methods ........................................................................................ 483.4.1.1.4 The Session Manager........................................................................................................ 523.4.1.1.4.1 public class SessionID ............................................................................................ 573.4.1.1.4.2 public class Session ................................................................................................. 583.4.1.1.4.3 public interface SessionManager .......................................................................... 603.4.1.1.4.4 public class DefaultSessionManager implements SessionManager....... 613.4.1.1.5 The Trust Decider ............................................................................................................. 703.4.1.1.5.1 public interface TrustDecider............................................................................... 723.4.1.1.5.2 public interface ServerTrustDecider extends TrustDecider .................... 733.4.1.1.5.3 public interface ClientTrustDecider extends TrustDecider .................... 773.4.1.1.5.4 Trust Deciding: What the SSLServer has to do............................................................. 903.4.1.1.5.5 Trust Deciding: What the SSLClient has to do ............................................................. 903.4.1.1.5.6 Client Authentication: What the SSLServer has to do .................................................. 913.4.1.1.5.7 Client Authentication: What the SSLClient has to do................................................... 923.4.1.1.6 SSLClientContext: Summary............................................................................................ 923.4.1.2 The SSLServerContext Class............................................................................................... 933.4.3 THE SSLSOCKET CLASS.......................................................................................................... 963.4.3.1 Connecting via a Proxy........................................................................................................ 973.4.3.2 Obtaining the peer´s certificate............................................................................................ 983.4.3.3 Security Parameter Renegotiation ....................................................................................... 993.4.4 THE SSLSERVERSOCKET CLASS........................................................................................... 1023.5 EXAMPLE: SSLCLIENT AND SSLSERVER............................................................................. 1053.5.1 A SSLCLIENT IMPLEMENTATION EXAMPLE......................................................................... 1053.5.2 A SSLSERVER IMPLEMENTATION EXAMPLE ........................................................................ 115

REFERENCES............................................................................................................................. 126

Page 4: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

SSL Overview

4

1 SSL - An OverviewSSL is an abbreviation for Secure Sockets Layer and constitutes an application

independent handshake protocol developed by the Netscape Communications Corporationfor providing a secure data transfer over the Internet.

Thereby, the connection security is marked by three basic properties ([SSL]):

• The connection is private. Encryption is used after an initial handshake to define asecret key. Data encryption is done by symmetric cryptography (e.g., DES, RC4,etc.).

• The peer´s identity can be authenticated using asymmetric, or public key cryp-tography (e.g., RSA, DSS, etc.).

• The connection is reliable. Message transport includes a message integrity checkbased on a MAC. Secure hash functions (e.g. SHA, MD5) are used for MACcomputations.

SSL operates at the Socket interface used for TCP, additionally supplied with peerauthentication and data encryption. So any higher level application protocol like HTTP,FTP, Telnet, ... may be protected by a secure transmission channel. Using HTTP, a SSLconnection can be recognized by means of the URL-type https (Port 443).

Currently SSL (Version 3.0) is the most important protocol for encrypted data transferover the WWW. It is supported not only by all the well known browsers like NetscapeNavigator (as standard), Microsoft Internet Explorer or SSLMosaic but also by manyservers like Netscape Server, Apache or NCSA.

The following section gives a more general view about the SSL Handshake protocol.For a detailed description see [SSL].

1.1 The Initial Handshake Procedure

Before starting the actual data transfer, client and server perform a handshake protocolphase authenticating each other (optional) and exchanging a session key. Purpose of thishandshake phase is the negotiation of cryptographic parameters, serving as a ´securitybasis´ for the following data transfer.

The handshake procedure is initiated by the client that sends a compression methodsand cipher suites list to the server containing the compression respectively cryptographicalgorithms supported by the client. These algorithms are offered the server in the client´s

Page 5: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

SSL Initial Handshake

5

preference order, meaning that the entries at the top of the particular list are favoured bythe client.

Now the server has to select one of the presented compression methods and ciphersuites to define the compression policy as well as the key exchange, symmetric encryptionand hash algorithms for the current session. If the server doesn´t support any of the client´scipher suites, a handshake failure alert is triggered and the connection is closed.

Otherwise the server authenticates itself by sending its certificate according to theselected cipher suite´s key exchange algorithm. Generally, the certificate message willconsist of a chain of X.509 certificates, starting with the server certificate and leading tothe certificate of the signing root certification authority.

The information derived from the certificate is used to create and exchange a sharedsecret (master key) between client and server. Based on this master key and some sessiondependent data, both client and server, generate two session keys - one of them for eachdata transfer direction.

After all, the handshake phase is concluded by the client´s and server´s Finished mes-sages, both already encrypted using the negotiated cryptographic algorithms and keys. Ifclient and server successfully have verified the correctness of the received communicationpartner´s finished message, they can enter the protected data transfer phase.

Note that

• Client authentication is optional and only necessary if explicitly requested by theserver. In this case, the server specifies the expected certificate type and thecertification authorities it is willing to accept. If the client is not able to comply withthe particular requirements, the server may close the connection, or it may continuethe handshake thereby tolerating the anonymity of the client.

Also it is possible to go into a completely anonymous session, meaning that neitherserver nor client authenticate themselves. However, such a communication would behighly vulnerable against man-in-the-middle attacks.

• The cryptographic parameters negotiated during some previous session may also beused for protecting the data transfer of the current session, making it superfluous toperform the whole handshake dialogue again.

There is no real necessity for the user of the iSaSiLk SSL implementation to haveknowledge about all the concerning details - mainly it would be advantageously to besomewhat familiar with the cipher suite concept for negotiating the cryptographicalgorithms of the current session. For that reason the following section tries to providesome basic understanding for the structure and using of cipher suites.

Page 6: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

SSL Cipher Suites

6

1.1.1 Cipher Suites

A cipher suite defines

• the public key (asymmetric) algorithm used for peer authentication and key exchange(e.g., RSA, DSA)

• the symmetric algorithm for data encryption (e.g., DES, RC4, ...)

• the secure hash function (e.g., SHA, MD5) for MAC computation

Client and server must agree on a specific cipher suite for determining the cryptographicalgorithms of the current session. At the beginning of the handshake dialogue the onlyactive cipher suite is labeled as SSL_NULL_WITH_NULL_NULL, indicating the initialabsence of any cryptographic specification.

The terminology for describing a cipher suite can be introduced as:

SSL_KeyExchangeAlgorithm_WITH_SymmetricEncryptionAlgorithm_HashAlgorithm

Thus, cipher suite SSL_NULL_WITH_NULL_NULL states NULL key exchange, NULLsymmetric encryption and NULL hash algorithm - hence initially none encryption is per-formed.

The following table lists all the cipher suites supported by SSLv3 and denotes thecorresponding key exchange, symmetric encryption and hash algorithms. Cipher suites thatare marked with an asterisk (*) indicate an exportable method that falls under the restric-tions of the current US export law. Except for Fortezza all the listed cipher suites areimplemented by iSaSiLk.

Cipher Suite Name Key Exchange

Algorithm

SymmetricEncryptionAlgorithm

HashAlgo-rithm

SSL_NULL_WITH_NULL_NULL* NULL NULL NULL

SSL_RSA_WITH_NULL_MD5* RSA NULL MD5

SSL_RSA_WITH_NULL_SHA* RSA NULL SHA

SSL_RSA_EXPORT_WITH_RC4_40_MD5* RSA_EXPORT RC4_40 MD5

SSL_RSA_WITH_RC4_128_MD5 RSA RC4_128 MD5

SSL_RSA_WITH_RC4_128_SHA RSA RC4_128 SHA

SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5* RSA_EXPORT RC2_CBC_40 MD5

SSL_RSA_WITH_IDEA_CBC_SHA RSA IDEA_CBC SHA

SSL_RSA_EXPORT_WITH_DES40_CBC_SHA* RSA_EXPORT DES40_CBC SHA

SSL_RSA_WITH_DES_CBC_SHA RSA DES_CBC SHA

SSL_RSA_WITH_3DES_EDE_CBC_SHA RSA 3DES_EDE_CBC SHA

SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA* DH_DSS_EXPORT DES40_CBC SHA

SSL_DH_DSS_WITH_DES_CBC_SHA DH_DSS DES_CBC SHA

Page 7: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

SSL Cipher Suites

7

SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA DH_DSS 3DES_EDE_CBC SHA

SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA* DH_RSA_EXPORT DES40_CBC SHA

SSL_DH_RSA_WITH_DES_CBC_SHA DH_RSA DES_CBC SHA

SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA DH_RSA 3DES_EDE_CBC SHA

SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA* DHE_DSS_EXPORT DES40_CBC SHA

SSL_DHE_DSS_WITH_DES_CBC_SHA DHE_DSS DES_CBC SHA

SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA DHE_DSS 3DES_EDE_CBC SHA

SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA* DHE_RSA_EXPORT DES40_CBC SHA

SSL_DHE_RSA_WITH_DES_CBC_SHA DHE_RSA DES_CBC SHA

SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA DHE_RSA 3DES_EDE_CBC SHA

SSL_DH_anon_EXPORT_WITH_RC4_40_MD5* DH_anon_EXPORT RC4_40 MD5

SSL_DH_anon_WITH_RC4_128_MD5 DH_anon RC4_128 MD5

SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA* DH_anon_EXPORT DES40_CBC SHA

SSL_DH_anon_WITH_DES_CBC_SHA DH_anon DES_CBC SHA

SSL_DH_anon_WITH_3DES_EDE_CBC_SHA DH_anon 3DES_EDE_CBC SHA

SSL_FORTEZZA_DMS_WITH_NULL_SHA FORTEZZA_DMS NULL SHA

SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA FORTEZZA_DMS FORTEZZA_CBC SHA

* .... exportable cipher suite

Table 1.1: SSL Cipher Suite Algorithms

The cipher suite negotiation process already has been discussed: the client offers a listof supported cipher suites in preference order. The server answers by selecting one of thepresented cipher suites or generating a handshake failure alert.

If the cipher suite negotiation has been successfully completed, usually the serverauthenticates itself by sending a X.509 certificate. The certificate message includes theserver´s public key that has to be appropriate for the key exchange algorithm of the ciphersuite agreed upon.

If the cipher suite defines a RSA certificate, the client gets the server´s RSA publickey for encrypting a ´premaster´ secret and sending it to the server. Following this, theserver decrypts the received premaster secret with his RSA private key and both,client and server, hold the same shared secret, serving as starting point for computingthe session keys which later are used for encrypting the data to be transfered.

If the server sends a Diffie Hellman certificate, the client uses the server´s DiffieHellman public key and parameters (prime modulus and generator) to calculate thepremaster secret. Furthermore the client generates his own public Diffie Hellman keyand sends it to the server that now is able to calculate the same premaster secret fromit´s own private and the client´s public key. For more information on Diffie Hellmankey exchange see [SSL] and [Schneier].

If the server has no certificate, or the server certificate cannot be used for keyexchanging, an extra server key exchange message has to be transmitted. The servercertificate may be unsuitable for key exchanging for the following reasons:

Page 8: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

SSL Cipher Suites

8

• The certificate is a sign-only certificate (e.g. DSA or sign-only RSA). Since, forinstance, the DSA algorithm only can be used for signing, it is necessary to send thekey within a separate message: the public DSA key is included in the certificate, andthe following key exchange message transmits the, for instance, public DH key,signed by the server´s private DSA key.

• The actual cipher suite falls under the US law export regulations forbidding RSAkeys used for encryption to be longer than 512 Bits. However, there are no limitsconcerning the length of RSA keys that are used for signing only.

So the server may send a temporary public RSA ´encryption´ key of a length lessthan (or equal) 512 Bits within a separate key exchange message, and signs this tem-porary key with the private key matching to the any length public key it haspreviously sent with its certificate.

Notice, that if the cipher suite is an exportable one and the certificate´s public key islonger than 512 Bits, the server has to take care for a temporary key pair since thecertificate´s any length public key is only allowed to be used for signing!

The following table provides an overview of the specific certificate types, cryptographickeys respectively parameters required by the particular cipher suites.

Cipher Suite Name PrivateKey +RSACertifi-cate

RSA tem-porarykey pair

PrivateKey +DSACertifi-cate

PrivateKey + DHCertifi-cate

DH tem-poraryparame-ters

SSL_NULL_WITH_NULL_NULL*

SSL_RSA_WITH_NULL_MD5* x x1)

SSL_RSA_WITH_NULL_SHA* x x1)

SSL_RSA_EXPORT_WITH_RC4_40_MD5* x x1)

SSL_RSA_WITH_RC4_128_MD5 x

SSL_RSA_WITH_RC4_128_SHA x

SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5* x x1)

SSL_RSA_WITH_IDEA_CBC_SHA x

SSL_RSA_EXPORT_WITH_DES40_CBC_SHA* x x1)

SSL_RSA_WITH_DES_CBC_SHA x

SSL_RSA_WITH_3DES_EDE_CBC_SHA x

SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA* x

SSL_DH_DSS_WITH_DES_CBC_SHA x

SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA x

SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA* x

SSL_DH_RSA_WITH_DES_CBC_SHA x

SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA x

SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA* x x

Page 9: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

SSL Cipher Suites

9

SSL_DHE_DSS_WITH_DES_CBC_SHA x x

SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA x x

SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA* x x

SSL_DHE_RSA_WITH_DES_CBC_SHA x x

SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA x x

SSL_DH_anon_EXPORT_WITH_RC4_40_MD5* x

SSL_DH_anon_WITH_RC4_128_MD5 x

SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA x

SSL_DH_anon_WITH_DES_CBC_SHA x

SSL_DH_anon_WITH_3DES_EDE_CBC_SHA x

* ...... exportable cipher suite

x ..... required to support the particular cipher suite1) ...... required if certificate RSA public key > 512 Bits

Table 1.2: Cipher Suite Requirements

Note, that a Diffie Hellman certificate for transmitting the DH parameters may be basedeither on RSA or on DSS signing (see table 1.3).

It´s quite obviously that the listed certificate types and keys only are predicted by theparticular cipher suite´s key exchange algorithm. Symmetric cipher and hash algorithmhave no influence on the choice of the certificate type. The table below therefore brieflydescribes the several key exchange algorithms (see also [SSL]).

Key Exchange Algorithm Description Key size limit for public keysused in exportable cipher suites

NULL No key exchange N/A

RSA RSA key exchange None

RSA_EXPORT RSA key exchange RSA = 512 Bits

DH_DSS DH with DSS-based certificates None

DH_DSS_EXPORT DH with DSS-based certificates DH = 512 Bits

DH_RSA DH with RSA-based certificates None

DH_RSA_EXPORT DH with RSA-based certificates DH = 512 Bits, RSA = None

DHE_DSS Ephemeral DH with DSS signatures None

DHE_DSS_EXPORT Ephemeral DH with DSS signatures DH = 512 Bits

DHE_RSA Ephemeral DH with RSA signatures None

DHE_RSA_EXPORT Ephemeral DH with RSA signatures DH = 512 Bits, RSA = None

DH_anon Anonymous DH, no signatures None

DH_anon_EXPORT Anonymous DH, no signatures DH = 512 Bits

Table 1.3: Key Exchange Algorithms

Page 10: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

SSL Cipher Suites

10

RSA denotes cipher suites where the server transmits its public RSA key of any lengthwithin a RSA certificate.

RSA_EXPORT demands for an extra key exchange message for sending a temporaryRSA public key of a length less than (or equal) 512 Bits according to the US law exportrestrictions if the certificate´s public key is longer than 512 Bits. In this case, the temporarykey pair is signed with the RSA private key that belongs to the any length RSA public keypreviously has been sent within the RSA certificate.

DH_RSA, DH_DSS: the server´s certificate transmits the Diffie Hellman parameters thatare signed by the certification authority using the RSA respectively DSA algorithm.

DH_RSA_EXPORT, DH_DSS_EXPORT: same as above, except for restricting theDiffie Hellman key length to a maximum of 512 Bits since the cipher suite is exportable.

DHE_RSA, DHE_DSS: the Diffie Hellman parameters are sent within an extra key ex-change message, signed by the key of a previously transmitted RSA respectively DSAcertificate.

DHE_RSA_EXPORT, DHE_DSS_EXPORT: same as above, except for restricting theDiffie Hellman key length to a maximum of 512 Bits since the cipher suite is exportable.

DH_anon, DH_anon_EXPORT: since the communication is an entirely anonymous one,none certificate will be necessary. The DH parameters are sent within the server keyexchange message.

Summing up, the server has to take care for a RSA certificate (plus correspondingprivate key) if it intends to support a RSA or DHE_RSA cipher suite. Additionally a RSAtemporary key pair will be necessary if the cipher suite is an exportable one and the RSAcertificate´s public key claims for more than 512 Bits. DHE_RSA require temporary DHparameters. A DH certificate (plus corresponding private key) must be provided for anykind of DH cipher suite. DHE_DSS cipher suites demand DSA certificates (pluscorresponding private keys) and temporary DH parameters. And finally DH_anon ciphersuites render any kind of certificate superfluous since the DH parameters are sent unsignedwithin a key exchange message.

The symmetric algorithms used by SSL for data encryption can be divided into streamciphers (RC4 with 40 or 128 Bit keys) and block ciphers (RC2 with 40 Bit keys, IDEA,DES40, DES, 3DES_EDE). All the block ciphers operate in CBC (Cipher Block Chaining)mode XORing each plaintext block with the previous ciphertext block before encrypting it.

The message digest algorithms supported by SSL are MD5 which produces a 128 Bithash, and SHA for providing a 160 Bit hash.

All the various combinations are listed above in table 1.1 and can be consulted in [SSL]for a further increasing of knowledge. Descriptions of the several algorithms may be foundin [Schneier].

Now, I suppose, quite enough has been said about the SSL cipher suites, and it´s time tointroduce IAIK´s SSLv3 implementation iSaSiLk. Before starting the discussion within thenext chapters, a short glossary tries to pithy depict some of the most essential terms com-monly emerging throughout the iSaSiLk SSL environment.

Page 11: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

SSL Glossary

11

2 Glossary

API Application Programming Interface; programminginterface of a software system.

Applet Java program that is embedded into a HTML file forexecuting it directly by an appropriate browser.

ASN.1 Abstract Syntax Notation One; language fordescribing data structures in an abstract and platformindependent manner.

Asymmetric Cipher Cryptographic algorithm using a public key for dataencryption and a secret (private) key for datadecryption. Anyone who has access to the public keycan encrypt a message, but only the owner of thecorresponding private key is able to decrypt thereceived message. Asymmetric - or public keyalgorithms - also are used for data signing. Messagesthat are signed with the private key of a specific entitycan be verified with the matching public key.

Authentication Someone´s identity supported by voucher, usuallydone by means of a certificate.

BER Basic Encoding Rules; set of rules for binaryencoding ASN.1 objects.

Block Cipher Symmetric algorithm that operates on - usually64 Bit - blocks of plaintext and ciphertext.

Browser Tool for viewing WWW sites.

CA Certification Authority; trustworthy and independentinstitution for issuing and managing certificates.

Page 12: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

SSL Glossary

12

CBC Cipher Block Chaining mode; adds a feedbackmechanism to a block cipher; before an plaintextblock is encrypted, it is XORed with the previousciphertext block (the first block is XORed with aninizialization vector).

Certificate A special message for verifying someone´s identity;usually a certificate will contain the user´s name andpublic key - optionally additional information may beincluded - and is signed by a trustworthy entity (i.e.certification authority). The certificate syntax isspecified by the ITU-T X.509 recommendation.

Client Within a client/server architecture, one part - theserver - provides some resources requested by theother part that is called the client. Server and clientusually execute on different hosts.

Data Integrity Certainty that the data has not been modified duringthe transmission.

DER Distinguished Encoding Rules; subset of the BasicEncoding Rules for binary encoding ASN.1 objects.DER encoding is non ambiguously. There isdefinitely one way to encode an ASN.1 object as anoctet string. BER encoding is ambiguously making itpossible to represent an ASN.1 object in more thanone ways as an octet string.

DES Data Encryption Standard; the most popularsymmetric block algorithm for data encryption.

DH Diffie-Hellman; the first public key algorithm; usedfor key distribution.

Digital Signature A possibility for ensuring the origin and integrity ofdata; the sender uses a public key algorithm and oneway hash function to sign his message; the recipientcan verify that the message has been signed by no oneother than the sender, and that the message hasreached the destination unchanged.

Page 13: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

SSL Glossary

13

DSA Digital Signature Algorithm; public-key digitalsignature algorithm, employed by the DSS.

DSS Digital Signature Standard, proposes the digitalsignature algorithm for digital signing to verify theintegrity of data and the identity of the sender.

FTP File Transfer Protocol; protocol for managing filetransfers over the net.

Handshake A negotiation dialogue between the client and serverarranging the cryptographic parameters for thefollowing secure data transfer.

Hash function Mathematical function for computing a fixed sizeddata value (hash) from input data of arbitrary size.The length of the hash value usually is shorter thanthat of the input data. In cryptography generally one-way hash functions are used, making it easy tocompute the hash but hard to go the reverse way forcalculating the input data when only the hash isknown.

HTML Hypertext Markup Language; formatting andstructuring language for building WWW documents.

HTTP Hypertext Transfer Protocol; the transfer protocol ofthe WWW.

IDEA International Data Encryption Algorithm; ranks asone of the best and most secure block ciphers that arecontemporary public available.

IP Internet Protocol; basic Internet transport protocol.

IV Initialization Vector for XORing with the first plainttext block when running a block cipher in CBC mode.

Page 14: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

SSL Glossary

14

Java Object oriented and platform independentprogramming language of Sun Microsystems Inc.

JCA Java Cryptography Architecture; framework foraccessing and developing cryptographic functionalityfor the Java Platform ([JCA]).

JCE Java Cryptography Extension; extends the JCA APIto include encryption and key exchange.

Key Exchange Cryptographic technique where the data encryption ofeach particular session is done with a specific sessionkey only used for this one single session.

MAC Message Authentication Code; denotes acryptocraphic checksum, which is derived byprocessing some given message (or the authenticationelements of the message) using a secret key forensuring the integrity of data.

Master Secret 48-Byte shared secret between client and server that isused for generating encryption keys, MAC secrets andinitialization vectors.

MD5 Message Digest 5; one-way hash function forproducing a 128-bit hash (message digest) from theinput data.

Message Digest Bit String of fixed length (hash), computed from inputdata of arbitrary length (see hash function).

PKCS Public-Key Cryptography Standards; standards forpublic-key cryptography applications based on theRSA encryption method.

Public Key Cryptography Asymmetric encryption method; one key is public andcan be used by anyone interested; the correspondingprivate key is kept in secret by the key-pair owner.Data that is encrypted with the public key only can bedecrypted with the corresponding private key. Data

Page 15: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

SSL Glossary

15

that is signed with the private key can be verified withthe matching public key.

RC2 Ron´s Code 2 (Rivest Cipher 2); variable-key-size64-Bit block cipher, developed by Ron Rivest forRSA Data Security, Inc.

RC4 Ron´s Code 4 (Rivest Cipher 4); variable-key-sizestream cipher, developed by Ron Rivest for RSA DataSecurity, Inc.

RSA Famous public-key algorithm, developed by RonRivest, Adi Shamir and Leonard Adleman in 1977;may be used for data encryption or digital signing.

Server Within a client/server architecture, one part - theserver - provides some resources requested by theother part that is called the client. Server and clientusually execute on different hosts.

Session A SSL session ([SSL]) is an association between aclient and a server. Sessions are created by thehandshake protocol. Sessions define a set ofcryptographic security parameters, which can beshared among multiple connections. Sessions are usedto avoid the expensive negotiation of new securityparameters for each connection. A particular sessionis identified by a value (session identifier) generatedby the server.

SHA Secure Hash Algorithm; algorithm for computing ahash value; designed for use with the DigitalSignature Standard (DSS); the corresponding standardis named Secure Hash Standard (SHS).

S-HTTP Secure-Hypertext Transfer Protocol; extends theHTTP about some security capabilities.

Socket Logical end-point of a network communication basedon TCP or UDP.

Page 16: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

SSL Glossary

16

Stream Cipher Symmetric algorithm that operates on streams ofplaintext and ciphertext one bit or byte at a time.

Symmetric Cipher Encryption algorithm that uses the same - secret - keyfor both, data encryption and data decryption.

TCP Transmission Control Protocol; connection basedprotocol that operates on the IP thereby extending itabout reliability.

TCP/IP Collection of protocols for managing data transfersover the Internet.

URL Uniform Resource Locator; address of a WWW-resource.

WWW World Wide Web; multimedia information system ofthe Internet; based on Hypertext.

X.509 ITU-T (International Telecommunication Union)recommendation for supposing an authenticationsystem and certificate syntax.

Page 17: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk Introduction

17

3 Introduction to iSaSiLk

iSaSiLk (IAIK Java SSL) is an implementation of the SSL protocol version 3.0 asspecified by Netscape Communications Corporation. iSaSiLk operates on top of theIAIK-JCE packages, both developed at the Institute for Applied Information Processingand Communications of the University of Technology in Graz, Austria, but may be usedwith any alternative JCE provider (see 3.3.1).

This paper gives an introduction to the main features of iSaSiLk. After presenting somegeneral outlines making you familiar with the essential programming requirements, some´step-by-step´ examples intend to provide guidelines for implementing SSL connections.

In chapter 1 - SSL Overview - it has been said that SSL operates at the Socket interfaceused for TCP, additionally supplied with peer authentication and data encryption.According to this, iSaSiLk implements SSL connections by extending the Socket classes ofthe java.net package about SSL´s inherent security features. So it would be a good practiceto introduce iSaSiLk by duplicating the process of going from a ´normal´ to a secure SSLconnection. During the following discussion, we have to distinguish between the client´sand the server´s side of a connection.

3.1 SSLClient: From Socket To SSLSocket

Perhaps you have read the Java tutorial for establishing TCP connections by means ofthe java.net.Socket and java.net.ServerSocket classes ([javaTut]) and remember the basicsteps required for implementing the client side of the connection:

1. Open a socket.2. Open an input stream and output stream to the socket.3. Read from and write to the streams according to the server's protocol.4. Close the streams.5. Close the socket.

In Java programming code the realization of these several tasks may look like (tosimplify matters, exception handling is not included in the following code examples):

1. Socket s = null;s = new Socket(serverName, serverPort);

A variable of type Socket is defined and then instantiated thereby establishing asocket connection to a server previously specified by serverName that islistening at port number serverPort.

Page 18: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk Introduction

18

2. PrintWriter os = new PrintWriter(s.getOutputStream()); DataInputStream is = newDataInputStream(s.getInputStream());

An output and an input stream are opened on the socket to write to and read fromthe socket.

3. Do something useful

Since this chapter only deals with the establishing and closing of connections, theactual client-server data transfer is not of interest at this state of discussion.

4. os.close(); is.close();

Close output and input streams.

5. s.close();

Close the socket.

If we want to include exception handling, we must be aware that connecting to a servermight raise an UnknownHostException and the several input/output stream operationsmight lead to an I/O Exception. Hence, the whole client program fragment for opening andclosing a conventional socket connection may look like:

Socket s = null;try {

s = new Socket(serverName, serverPort); PrintWriter os = new PrintWriter(s.getOutputStream());

DataInputStream is = newDataInputStream(s.getInputStream()); ... communicate with server ...

os.close(); is.close(); s.close();} catch (UnknownHostException ex) { System.out.println("UnknownHostException: "+ex.getMessage());} catch (IOException ex) { System.out.println("IOException: "+ex.getMessage());}

Now, after we have taken a look at the core work for realizing the client´s side of a´normal socket´ client-server connection, the question arises, what´s to do whenimplementing a ´SSLClient´ using iSaSiLk? If we - for the present - don´t consider basicprerequisites like importing some necessary classes or installing a provider, the main stepsdon´t differ greatly from the tasks for building a conventional client:

Page 19: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk Introduction

19

1. Open a SSL socket.2. Open an input stream and output stream to the SSL socket.3. Read from and write to the streams according to the server’s protocol.4. Close the streams.5. Close the SSL socket.

In Java programming code the realization of these several tasks may look like (tosimplify matters, exception handling is not included in the following code examples):

1. SSLSocket s = null; SSLClientContext context = new SSLClientContext();

s = new SSLSocket(serverName, serverPort, context);

Instead of creating a normal Socket object as above, a representative ofSSLSocket is instantiated. The iSaSiLk class SSLSocket inherits from the classSocket of the java.net package and extends it about the SSL security features.The specific security properties of a particular SSLSocket object mainly aredetermined by the context of the SSL socket and can be influenced by the user increating a SSLClientContext object and supplying it with the desired settings(cipher suites, compression methods, ...). When actually instantiating theSSLSocket object in line 3 of the code stated above, the constructor demands for acontext object to define the client´s security capabilities for going into a SSLhandshake with the specified server listening on port serverPort. If a contextobject only has been created but not equipped with special user inputs, a defaultcontext is taken and put to the SSLSocket.

The SSLSocket and context classes are discussed in detail further below; for a firstglance it should do to confirm with the default settings.

2. PrintWriter os = new PrintWriter(s.getOutputStream()); DataInputStream is = newDataInputStream(s.getInputStream());

By means of exactly the same lines of program code as be usual for a conventionalconnection, an output and an input stream are opened on the SSL socket to write toand read from the socket.

3. Do something useful

Since this chapter only deals with the establishing and closing of SSL connections,the actual client-server data transfer is not of interest at this state of discussion.

4. os.close(); is.close();

Close output and input streams. The output stream has to be closed before closingthe input stream.

Page 20: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk Introduction

20

5. s.close();

Close the SSL socket.

Note, that when finishing an iSaSiLk SSL connection there is no real necessity forexplicitly closing the streams on the socket since this is automatically done when closingthe socket in the step 5 listed above. If you want to explicitly close the streams, be sure toclose the output stream before closing the input stream to ensure that the SSL connectionfinishes correctly.

Again, we should be aware of UnknownHost and I/O Exceptions leading to thefollowing program fragment as part for implementing the client side of a SSL connection:

SSLSocket s = null;SSLClientContext context = new SSLClientContext();try {

s = new SSLSocket(serverName, serverPort, context); PrintWriter os = new PrintWriter(s.getOutputStream());

DataInputStream is = newDataInputStream(s.getInputStream()); ... communicate with server ...

os.close(); is.close(); s.close();} catch (UnknownHostException ex) { System.out.println("UnknownHostException: "+ex.getMessage());} catch (IOException ex) { System.out.println("IOException: "+ex.getMessage());}

So far you have seen that the implementation of the basic steps for building aconventional Client or a SSLClient mainly differs in providing a context object thatdetermines the security features of the SSL Socket connection. The next chapter willintroduce the basic tasks for realizing the server side of a SSL connection. As you alreadymight suppose, you will have to take care for a server context to manage the securityproperties of the SSLServer.

3.2 SSLServer: From ServerSocket ToSSLServerSocket

The basic steps for implementing the server side of a conventional socket connectioncan be summarized as follows:

Page 21: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk Introduction

21

1. Open a server socket to listen on a specified port number for any client requests.2. If a client wishes to connect to the server, try to accept the connection by creating a

client socket.3. Open an input stream and output stream to the client socket.4. Read from and write to the streams.5. Close the streams.6. Close the sockets.

In Java programming code the realization of these several tasks may look like (tosimplify matters, exception handling is not included in the following code examples):

1. ServerSocket server = null;server = new ServerSocket(serverPort);

A ServerSocket object is created for listening on a previously specified portserverPort.

2. Socket s = null; s = server.accept();

The server, that listens on the specified port number, tries to accept a client request.If this successfully is done, the accept method returns a new socket object forcommunicating with the client.

3. PrintWriter os = new PrintWriter(s.getOutputStream()); DataInputStream is = newDataInputStream(s.getInputStream());

An output and an input stream are opened on the socket to write to and read fromthe socket.

4. Do something useful

Since this chapter only deals with the establishing and closing of connections, theactual client-server data transfer is not of interest at this state of discussion.

5. os.close(); is.close();

Close output and input streams.

6. s.close(); server.close();

Close (client) socket and server socket.

Page 22: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk Introduction

22

Considering exception handling on the server side, we must try to catch I/O exceptionsif the server will not be able to listen on a specific port or if some Input/Output streamoperation fails. Also the accept method may throw an I/O exception if an error occurswhile waiting for a connection request. Hence, the whole server program fragment forlistening and accepting conventional socket connection requests may look like:

ServerSocket server = null;Socket s = null;try {

server = new ServerSocket(serverPort); s = server.accept();

PrintWriter os = new PrintWriter(s.getOutputStream()); DataInputStream is = newDataInputStream(s.getInputStream()); ... communicate with client ...

os.close(); is.close(); s.close();

server.close();} catch (IOException ex) { System.out.println("IOException: "+ex.getMessage());}

Maybe, you don´t want to close the server socket immediately after closing the clientsocket in order to be able for accepting further client requests. In this case, a while loopmay be used for handling one client request after the other. The server socket is openedoutside the while loop and continues listening for connection requests after theconversation with one particular client has been finished by closing the client socket :

ServerSocket server = null;Socket s = null;try {

server = new ServerSocket(serverPort);} catch (IOException ex) { System.out.println("IOException: "+ex.getMessage());}while (true) { try {

s = server.accept(); PrintWriter os = new PrintWriter(s.getOutputStream());

DataInputStream is = newDataInputStream(s.getInputStream()); ... communicate with client ...

os.close(); is.close(); s.close(); } catch (IOException ex) { System.out.println("IOException: "+ex.getMessage()); }}

Page 23: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk Introduction

23

Now, after we have take a look at the core work for realizing the server´s side of a´normal socket´ client-server connection, what´s to do when implementing a ´SSLServer´using iSaSiLk? If we - for the present - don´t consider basic prerequisites like importingsome necessary classes or installing a provider, the main steps don´t differ greatly from thetasks for building a conventional server:

1. Open a SSL server socket to listen on a specified port number for any clientrequests.

2. If a client wishes to connect to the server, try to accept the connection by opening aSSL client socket.

3. Open an input stream and output stream to the client socket.4. Read from and write to the streams.5. Close the streams.6. Close the SSL sockets.

In Java programming code the realization of these several tasks may look like (tosimplify matters, exception handling is not included in the following code examples):

1. SSLServerSocket server = null; SSLServerContext serverContext = new SSLServerContext();

server = new SSLServerSocket(serverPort, serverContext);

Instead of creating a normal ServerSocket object as above, a representative ofSSLServerSocket is instantiated. The iSaSiLk class SSLServerSocketinherits from the class ServerSocket of the java.net package and extends itabout the SSL security features. The specific security features of a particularSSLServerSocket object mainly are determined by the context of the SSLserver socket and can be influenced by the user in creating aSSLServerContext object and supplying it with the desired settings (ciphersuites, compression methods, ...). When actually instantiating the SSLServerSocketobject in line 3 of the code stated above, the constructor demands a context objectto define the server´s security capabilities for going into a SSL handshake with thea client requesting a connection at the port number the server is listening. If acontext object only has been created but not equipped with special user inputs, adefault context is taken and put to the SSLServerSocket.

The SSLServerSocket and context classes are discussed in detail further below; fora first glance it should do to confirm with the default settings.

2. SSLSocket s = null; s = (SSLSocket)server.accept();

The server, that listens on the specified port number, tries to accept a client request.If this successfully is done, the accept method returns a new SSL socket objectfor communicating with the client. Since the accept method of the ServerSocketclass by default returns a conventional Socket object, it is necessary to make anexplicit cast for obtaining a SSLSocket object.

Page 24: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk Introduction

24

3. PrintWriter os = new PrintWriter(s.getOutputStream()); DataInputStream is = newDataInputStream(s.getInputStream());

By means of exactly the same lines of program codes as be usual for a conventionalconnection, an output and an input stream are opened on the SSL socket to write toand read from the socket.

4. Do something useful

Since this chapter only deals with the establishing and closing of SSL connections,the actual client-server data transfer is not of interest at this state of discussion.

5. os.close(); is.close();

Close output and input streams. The output stream has to be closed before closingthe input stream.

6. s.close(); server.close();

Close the SSL (client) socket and the SSL server socket.

Note, that in a iSaSiLk SSL connection there is no real necessity for explicitly closingthe streams on the client socket since this is automatically done when closing the clientsocket in the step 6 listed above. If you want to explicitly close the streams, be sure toclose the output stream before closing the input stream to ensure that the SSL connectionfinishes correctly.

Exceptions on the server side of a SSL connection may be thrown for the same reasonsas they may appear when implementing a server in a conventional connection: we must tryto catch I/O exceptions if the server will not be able to listen on a specific port or if someInput/Output stream operation fails. Also the accept method may throw an I/O exceptionif an error occurs while waiting for a connection request. Additionally we have tointroduce the SSLException for capturing errors that may occur during the SSL handshakephase. Hence, the whole SSL server program fragment for listening and accepting SSLsocket connection requests may look like:

SSLServerSocket server = null;SSLServerContext serverContext = new SSLServerContext();SSLSocket s = null;try {

server = new SSLServerSocket(serverPort, serverContext); s = (SSLSocket)server.accept();

PrintWriter os = new PrintWriter(s.getOutputStream()); DataInputStream is = newDataInputStream(s.getInputStream()); ... communicate with client ...

Page 25: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk Introduction

25

os.close(); is.close(); s.close();

server.close();} catch (SSLException ex) { System.out.println("SSLException: "+ex.getMessage());} catch (IOException ex) { System.out.println("IOException: "+ex.getMessage());}

Again, you might wish to implement a SSL server permanently listening on clientrequests:

SSLServerSocket server = null;SSLSocket s = null;SSLServerContext serverContext = new SSLServerContext();try {

server = new SSLServerSocket(serverPort, serverContext);} catch (IOException ex) { System.out.println("IOException: "+ex.getMessage());}

while (true) { try {

s = (SSLSocket)server.accept(); PrintWriter os = new PrintWriter(s.getOutputStream());

DataInputStream is = newDataInputStream(s.getInputStream()); ... communicate with client ...

os.close(); is.close(); s.close(); } catch (SSLException ex) { System.out.println("SSLException: "+ex.getMessage()); } catch (IOException ex) { System.out.println("IOException: "+ex.getMessage()); }}

After these first glances onto the main steps for programming client and server of a SSLconnection based on the iSaSiLk SSLv3 implementation, we are ready to take a lookbehind the main properties of SSL Socket and Context classes. Before doing so, perhaps itwould be advantageously to reflect the basic preconditions that are necessary forimplementing SSL clients and SSL servers.

Page 26: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk Introduction

26

3.3 Basic Requirements

Within the previous sections we directly have stepped into program code fragments forimplementing a SSL client and server, not concerning some fundamental requirements thathave to be fulfilled for ensuring the correct working of our implementations. If you thinkof the cipher suite discussion of chapter 1 - SSL Overview - you will remember the severalcertificate types, cryptographic keys and parameters that are necessary for supporting theparticular sorts of cipher suites (see table 1.2).

In this section we introducing will scrutinize how iSaSiLk fits into the JCA/JCEprovider architecture. Following this, we will assume to implement a SSL server anddiscuss basic preconditions like taking care for particular certificates and cryptographicparameters necessary for cipher suite support.

3.3.1 Provider Handling

The provider architecture has been introduced by the Java Cryptographic Architecture(JCA) making it possible for different cryptography implementations to operate oncommon interfaces.

The term provider is an abbreviation for Cryptographic Package Provider and denotesa package or a set of packages supplying a concrete implementation of a subset of thecryptography aspects of the Java Security API (see [JCA]). The Java Development Kitoffers a default provider - "SUN" - but everyone is free to create its own or use any otherprovider having access to it.

Each provider may come up with its own particular implementation of anycryptographic algorithm to be used, and the user may decide to prefer, for instance, theDSA implementation of provider 1 instead of working with the DSA algorithmimplemented by provider 2.

For applications that operate on the Java Cryptography Extension (JCE) additionally to´JCA providers´ at least one proper JCE provider - for instance the IAIK provider asdescribed below - has to be made available.

Precondition for being able to use some specific provider is to install and configure thecorresponding provider package classes (see [JCA]).

For generally accessing and using the algorithm implementations of specific providers,the Java Cryptography Architecture introduces the concept of engine classes and factorymethods. Engine classes provide interfaces to the functionality of a type of cryptographicalgorithms and factory methods are used for obtaining some specific implementation.

So, for instance, an object of the MessageDigest engine class is instantiated by meansof the getInstance factory method:

MessageDigest md = MessageDigest.getInstance("AlgorithmName", "ProviderName");

Page 27: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk Introduction

27

Specifying a particular provider is optional. If no provider is stated, all actual providersare searched until one is found that implements the required algorithm:

MessageDigest md5 = MessageDigest.getInstance("MD5");

Otherwise the particular algorithm implementation of the explicitly specified providerwill take precedence .

A provider may realize implementations of digital signature algorithms, message digestalgorithms and - if supported by JCE - encryption algorithms.

The IAIK security provider package supports the following algorithms and securityfacilities:

• Signatures:

- MD5/RSA (MD5 with RSA encryption)

- SHA/RSA (SHA with RSA encryption)

• Key Management facilities:

- RSA and DSA keys

- RSA and DSA key pair generators

- DH keys and key parameter generation

• Symmetric Ciphers:

- DES

- Triple DES

- IDEA

- RC4

- RC2

Precondition for being able to use some specific provider is to install and configure thecorresponding provider package classes.

When intending to use the IAIK security provider package, the first step of installingthe provider already has been done by installing the IAIK-JCE implementation andupdating the classpath variable according to the location of the iaik-jce.jar file.

The second step of configuring the provider can be done either statically or dynamically.For detailed information about the configuration process you may consult the [JCA]documentation; in our example we will register the IAIK provider dynamically by adding itto the list of the providers in use:

Page 28: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk Introduction

28

IAIK provider = new IAIK(); Security.addProvider(provider);

For supporting any alternative provider, iSaSiLk is equipped with a specific interfaceclass (iaik.security.ssl.provider.SecurityProvider) that has to beimplemented by an application intending to use another than the IAIK provider. Everytimesome provider related objects are required, iSaSiLk will consult this SecurityProviderimplementation to query for the provider dependent source by accessing one of the severalgetCryptographicObject methods:

/*** Returns a DHPublicKey created from the values: y (public), p (prime modulus) and* g (base generator).

* * This method only must be implemented if an application wants to use Diffie-Hellman * cipher suites. */ public abstract DHPublicKey getDHPublicKey(BigInteger y, BigInteger p, BigInteger g);

/*** Returns a DHPrivateKey created from the values: x (private), p (prime modulus) and* g (base generator).

** This method only must be implemented if an application wants to use Diffie-Hellman* cipher suites.

*/ public abstract DHPrivateKey getDHPrivateKey(BigInteger x, BigInteger p, BigInteger g);

/** * Returns a RSAPublicKey created from the values: modulus and publicExponent. * * This method only must be implemented if an application wants to use RSA cipher suites. */ public abstract RSAPublicKey getRSAPublicKey(BigInteger modulus,

BigInteger publicExponent);

/** * Returns a X509Certificate created from a DER encoded byte array. */ public abstract X509Certificate getX509Certificate(byte[] array) throws CertificateException;

/** * Returns a Principal created from a DER encoded byte array. * * A Principal in Sun’s point of view is the ASN.1 stucture: Name. This method is * the opposite of getEncodedPrincipal(Principal). */ public abstract Principal getPrincipal(byte[] array) throws IOException;

Page 29: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk Introduction

29

/** * Returns a DER encoded Name (Principal). * * A Principal in Sun’s point of view is the ASN.1 stucture: Name. This method * is the opposite of getPrincipal(byte[]). */ public abstract byte[] getEncodedPrincipal(Principal principal);

/** * Returns the desired MessageDigest object specified by the algorithm name. * * iSaSiLk makes use of the following MessageDigest algorithms: * "SHA", "MD5" */ public abstract MessageDigest getMessageDigest(String algorithm) throws

NoSuchAlgorithmException;

/** * Returns the desired Signature object specified by the algorithm name. * * iSaSiLk makes use of the following MessageDigest algorithms: * "DSA", "RawDSA" */ public abstract Signature getSignature(String algorithm) throws NoSuchAlgorithmException;

/** * Returns the desired Cipher object specified by its transformation. * * iSaSiLk makes use of the following cipher algorithms:

* "RSA/1/PKCS1Padding", "RSA/2/PKCS1Padding", "RC4", "RC2/CBC",* "IDEA/CBC", "DES/CBC", "3DES/CBC"

*/ public abstract Cipher getCipher(String algorithm) throws NoSuchAlgorithmException;

/** * Return a new instance of a SecureRandom number generator. This can be * the original java.security.SecureRandom or a better * generator if available (as when using IAIK JCE 2.5). */ public abstract SecureRandom getSecureRandom();}

As you already might have seen, not all of these methods have to be implemented by anapplication that wants to use another than the IAIK security provider. If, for instance, anapplication don´t intends to support Diffie Hellman cipher suites, there is no need forimplementing getDHPublicKey and getDHPrivateKey. Also getRSAPublicKey isoptionally, depending on whether to support RSA cipher suites or not.

Page 30: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk Introduction

30

For defining the default settings, the iSaSiLk package includes a IAIK provider specificimplementation of the SecurityProvider interface, which may serve as a guidance onhow to implement this interface: iaik.security.ssl.IAIKProvider:

import java.io.IOException;import java.math.BigInteger;import java.security.NoSuchAlgorithmException;import java.security.cert.X509Certificate;import java.security.cert.CertificateException;import java.security.Signature;import java.security.MessageDigest;import java.security.Principal;import javax.crypto.Cipher;import javax.crypto.NoSuchPaddingException;import javax.crypto.interfaces.RSAPublicKey ;import javax.crypto.interfaces.DHPublicKey;import javax.crypto.interfaces.DHPrivateKey;import javax.crypto.spec.DHPublicKeySpec;import javax.crypto.spec.DHPrivateKeySpec;import iaik.asn1.structures.Name;

// This class implements the SecurityProvider interface for the provider// IAIK.public class IaikProvider implements iaik.security.ssl.provider.SecurityProvider { // default constructor public IaikProvider() { } public DHPublicKey getDHPublicKey(BigInteger y, BigInteger p, BigInteger g) { return new iaik.security.dh.DHPublicKey(new DHPublicKeySpec(y, p, g)); }

public DHPrivateKey getDHPrivateKey(BigInteger x, BigInteger p, BigInteger g) {

return new iaik.security.dh.DHPrivateKey(new DHPrivateKeySpec(x, p, g)); }

public RSAPublicKey getRSAPublicKey(BigInteger modulus, BigInteger exponent) {

return new iaik.security.rsa.RSAPublicKey(modulus, exponent); }

public X509Certificate getX509Certificate(byte[] array) throws CertificateException {

return new iaik.x509.X509Certificate(array); }

public Principal getPrincipal(byte[] array) throws IOException { try { return new Name(array); } catch (Exception ex) { throw new IOException("Unable to parse Principal."); } }

Page 31: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk Introduction

31

public byte[] getEncodedPrincipal(Principal principal) { return ((Name)principal).getEncoded(); }

public MessageDigest getMessageDigest(String algorithm) throws NoSuchAlgorithmException {

if( algorithm.equals("MD5") ) return new iaik.security.md.Md5(); if( algorithm.equals("SHA") ) return new iaik.security.md.SHA(); try { return MessageDigest.getInstance(algorithm); } catch (Exception ex) { throw new NoSuchAlgorithmException(ex.toString()); } } public Signature getSignature(String algorithm)

throws NoSuchAlgorithmException { if( algorithm.equals("DSA") ) return new iaik.security.dsa.DSA(); if( algorithm.equals("RawDSA") ) return new iaik.security.dsa.RawDSA(); try { return Signature.getInstance(algorithm); } catch (Exception ex) { throw new NoSuchAlgorithmException(ex.toString()); } }

public Cipher getCipher(String algorithm) throws NoSuchAlgorithmException { try { return Cipher.getInstance(algorithm, "IAIK"); } catch (Exception ex) { throw new NoSuchAlgorithmException(ex.toString()); } }

/** * Return an instance of the default SecureRandom class set * in iaik.security.random.SecRandom. */ public SecureRandom getSecureRandom() { return iaik.security.random.SecRandom.getDefault(); }

}

For definitely knowing what type of objects have to be returned by the severalgetCryptographicObject methods, take a look at the import section of theIiakProvider source code printed above. Of interest are all the imported classesprefixed by java.security or javax.crypto that have no concern with anyexception or specification:

java.security.cert.X509Certificatejava.security.Signaturejava.security.MessageDigestjava.security.Principaljavax.crypto.Cipherjavax.crypto.interfaces.RSAPublicKey (optional)javax.crypto.interfaces.DHPublicKey (optional)

Page 32: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk Introduction

32

javax.crypto.interfaces.DHPrivateKey (optional)

iSaSiLk will operate on any proper JCE implementation supported by a providerimplementing/extending the several interfaces/classes stated above! In that way, iSaSiLkoffers a high degree on provider independence since all provider related code strictly isconcentrated to the SecurityProvider interface having the only task to tell iSaSiLkwhere to look for the requested cryptographic object implementations.

If, for instance, an application wishes to support Diffie Hellman cipher suites therebynot using the IAIK default provider, the corresponding SecurityProvider interfaceimplementing class has to contain implementations of the getDHPublicKey andgetDHPrivateKey methods returning proper DHPublicKey respectivelyDHPrivateKey objects instantiated from classes that implement the DHPublicKeyrespectively DHPrivateKey interfaces of the javax.crypto.interfaces package.

From this follows for the previous IiakProvider implementation example, that theiaik.security.dh.DHPublicKey class is an (IAIK provider specific) implementationof the javax.crypto.interfaces.DHPublicKey interface, since thegetDHPublicKey method accesses iaik.security.dh.DHPublicKey forinstantiating the DHPublilcKey object to be returned:

public DHPublicKey getDHPublicKey(BigInteger y, BigInteger p, BigInteger g) { return new iaik.security.dh.DHPublicKey(new DHPublicKeySpec(y,p,g));}

Generally an implementation of the SecurityProvider interface may follow twoways for telling iSaSiLk where to look for a provider specific implementation of somerequired cryptographic object:

• Specifying the provider´s name (for instance IAIK for the IAIK provider wheninstantiating a MessageDigest object):

public MessageDigest getMessageDigest(String algorithm) throws NoSuchAlgorithmException { try { return MessageDigest.getInstance(algorithm, "IAIK"); } catch (Exception ex) { throw new NoSuchAlgorithmException(ex.toString()); } }

• Directly by accessing the class which implements the corresponding interface,respectively extends the corresponding class (for instance, in the case of aMessageDigest object, we have to distinguish between MD5 and SHA, since bothare used by iSaSiLk):

Page 33: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk Introduction

33

public MessageDigest getMessageDigest(String algorithm) throws NoSuchAlgorithmException {

if (algorithm.equalsIgnoreCase("MD5") { return new iaik.security.md.MD5(); } else if (algorithm.equalsIgnoreCase("SHA") { return new iaik.security.md.SHA(); } else { throw new NoSuchAlgorithmException("Algorithm "+algorithm+"

not implemented."); }}

Notice, that both classes, iaik.security.md.MD5 andiaik.security.md.SHA extend the java.security.MessageDigest class.

The second way has the advantage not to explicitly specify any provider which may bepreferred when dealing with applets.

After successfully implementing the SecurityProvider interface you finally have totell iSaSiLk not to use the IAIK default provider by setting the new SecurityProviderimplementation through a call to the setSecurityProvider method of theiaik.security.ssl.SSLContext class (see 3.4.1) :

public static void setSecurityProvider(SecurityProvider provider);

Summing up, an application has to perform the following steps when intending to usesome other than (or beside) the IAIK security provider:

1. Installing and configuring the particular provider in mind (see [JCA]).

When you wish to configure the new provider dynamically, you may prefer to add itfrom inside your SecurityProvider implementation, so far as you don´t need toaccess provider dependent implementations before creating a new context object.

2. Implementing the SecurityProvider interface of theiaik.security.ssl.provider package thereby implementing theRSAPublicKey (optional), DHPublicKey (optional), DHPrivateKey (optional),

and Principal interfaces of the javax.crypto.interfaces respectivelyjava.security packages, and extending the cert.X509Certificate,Signature (iSaSiLk supports "DSA" and "RawDSA"), MessageDigest(iSaSiLk supports "SHA" and "MD5") and Cipher (iSaSiLk supports"RSA/1/PKCS1Padding", "RSA/2/PKCS1Padding", "RC4", "RC2/CBC","IDEA/CBC", DES/CBC", "3DES/CBC") classes of the java.securityrespectively javax.crypto packages.

Page 34: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk Introduction

34

Notice that "RSA/1/PKCS1Padding" and "RSA/2/PKCS1Padding" are notstandardized in javax.crypto.cipher. The transformation string"RSA/1/PKCS1Padding" means that a RSA en/decryption will be performed usingblock formatting according to PKCS#1 with block type 1; "RSA/2/PKCS1Padding"uses blocktype 2.

iSaSiLk will follow the same principle as used for any other Cipher object whenobtaining the corresponding provider dependent en/decryption object by accessingthe getCipher method of the actual SecurityProvider implementation(assuming that provider denotes the particular SecurityProviderimplementation):

Cipher rsa = provider.getCipher("RSA/1/PKCS1Padding");

rsa.init(ENCRYPT_MODE, key);

respectivelyrsa.init(DECRYPT_MODE, key);

byte[] rsa_crypted = rsa.doFinal(data);3. Setting the SecurityProvider implementation by calling the

setSecurityProvider method of the iaik.security.ssl.SSLContextclass:

SSLContext.setSecurityProvider(securityProvider);

If no particular SecurityProvider interface implementation is requested, perdefault the IAIK security provider will be prefered.

3.3.2 Certificates, Keys and Parameters

Since our SSL server shall be able to support all the cipher suites implemented byiSaSiLk - and that are all the SSLv3 cipher suites except for Fortezza - it is necessary toprovide all the certificate types, keys and parameters that may be required throughout aSSL handshake procedure (remember table 1.2):

� Certificate types: RSA, DH, DSA

� Private keys: RSA, DH, DSA

� Temporary keys/parameters: RSA, DH

Page 35: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk Introduction

35

As introduced in sections 3.1 and 3.2, the security features of a SSL socket respectivelySSL server socket mainly are determined by their appropriate contexts. For the current taskof providing the different certificates and keys, the following consequence has be drawnfor the further proceeding: At first it has to be obtained the particularcertificate/key/parameter. Following this, the particular certificate/key/parameter must bepresented to the actual context, and finally the context has to be incorporated into thesocket object claiming for it.

For the first step we will assume that all the required server certificates and keys -except for temporary DH parameters which we will generate separately - are stored as DERencoded IAIK KeyAndCertificate structures on the local host in .der files located in a subfolder certs of the actual calling directory. DER denotes the distinguished encoding rulesfor encoding ASN.1 structures.

However, for our current task it is not of main interest, how to create or get certificates1

and keys. Rather we want to ´load´ them into the actual server context thereby assumingthat the several certificate and key files already exist in the certs directory. Eachparticular application may follow its own strategy for obtaining certificates and keymaterial from some available source. For our specific example, we will ´read in´ therequired entities from DER encoded files.

Since certificate chain and belonging private key of each specific type are stored withinthe same file, we have to perform the following steps for obtaining the requestedauthentication material :

1. Reading in certificate chain and private key from the actual DER file therebycreating a KeyAndCertificate object of the iaik.utils package:

import iaik.utils.KeyAndCertificate; ...

KeyAndCertificate kac;

kac = new KeyAndCertificate("certs/serverRSA1024.der");

respectivelykac = new KeyAndCertificate("certs/serverDSA1024.der");

respectivelykac = new KeyAndCertificate("certs/serverDH1024.der");

2. Decrypting the password based encrypted private key according to PKCS#8 PrivateKey Information Syntax Standard after extracting it from the just createdKeyAndCertificate object:

import iaik.pkcs.pkcs8.EncryptedPrivateKeyInfo; ...

1 Note that the demo samples included in the iSaSiLk distribution use a keystore for obtaining keys andcertificates (see the corresponding information html files)

Page 36: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk Introduction

36

EncryptedPrivateKeyInfo epki;

epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey();epki.decrypt("This is the passphrase!");

Making an anticipation to the discussion of the SSL context and socket classes withinsection 3.4, setting the several properties of a context object is done by means of particularsetproperty methods.

Now, if we assume that we already have created a SSLServerContext object bywriting

SSLServerContext serverContext = new SSLServerContext();

we are ready to set the context´s certificate and private key entries:

// set the RSA certificate/private key for RSA cipher suitesserverContext.setRSACertificate(kac.getCertificateChain(),

epki.getPrivateKey());

// set the DSA certificate/private key for DSA cipher suitesserverContext.setDSACertificate(kac.getCertificateChain(),

epki.getPrivateKey());// set the DH certificate/private key for DH cipher suitesserverContext.setDHCertificate(kac.getCertificateChain(),

epki.getPrivateKey());;

Note that KeyAndCertifcate´s method getCertificateChain() returns aX.509v3 certificate chain as required by the SSL protocol, starting with the servercertificate and leading to the root certification authority.

The several private keys are presented the server context object simultaneously with thecorresponding certificates by means of the set*Certificate methods.

In order for being able to support ephemeral and anonymous Diffie Hellman ciphersuites, and exportable RSA cipher suites if the certificate´s public key claims for more than512 bits, the actual context has to be supplied with the required temporary keys.

RSA temporary key pairs again may be read in from a DER encoded files holding aDER encoded private key structure1. First a RSA private key object is created from a DERfile, then the corresponding public key is filtered out, and at last the temporary RSA keypair is generated from the private and public key:

RSAPrivateKey tsk = new RSAPrivateKey( new FileInputStream("certs/tempRSAPrivateKey.der"));

PublicKey tpk = tsk.getPublicKey(); KeyPair tempKeyPair = new KeyPair(tpk, tsk);

1 Note that the demo samples included in the iSaSiLk distribution use a keystore for obtaining keys andcertificates (see the corresponding information html files)

Page 37: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk Introduction

37

Instead of using an AlgorithmParameterGenerator, we will directly construct thetemporary Diffie Hellman parameters using the BigInteger class of the java.mathpackage and the DHParameterSpec class of the javax.crypto.spec package:

BigInteger p = new BigInteger("da583c16d98522...", 16); BigInteger g = BigInteger.valueOf(2); DHParameterSpec dhparam = new DHParameterSpec(p, g);

The demo SSLServer implementation of the iSaSiLk library also includes an examplefor using the AlgorithmParameterGenerator class of the java.security.spec package.

After creating temporary RSA key pair and DH parameters, they have to be put to theserver context object:

serverContext.setRSATempKeyPair(tempKeyPair); serverContext.setDHParameter(dhparam);

Throughout the process of providing the several certificates, keys and parametersdifferent failures may occur that should be treated by a proper exception handling. AGeneralSecurityException may be thrown when dealing with security objects (JDK 1.2),key management may cause a InvalidKeyException, trying to access a not implementedalgorithm may lead to a NoSuchAlgorithmException, and finally, file operations make itnecessary to include I/O exception handling, leading to the following program codefragment for supplying the several certificate types and keys in order to support all thecipher suites:

SSLServerContext serverContext = new SSLServerContext();try { // specify the DH parameters: BigInteger p = new BigInteger("da583c16d98522...", 16); BigInteger g = BigInteger.valueOf(2); DHParameterSpec dhparam = new DHParameterSpec(p, g); // set the DH parameter for ephemeral cipher suites serverContext.setDHParameter(dhparam);

// create certificates and private keys and set them to the context: KeyAndCertificate kac; EncryptedPrivateKeyInfo epki; // set the RSA certificate/private key for RSA cipher suites kac = new KeyAndCertificate("certs/serverRSA1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("This is the passphrase!"); serverContext.setRSACertificate(kac.getCertificateChain(),

epki.getPrivateKey());

// set the DSA certificate/private key for DSA cipher suites kac = new KeyAndCertificate("certs/serverDSA1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("This is the passphrase!");

Page 38: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk Introduction

38

serverContext.setDSACertificate(kac.getCertificateChain(), epki.getPrivateKey());

// set the DH certificate/private key for DH cipher suites kac = new KeyAndCertificate("certs/serverDH1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("This is the passphrase!"); serverContext.setDHCertificate(kac.getCertificateChain(),

epki.getPrivateKey());

// set the temporary RSA key pair for RSA_EXPORT cipher suites RSAPrivateKey tsk = new RSAPrivateKey(

new FileInputStream("certs/tempRSAPrivateKey.der")); PublicKey tpk = tsk.getPublicKey(); KeyPair tempKeyPair = new KeyPair(tpk, tsk); serverContext.setRSATempKeyPair(tempKeyPair);} catch (InvalidKeyException ex) { System.out.println("InvalidKeyException: "+ex.getMessage()); System.exit(0);} catch (NoSuchAlgorithmException ex) { System.out.println("NoSuchAlgorithmException:"+ex.getMessage()); System.exit(0);} catch (GeneralSecurityException ex) { System.out.println("GeneralSecurityException:"+ex.getMessage()); System.exit(0);} catch (IOException ex) { System.out.println("IOException: "+ex.getMessage()); System.out.println("No server certs found!"); System.exit(0);}

So far all the required certificates, keys and parameters have been created andsuccessfully presented to the server context object, leaving the only task to doincorporating the server context object to the corresponding server socket object:

SSLServerSocket server = new SSLServerSocket(port, serverContext);

After incorporating the server context object to the server socket object, we can closeour discussion about the basic preconditions for implementing one (the server) side of aSSL connection.

Later, when the SSLClientContext class will be introduced within chapter 3.4.1.1,you will notice, that on the client´s side of a SSL connection certificates and key materialare not directly obtained by the client. Rather a particular client trust decider has toimplemented for fulfilling the task of certificate and key obtaining.

The next chapter will introduce the several socket and context classes implementationsof the iSaSiLk SSLv3 project.

Page 39: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk Introduction

39

3.4 SSL Socket And SSL Context Classes

It already has been mentioned that the SSLSocket class inherits from the Socketclass of the java.net package and correspondingly the SSLServerSocket classinherits from the java.net.ServerSocket class extending them about the SSLsecurity features. Since objects of the SSLContext classes determine the securityproperties of SSLSocket respectively SSLServerSocket objects, it would be preferableto first introduce the SSLContext classes implementations, serving as a basis for thesubsequent discussion of the SSLSocket classes.

The main interaction process between SSL contexts and SSL sockets already has beenmentioned:

First it has to be created a SSLClientContext (or SSLServerContext) object:

SSLClientContext clientContext = new SSLClientContext();

or

SSLServerContext serverContext = new SSLServerContext();

Following this, a new SSLSocket (respectively SSLServerSocket) object is created andinitialized with the particular context object generated above:

SSLSocket clientSocket = new SSLSocket(serverName, serverPort, clientContext);

respectively

SSLServerSocket = New SSLServerSocket(port, serverContext);

Between these two tasks of creating a SSL context object and later using it as parametervalue for instantiating a SSL socket object, the user optionally may supply the contextobject with particular properties. Otherwise the context objects will use default settings fordefining the security features of the corresponding SSL socket objects.

Goal of the following description of the SSLContext classes is the presentation of theseveral context properties that can be set by the user.

3.4.1 The SSLContext Class

Instances of the SSLClientContext and SSLServerContext classes are used todefine the security properties of corresponding SSLSocket respectively

Page 40: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

40

SSLServerSocket objects for implementing the client respectively server side of a SSLconnection.

Both, SSLClientContext and SSLServerContext classes are members of theiaik.security.ssl package making it necessary to import this package when intending toimplement client or/and server side of a SSL connection:

import iaik.security.ssl.*

The SSLServerContext class is implemented as a subclass of theSSLClientContext class extending it about the member classes and methods that arenecessary to fulfill the several certificate, key and parameter conditions for supporting anydesired cipher suite (remember: on the server side, certificates and keys for authenticationand key exchange are immediately supplied to the actual SSLServerContext object,whereas on the client side certificates and keys are obtained by a special client trustdecider; see 3.4.1.1.5.3):

public class SSLServerContext extends SSLClientContext implements Cloneable

Instances of the SSLServerContext class will be cloneable since it may be necessaryfor cryptography parameter renegotiation to create field-to-field copies of an existingcontext object (see section 3.4.3.3).

The SSLClientContext class itself implements the abstract class SSLContextdefining a set of abstract methods for managing all the properties that are basicallynecessary for realizing any kind of SSL socket:

public class SSLClientContext extends SSLContext implements Cloneable

All the abstract methods of the public public abstract class SSLContext providetemplates for setting respectively getting the several properties of a particular SSL Socketimplementation:

• public abstract CipherSuite[] getEnabledCipherSuites();

public abstract void setEnabledCipherSuites(CipherSuite[] enabledCipherSuites);

for obtaining respectively setting the particular Cipher Suites supported by the actualSSL context implementation.

• public abstract CompressionMethod[] getEnabledCompressionMethods();

public abstract void setEnabledCompressionMethods(CompressionMethod[]

enabledCompressionMethods);

for obtaining respectively setting the particular compression methods supported by theactual SSL context implementation.

Page 41: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

41

• public abstract Random getRandomGenerator();

public abstract void setRandomGenerator(Random randomGenerator);

for obtaining respectively setting a specific random generator implementationresponsible for generating all the random numbers that are required throughout thehandshake procedure.

• public abstract SessionManager getSessionManager();

public abstract void setSessionManager(SessionManager sessionManager);

for obtaining respectively setting a specific session manager implementation that isresponsible for the actual session caching strategy.

• public abstract TrustDecider getTrustDecider();

public abstract void setTrustDecider(TrustDecider trustDecider);

for obtaining respectively setting the particular trust decider implementation that isresponsible for the actual certificate trusting strategy.

If you think back to section 3.3.1 you will remember that iSaSiLk offers a high degree ofprovider independence: an application that wishes to use another than the default IAIKSecurity Provider only has to implement the SecurityProvider interface of theiaik.security.ssl.provider package. For enabling a specificSecurityProvider implementation, it has to be set by calling thesetSecurityProvider method of the SSLContext class. The currently installedsecurity provider can be obtained from the context by using the setSecurityProvidermethod:

• public static void getSecurityProvider();

public static void setSecurityProvider(SecurityProvider provider);

Note, that in contrast to all the methods listed above, the two methods for obtainingrespectively setting some particular SecurityProvider implementation, are not declaredas being abstract. They are already implemented by the SSLContext class itself,namely as static methods, since only one unique system-wide security provider will benecessary.

All the listed properties (cipher suites, compression methods, session manager, ...) haveto be incorporated by both, SSLClientContext objects as well as SSLServerContextobjects. SSLServerContext objects additionally come up with the several certificate,key and cryptographic parameter features. Hence, the following SSLClientContextclass discussion introduces the basic main properties of any SSL context object, followedby a description of the SSLServerContext extensions.

Page 42: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

42

3.4.1.1 The SSLClientContext Class

The SSLClientContext class implements the SSLContext interface and provides allthe basic properties that are necessary for managing the security features of the clientsocket of a SSL connection: supported cipher suites, supported compression methods,random number generator, session manager and trust decider. All these entities either canbe set by means of particular user directives or might be established by agreeing with somepredefined default settings.

During the following discussion, keep in mind that all the basic properties also must besupported by any specific SSLServerContext implementation.

3.4.1.1.1 Random Number Generator

It already has been introduced several times how to create an SSLClientContext objectby instantiating the SSLClientContext class:

SSLClientContext clientContext = new SSLClientContext();

If we agree with this line of program code, we make use of the SSLClientContextdefault empty constructor that first has to create a default random number generator basedon the current time, which may last a few seconds1. The task of the random numbergenerator is the generation of all random numbers that are required throughout the SSLhandshake procedure:

import java.util.Random; Random random_generator;

1 Depending on the platform your application is running, the initialization of the random number generator may last less or more time.For increasing speed, immediately after starting your application you may create a new thread which initializes the SecureRandomgenerator. In this way, the seed already has been generated the first time random numbers are requested, e.g.:

(new Thread() { public void run() { try { setPriority(Thread.MIN_PRIORITY); random.nextInt(); System.out.println("random number generator initialized..."); } catch (Exception ex) { ex.printStackTrace(); } } }).start();

Alternatively you may implement your own seed generator for providing a faster way of random number generation.

Page 43: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

43

If we intend to implement our own random generator - for instance by creating aSecureRandom object of the java.security package providing a crytpographically strongpseudo-random number generator that is based on the SHA-1 hash algorithm, we directlyhave to supply it when creating the context object. The SSLClientContext class therefore isequipped with a proper constructor:

public SSLClientContext(SecureRandom random)

Suppose, we have created a new Random (or SecureRandom) object serving as ourspecific random number generator. Instead of using the SecureRandom default emptyconstructor, we assume that we have implemented our own seed generation algorithm forseeding the SecureRandom object:

import java.security.*;import java.util.Random; ...

byte[] seed = derived from some particular seed generation algorithm;SecureRandom randomGenerator = new SecureRandom(seed);

Following this, we directly supply the self-designed random number generator whencreating the SSLClientContext object:

SSLClientContext context = new SSLClientContext(randomGenerator);

Note, that we could use the setRandomGenerator(...) method for defining aspecific random generator. However, we will prefer to set a self-designed random numbergenerator directly when creating the context object, since first time-consuming creating thedefault generator by using the default SSLClientContext constructor and subsequentlyoverwriting the just created generator by the new one, will cost a superfluous amount oftime.

For later obtaining actual - default or user defined - random number generator from thecontext, we may use the getRandomGenerator method:

Random randomNumberGenerator;

RandomNumberGenerator = context.getRandomGenerator();

Keep in mind that the same proceeding has to be used when supplying a self-designedrandom number generator for a SSLServerContext object:

...

SSLServerContext serverContext =

new SSLServerContext(randomGenerator);

Page 44: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

44

...

Random randomNumberGenerator;RandomNumberGenerator = serverContext.getRandomGenerator();

When first invoking the - default or supplied by a self-designed random numbergenerator - SSLClientContext constructor, all the other properties (enabled ciphersuites and compression methods, session manager and trust decider) of the new createdSSLClientContext object are initialized with default settings that later may - or may not- be actualized by particular user settings.

3.4.1.1.2 Enabled Cipher Suites

At the beginning of the lifetime of a SSLClientContext object, the constructor enablesall the cipher suites implemented by iSaSiLk. Remember, that iSaSilk implements all theSSLv3 cipher suites except for Fortezza (see 1.1.1).

Every single cipher suite defines a specific key exchange algorithm, symmetricencryption algorithm and a secure hash function (see 1.1.1). Client and server have toagree on one particular cipher suite that is supported by both of them. This negotiatedcipher suite is called active cipher suite and decisively determines the handshake process.An active cipher suite is selected among the enabled cipher suites that are common forboth, SSL client context and SSL server context.

An enabled cipher suite is a cipher suite that is supported by the actual SSLContextobject (respectively SSLSocket object supplied by the context object). If an applicationdoesn´t want - or is not able - to support all the possible cipher suites, it has the ability torearrange the default settings after it has created the particular SSLContext object.

Since the enabled cipher suites are defined as an array of cipher suites within theSSLClientContext class implementation, we also have to define an array of ciphersuites every time we want to actualize the enabled cipher suites of a context object - even ifwe only want to enable one single cipher suite:

//enabled_cipher_suites as an array of cipher suites in SSLClientContext class:

CipherSuite[] enabled_cipher_suites;

Unlike defining a specific random number generator as described in the previoussection, we cannot directly enable particular cipher suite(s) by means of one of the twoSSLClientContext constructors. Rather we have to make use of the SSLClientContext´ssetEnabledCipherSuites(CipherSuite[] enabledCipherSuites) method.Supposing we intend to only enable the two cipher suites SSL_RSA_WITH_IDEA_CBC_SHAand SSL_DH_DSS_WITH_DES_CBC_SHA, we first have to declare an array for being able tohold two cipher suites:

Page 45: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

45

CipherSuite[] cs = new CipherSuite[2];

Following this, we will fill the array with our two particular cipher suites and thensupply it to the actual context object:

cs[0] = CipherSuite.SSL_RSA_WITH_IDEA_CBC_SHA; cs[1] = CipherSuite.SSL_DHE_DSS_WITH_DES_CBC_SHA; //enable the cipher suites context.setEnabledCipherSuites(cs);

Automatically two CipherSuite objects are created and supplied with the particularparameter values for implementing the SSL_RSA_WITH_IDEA_CBC_SHA respectivelySSL_DHE_DSS_WITH_DES_CBC_SHA cipher suites. The two cipher suites are assigned tothe cs array.

For obtaining all the actually enabled cipher suites of a particular context object, wemay utilize the context´s getEnabledCipherSuites() method. If we, for instance, areinterested in the names of the enabled cipher suites, we may query them by the followinglines of program code:

CipherSuite[] enCs = context.getEnabledCipherSuites();System.out.println("Enabled cipher suites:");for (int i = 0; i < enCs.length; i++) { System.out.println("cipher suite no. "+ i +": " + enCs[i].getName());

}

First we have defined a cipher suite array of an unspecified length and filled it with allthe enabled cipher suites by calling the getEnabledCipherSuites()method of theactual context object. Then we have stepped through the array thereby printing the name ofeach cipher suite we have been passing by. The name of a specific cipher suite object isobtained by using the getName() method of the CipherSuite class.

So far we have learned enough for enabling particular cipher suites, or making use of allthe implemented cipher suites by only creating a default SSLClientContext object.Furthermore, we are able to obtain the enabled cipher suites of a context object.

Now we want look somewhat behind the iSaSilK cipher suite implementation. Perhapsyou will skip this section and directly go to the discussion of compression methods(3.4.1.1.3) or session manager (3.4.1.1.4).

The basic class throughout iSaSilk´s cipher suite environment is the CipherSuiteclass:

public class CipherSuite

A particular CipherSuite object cannot be created by directly calling a constructor.Rather the name of the specific cipher suite has to be used:

Page 46: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

46

CipherSuite cipher_suite = CipherSuite.name_of_CipherSuite

Since iSaSilK implements all the SSLv3 cipher suites (except for Fortezza) any knowncipher suite name may be set for name_of_cipherSuite. Automatically a newCipherSuite object is instantiated and supplied with all the parameter values that arenecessary to implement the particular cipher suite. The constructor of the CipherSuiteclass itself is declared as private forbidding to call it from outside the CipherSuite class:

private CipherSuite(String cipherSuiteName, String cipherAlgorithm,

int id1, int id2, int keyMaterial,

int expandedKeyMaterial, int IVSize,

boolean isExportable, boolean implemented)

where:

cipherSuiteName .......... the name of the particular cipher suite

cipherAlgorithm ............. the name of the symmetric cipher of this suite

id1, id2 ............................ a two byte identifier of this cipher suite

keyMaterial ..................... the number of bytes from the key block that are

used for generating the write keys

expandedKeyMaterial ... the number of bytes actually fed into the

encryption algorithm

IVSize ............................... the number of bytes of the initialization vector

for running the symmetric cipher in CBC mode

isExportable....................... is this cipher suite exportable?

implemented ................... is this cipher suite already implemented by iSaSilK?

(false for Fortezza, true for all others)

Now, what really happens when we wish to create a SSL_RSA_WITH_IDEA_CBC_SHAcipher suite object by writing

CipherSuite cipher_suite = CipherSuite.SSL_RSA_WITH_IDEA_CBC_SHA

within our SSLClient (or SSLServer) implementation?

Let´s take a look inside iSaSiLk´s CipherSuite class where the desired cipher suiteobject is instantiated by calling the private CipherSuite constructor and providing itwith the particular parameter values:

public static final CipherSuite SSL_RSA_WITH_IDEA_CBC_SHA =

new CipherSuite("SSL_RSA_WITH_IDEA_CBC_SHA", "IDEA.CBC.SSL",

0x00, 0x07, 16, 16, 8, false, true);

Page 47: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

47

By means of this lines of program code actually a CipherSuite object is created thatis ready for supporting the SSL_RSA_WITH_IDEA_CBC_SHA cipher suite using RSA forkey exchanging, SHA for MAC computation, and a 128 bit key for data encrypting withIDEA in CBC mode.

The CipherSuite class is equipped with a variety of methods for querying for specificinformation about a cipher suite object. So, for instance, you may be interested in thecipher suite object´s name, it´s ID, cipher algorithm and key exchange algorithm. Maybe,for some purpose you only wish to know whether the symmetric cipher is a block or streamcipher making it necessary to ask for the corresponding information. All this is done byusing the several get* methods of the CipherSuite class. Presuming the existence ofsome cipher suite object with name c_s, we may get particular information by typing:

// get the cipher type (STREAM = 1, BLOCK = 2)int cipherType = c_s.getCipherType();

// get the name of the encryption algorithmString cipher_alg = c_s.cipherAlgorithm();// get the name of the MAC algorithmString mac_alg = c_s.macAlgorithm();// get the name of the key exchange algorithmString kex_alg = c_s.getKeyExchangeAlgorithm();// ask, if cipher suite is exportableboolean export = c_s.isExportable();// get the key size limit for certificateint limit = c_s.getKeySizeLimit();// get the hash size for message digestsint hashsize = c_s.hashSize();// get the number of bytes used for generating the write keysint keymaterial = c_s.keyMaterial();// get the number of bytes actually fed into the encryption algorithmint exp_keymaterial = c_s.expandedKeyMaterial();// get the the number of bytes used for the initialization vectorint ivsize = c_s.IVSize();

For obtaining all the cipher suites implemented by iSaSiLk, the CipherSuite classprovides the getDefault() method returning an array of all the cipher suites thatactually are implemented. This method is used by the constructor of theSSLClientContext object for initially enabling all the implemented cipher suites when anew SSLClientContext object is created:

CipherSuite[] enabled_cipher_suites;enabled_cipher_suites = CipherSuite.getDefault();

Since getDefault() is a static method, no extra CipherSuite object must be created foraccessing all the implemented cipher suites.

Remember that you have to take care for providing several certificate types andcryptographic keys/parameters if your SSLClient (respectively server) implementation

Page 48: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

48

shall be able to correctly support any desired cipher suite type (consult chapter 1.1.1, table1.2 in particular). On the server side of the connection, certificates and keys/parameters aremanaged by directly binding them to the specific context object (see chapter 3.3.2), on theclient side a trust decider has to be implemented for managing certificate requests comingfrom the server (see section 3.4.1.1.5).

A server also may force a cipher suite renegotiation any time during the actual client-server communication to determine a new cipher suite for the current session (see section3.4.3.3).

Similarly to the negotiation of a specific cipher suite, client and server also have toagree upon a particular compression method defining the algorithm for compressing thedata records of the current session. Since data compression is an optional task andgenerally yet not done by SSLv3, the next chapter only gives a short description aboutsetting and getting the actual compression method of a context object.

3.4.1.1.3 Enabled Compression Methods

The basic concept for managing the compression methods within the iSaSilK SSLv3environment resembles the cipher suite management system.

Again, when a SSLClientContext object is created the first time, per default allimplemented compression methods are enabled by the SSLClientContext constructor incalling the getDefault() method of the CompressionMethod class of theiaik.security.ssl package.

CompressionMethod[] enabled_compression_methods;enabled_compression_methods = CompressionMethod.getDefault();

Since currently the only defined compression method of SSLv3 is the NULL method,meaning that none compression is performed on the data records, the only compressionmethod that can be returned by the CompressionMethod.getDefault() method alsois the NULL method.

However, each application may add compression methods as needed. New compressionmethods have to be registered within the compression methods repository which ismaintained by the abstract CompressionMethod class of the iaik.security.sslpackage. Each particular compression method wishing to be registered must extend theCompressionMethod class by implementing the following abstract methods:

/** * Returns the name of the compression method. * * @return the name of thise compression method */ public abstract String getName();

Page 49: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

49

/** * Returns the identifier of the compression method. * * @return the identifier of the compression method */ public abstract int getID();

/** * Performs the compress operation. Implemented by a subclass. * * @param in the byte array holding the data to be processed * @param inOff the offset indicating the start position within the * in byte array * @param inLen the number of bytes to be processed * @param out the byte array for holding the result * @param outOff the offset indicating the start position within the * out byte array * @return the number of bytes that are stored in the out byte array */ public abstract int compress(byte[] in, int inOff, int inLen,

byte[] out, int outOff) throws DataFormatException;

/** * Performs the decompress operation. Implemented by a subclass. * * @param in the byte array holding the data to be processed * @param inOff the offset indicating the start position within the * in byte array * @param inLen the number of bytes to be processed * @param out the byte array for holding the result * @param outOff the offset indicating the start position within the

* out byte array * @return the number of bytes that are stored in the out byte array */ public abstract int decompress(byte[] in, int inOff, int inLen,

byte[] out, int outOff) throws DataFormatException;

The getName() and getID() methods provide information about the particularcompression method, compress(...) and decompress(...) actually implement thespecific compression/decompression algorithmus. For registration purposes it is importantthat each particular compression method implementation includes the empty defaultconstructor!

For providing an example on how to implement a compression method, thedemo.compression package of the iSaSiLk demo library contains a sample class - calledXorCompression - which actually does not perform any compression at all, but only - forthe purpose of demonstration - performs a simple XOR operation with a predefined value(0xAA)1: 1 Note that each compression method is assigned a specific ID (0 in the case of the NULL method). So, choose arbitrary compressionmethod IDs only for the purpose of testing. In the future - when other compression methods will be defined beside the NULL method -consult the corrresponding documentation for assigning the right predefined ID.

Page 50: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

50

package demo.compression;

import iaik.security.ssl.*;

/** * This class shows an example of how to implement a compression * method. This demo does not really compress the content; it just * performs a XOR operation with a defined value (0xAA). */public class XorCompression extends CompressionMethod {

// the name of this compression method private final static String name = "XOR Compression Demo"; // the id of this compression method private final static int id = 0x80; // the byte to xor the data with private final static byte xor = (byte)0xAA; /** * Default Constructor. Needed for registration. */ public XorCompression() { }

/** * Returns the name of this compression method. */ public String getName() { return name; }

/** * Returns the identifier of this compression method. */ public int getID() { return id; }

/** * Performs a simple XOR operation. * * @param in the byte array holding the data to be processed * @param inOff the offset indicating the start position within the * in byte array * @param inLen the number of bytes to be processed * @param out the byte array for holding the result * @param outOff the offset indicating the start position within the * out byte array * @return the number of bytes that are stored in the out byte array */ public int compress(byte in[], int inOff, int inLen, byte out[],

int outOff) { for (int i=0; i<inLen; i++) out[outOff+i] = (byte)(in[inOff+i] ^ xor);

Page 51: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

51

return inLen; }

/** * Performs a simple XOR operation. * * @param in the byte array holding the data to be processed * @param inOff the offset indicating the start position within the * in byte array * @param inLen the number of bytes to be processed * @param out the byte array for holding the result * @param outOff the offset indicating the start position within the * out byte array * @return the number of bytes that are stored in the out byte array */

public int decompress(byte in[], int inOff, int inLen, byte out[], int outOff) {

for (int i=0; i<inLen; i++) out[outOff+i] = (byte)(in[inOff+i] ^ xor);

return inLen; }}

For actually registering the new compression method, just call the default constructor:

new demo.compression.XorCompression();

After registering a new compression method, it has to be added to the set ofenabled compression methods. An enabled compression method is a compression methodthat is supported by the actual SSLContext object (respectively SSLSocket object suppliedby the context object). Both, client and server have to agree upon one of the enabledcompression methods to define the active compression algorithm that is used for datarecord compression during the current session.

As already accustomed from the cipher suite management system, a particularcompression method may be supplied to the actual context object by using thesetEnabledCompressionMethods(CompressionMethod[] enabledCompMeths)

method. So, for instance, for enabling the NULL and XOR compression methods, we onlyhave to call getDefault() on the CompressionMethod class. Since both methods arealready registered - the one per default and the other by explicitly calling its constructorabove - getDefault() will return both methods:

//get the registered compression methods CompressionMethod[] cm = CompressionMethod.getDefault(); //enable the compression methods by supplying it to the

//context context.setEnabledCompressionMethods(cm);

Page 52: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

52

Note the kind of redundancy in the code sample from above: when creating a newSSLClient(Server)Context object, the corresponding constructor automatically will enableall registered compression methods by implicitly calling the getDefault() method ofthe CompressionMethod class. However, an application may use thesetEnabledCompressionMethods method for changing the default setting aftercreating a SSLContext!

To obtain the enabled compression methods of a context object, we may use thegetEnabledCompressionMethods() method:

CompressionMethod[] enabled_compressionMethods =

context.getEnabledCompressionMethods();

Every single CompressionMethod object is identified by a specific name and a particularID that may be queried by the getName() respectively getId() methods. Supposingthat cm denotes a CompressionMethod object, we may write:

String name = cm.getName();

int id = cm.getID();

The cipher suite and compression method actually used for a particular session aredefined by the active cipher suite respectively active compression method. Active ciphersuites and compression methods are kept in mind for a particular time interval, making itpossible to be reused within a later session. It is the responsibility of the implementedsession manager to determine the session caching strategy. The session manager will beintroduced within the following chapter.

3.4.1.1.4 The Session Manager

When client and server start a new communication, they may negotiate completely newcryptographic parameters or they may agree on specifications they already have usedthroughout a previous session or throughout another session that temporary is active.

If the client - that usually initiates a handshake dialogue - intends to rely on the securityspecifications of some former or existing session, it may suggest this the server by sendingthe SessionID of the particular session in mind. If the server accepts the client´s proposal, itanswers by resending the same SessionID. Following this, client and server perform ashortened handshake process for generating keys for data encryption and MAC calculationbased on the same cipher suite and master secret that already have been used during thesession identified by the specific SessionID.

However, if the server for some reason is not willing to ´reestablish´ a connectionsuggested by the client, it refuses the client´s proposal by creating and resending an entire

Page 53: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

53

new session identifier. In this case client and server have to go through a completehandshake dialogue for negotiating the cryptographic specifications of the new session.

For being able to support the reuse of former security negotiations, bothcommunication partners have to implement some kind of session caching management.Within the iSaSiLk environment the session caching management is done by means of fourclasses leaving some scope for the user to implement her/his own session caching strategy:

public class SessionID class for implementing a session identifier as an arbitrarybyte sequence generated by the server for identifying someactive session or some session to be resumed

public class Session class for implementing a session object responsible for holdingall the information that is necessary for resuming an oldsession

public interface SessionManager interface of abstract methods for providing the usera template for implementing his own sessioncaching strategy

public class DefaultSessionManager implements SessionManager class for providing a simple example of an actual

session manager implementation; an applicationmay rely on this default session manager or itmay implement its own session manager;

During the SSLClient introduction within chapter 3.2 it has been described how to opena SSLClientSocket object and subsequently open an output respectively input stream forenabling the writing/reading to/from the SSL socket:

SSLSocket s = null;// create a SSLClientContext objectSSLClientContext context = new SSLClientContext();// create a SSLSocket object for connecting to the specified// server on the specified port numbers = new SSLSocket(serverName, serverPort, context);// open output/input streams to write/read to/from the socketPrintWriter os = new PrintWriter(s.getOutputStream());DataInputStream is = newDataInputStream(s.getInputStream());

When opening an stream on the socket object, the socket class´ getOutputStream(),respectively getInputStream() method starts the handshake dialogue by calling thesocket´s starthandshake() method which itself invokes the handshaker by means ofthe doHandshake() message. The Handshaker class is an abstract iSaSiLk class that isextended by the Client- respectively ServerHandshaker for directing the initialhandshake dialogue. Client and ServerHandshaker are instantiated by the appropriateconstructor when creating a SSLClientSocket respectively SSLServerSocket object.

Page 54: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

54

Since we are located at the client´s side of a SSL connection to be established, the(client)handshaker first has to query if there already has been any communication sessionwith the server identified by its Inet address. Therefore the handshaker makes a call to theproper session manager:

Session session;session = context.getSessionManager().getSession(socket, null);

The session manager itself makes use of its getSession(SSLSocket socket,SessionID sessionID) method to search the session cache for any session thatmatches to the inet address of the server. It is the responsibility of the actuallyimplemented session manager to determine the searching strategy for cached sessions.Since the default session manager stores sessions within a hashtable using the peer´saddress as key, the default session manager´s getSession method is implemented toextract the inet address of the peer from the socket object that looks for a session:

Session s = (Session)activeSessions.get(socket.getInetAddress());

Note, that since activeSessions is an instance of the java.util.Hashtable class, anexplicit cast is necessary to obtain a Session object.

If a corresponding session is detected, the session manager reports it to the handshakerthat uses the session´s inherent sessionID for suggesting the server to resume the particularsession (see illustration of figure 3.1).

Page 55: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

55

Figure 3.1: The Client Session Manager

On the other side of the connection, when the server handshaker - responsible fordirecting the handshake on the server side - receives a client´s Hello message including aparticular sessionID, it also asks its session manager for searching the cache for containingany appropriate session (see figure 3.2). In contrast to the client session manager, theserver session manager not only specifies the client´s inet address - by extracting it fromthe supplied SLL socket object - when calling its getSession method. Since the server isinterested in the one particular session the client has indicated by sending the appertainingsessionID, also this sessionID has to be specified:

Session session;

session = context.getSessionManager().getSession(socket,

ch.getSessionID());

Thereby ch denotes the received ClientHello message containing the particularsessionID.

Session Manager

Client Handshaker

Client

1

2

3

suggest server toresume a sessionidentified by SessionID

connect to server

4

has there already beenany session with this server?

have detected a former session with this server and report youcorresponding SessionID

The Client orders its client handshaker to connect to a particular server. Before doing so, the handshakerasks the session manager to query the session cache if there already has been a session with this server.If the session manager detects a match in the cache, it reports the corresponding ID to the handshakerwhich suggets the server to resume this particular session.

Page 56: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

56

Server

Session Manager

Server Handshaker´ tell client that session with SessionID will be resumed

5

1

client has sent a particular SessionID

for resuming a former session

3

perform handshake with requesting client

4

have detected a former session with this client and this SessionID in

the cache!

The server session manager searches the cache for any session that has been held with the requesting clientduring the last resume period. If a match is found, a second comparison is necessary to ensure that the ID ofthe detected session actually matches to the SessionID received from the client.

Client wishes to resume

a particular session

2

Figure 3.2: The Server Session Manager

If the client has sent a Hello message without specifying any session identifier, theserver has to create a entirely new session object with a new sessionID for identifying thenew session. A whole handshake dialogue will be necessary to negotiate the securityparameters.

Now, after we have seen the general proceeding of session caching and searching, it´stime to provide some guidelines for implementing one´s own session manager. For thatreason it would be advantageously to gain some basic understanding of iSaSiLk´s severalsession class implementations. The following sections first briefly introduce the iSaSiLkclasses SessionID, Session and SessionManager as fundamental preconditions forsubsequently discussing a particular session manager implementation by means of theDefaultSessionManager class.

Page 57: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

57

3.4.1.1.4.1 public class SessionID

The session identifier is used to identify a particular SSL session. ISaSiLk implements asession identifier as an arbitrary byte sequence, generally generated by the server foridentifying some active session or some session to be resumed. However, a SessionIDobject also may represent an empty byte array as needed by the client when indicating theserver to negotiate new security parameters. Since the client´s Hello message has toinclude a session identifier, an empty SessionID object is transmitted if no particularsession ID is available or the client intends to negotiate new security parameters.

An object of the iSaSiLk SessionID class may be created by means of the emptystandard constructor or by providing some random seed.

If the client, that searches the cache, doesn´t find some appropriate session to beresumed, it creates a new session with an empty session identifier by using the standardsessionID constructor:

//constructor for creating an empty session id:

SessionID()

If the server is motivated by the client to create a new session, or if the server refusesthe client´s proposal for agreeing on the security specifications of some former session, itcreates a new session with a random seeded session identifier by using the secondconstructor of the SessionID class:

//constructor for creating a random session id: SessionID(Random random)

Once a SessionID object is created, it mainly will be used to identify some particularsession within the session cache. Suppose, the server has received the client´s Hellomessage containing the session ID of a specific session the client wishes to resume. Nowthe server charges the session manager to search the cache for this particular session. Thedefault session manager uses the IP address of the peer (i.e. requesting client) as key forsearching the session hashtable. If a match is found, the session identifier of the detectedcached session has to be compared with the sessionID derived from the client.

Note, that the default session manager only caches one session it has held with anyparticular peer. If there have been more than one sessions with the same peer during thelast resume period, only the most recent session is kept in the cache. Notice the difference:the IP address of the peer is used to search the session cache. Only if a match is found, thesessionID is used to unmistakable identify the detected session as being the one the clientwishes to resume.

If an application intends to implement its own session manager, perhaps it may wish tocache all the sessions held with some specific peer during the last resume period. It alsomay use another hashing key than the IP address of the peer (for instance extended by a

Page 58: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

58

particular port number). The session manager (see 3.4.1.1.4.3) provides a template givingthe freedom to realize one´s own session caching strategy; the default session manager (see3.4.1.1.4.4) only is one basic example of a simple session caching policy.

In either case, there will be need for some utility to compare sessions for having thesame or different session identifiers. The SessionID class provides a equals(..)method for comparing a SessionID object with another SessionID object:

//method for comparing with another session identifier:

public boolean equals(Object object)

The SessionID class´ equals method is used by the default session manager´sgetSession method for uniquely identifying a particular session derived from the sessioncache (see 3.4.1.1.4.4).

For providing the possibility to use SessionID objects as keys for storing session objectswithin a hashtable object of the java.util package, additionally the SessionID class has tosupport an implementation of the hashcode method of the java.lang.Object class:

//Creates an integer suitable for hash table indexing

public int hashCode()

You may ask yourself, why not using the SessionID immediately as key for cachingrespectively searching for sessions? The answer is, that the client - when initiating aconnection to a particular server - first looks into the session cache if there has been anysession with this server during the last resume period. If a match is found, the client getsthe corresponding sessionID from the cache for reporting it the server. When starting thesearch, the client doesn´t know any sessionID, and it cannot use something as search keythat it doesn´t know of! Since it knows the peer´s IP address, this address can be serve assearch key. Since per default client and server implementations use the same defaultsession manager, sessions are also cached on the server´s side by using the peer´s IPaddress as key. Maybe an application wishes to implement different session cachingstrategies for server respectively client and directly use the sessionID as caching andsearching key on the server´s side.

The following section introduces the Session class providing the data structures andmethods for holding and obtaining all the information that is required to keep in mind forbeing able to resume a previous session.

3.4.1.1.4.2 public class Session

In order to enable the resuming of some former session without performing a completehandshake dialogue again, all the security specifications that are typically associated with asession have to be kept in mind: negotiated cipher suite and compression method, peercertificate chain and generated master secret.

Page 59: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

59

All the information is collected within a special ´container´. For every single sessionanother container has to be used to keep the parameters of this session. In order todistinguish the several containers, each container is labeled with an etiquette uniquelyidentifying the particular container. Additionally, each container is provided with a timestamp indicating the moment it has been put into the container depot.

Within the iSaSiLk SSLv3 implementation, containers are created as instances of theSession class and the etiquette of a particular container corresponds to the SessionID ofthe particular session object (see 3.4.1.1.4.1). As containers are kept within the containerdepot sessions are stored within the session cache. The time stamp indicates the creationtime of a session object and is used to remove sessions that are longer in the cache thanallowed by the actual resume period. The management of the session cache is devolved onthe implemented session manager (see 3.4.1.1.4.3) which per default is the default sessionmanager (see 3.4.1.1.4.4).

The Session class provides two constructors for creating a new session object. Thestandard empty constructor creates a session object with an empty session identifier andmay preferably be used by the client leaving the server the task to create a new randomsession id:

//constructor for creating a new session with an empty session id:

Session()

On the other side of the connection, the server has to use a random number generator forseeding the second session class constructor to create a session with a new random sessionidentifier:

//constructor for creating a session with a new random session id:Session(Random random)

For implementing your own session manager, you may take use of the Session class´several service methods for accessing the entities of a particular session object:

//Get the ID of this session

public SessionID getID()//Get the creation time of this session

public long getCreationTime()//Get the peer´s certificate

protected SSLCertificate getPeerCertificate ()//Get the master secret

protected byte[] getMasterSecret()//Get the negotiated cipher suite of this session

protected CipherSuite getCipherSuite()//Get the compression method of this session

CompressionMethod getCompressionMethod()

Page 60: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

60

Furthermore, the Session class provides a special method for obtaining a stringrepresentation of all the entities collected within a particular session object:

//Get a string representation of this session

public String toString()

A call to this method may, for instance, print out the following information held by aspecific session object:

Peer Certificate: C=AT, O=IAIK, CN=atlas, OU=DH Server Certificate

Resumeable: noCreation time: 884863502869Cipher suite: SSL_DH_RSA_WITH_DES_CBC_SHACompression method: NULLSessionID: fffffeee

Several sessions may be created during multiple client-server connections. It is theresponsibility of the implemented session manager to decide how to cache and manage thecorresponding session objects holding the security parameters that are required to resumesome session. The following section describes the session manager interface providing atemplate for the user to implement her/his own session caching policy.

Subsequently, the default session manager introduction gives an example for a simplesession manager implementation.

3.4.1.1.4.3 public interface SessionManager

To continue the example comparing a session object with a container for holding all thesecurity parameters that are required for resuming a session, we have to decide how tomanage all the containers respectively session objects that may appear during aclient/server communication. The particular caching strategy is left to the user; theSessionManager interface only predicts two abstract methods, one for caching sessionsand one for obtaining sessions from the cache. Each class that implements the sessionmanager interface at least has to support implementations for these two methods:

/** * Add this session to the session cache. * * @param socket the ssl socket which wants to cache this session * @param session the session to cache */

public void cacheSession(SSLSocket socket, Session session);

Page 61: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

61

/** * Get a session from the session cache. * * @param socket the SSL socket which wants to look for a session * @param sessionID a SessionID or <code>null</code> * * @return null if the session is not in the cache or the SessionManager wont resume this * session; the cached session otherwise */

public Session getSession(SSLSocket socket, SessionID sessionID);}

Notice that both methods are ´parameterized´ with the SSLSocket object that wants tolook for a session. From the supplied socket object the implemented session manager mayget the information serving as key for putting a session object to the cache or searching fora specific session in the cache. The default manager, who manages the session caching forthe server as well as for the client, depicts the peer´s IP address from the socket object andstores sessions in a hashtable by using this IP address as key index.

You may rely on the default session manager or you may implement your own sessioncaching strategy, perhaps using some other keying system. You also may implement twoseparate session managers, one for the client and one for the server, that use differentpolicies. The following section discusses the default session manager that may be used asan example for implementing a session manager.

Before doing so, we should introduce the two methods of a SSLClientContext(respectively SSLServerContext) class that are necessary to bind (set) a specific sessionmanager implementation to a context object, and to obtain (get) the actual session managerfrom a context object:

//get the actual session manager of this context object

public abstract SessionManager getSessionManager();

//set the session manager for this context object

public abstract void setSessionManager(SessionManager sessionManager);

3.4.1.1.4.4 public class DefaultSessionManagerimplements SessionManager

Per default, the iSaSiLk SSLv3 implementation uses one single default session managerto manage both, the client´s session caching as well as the server´s session caching. Thissection describes the default session manager by a step-by-step walk through thecorresponding program code.

Before going into details, we will think of the tasks the default session manager shall beable to handle:

Page 62: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

62

• Putting some session to the session cache

• Getting some session from the session cache

• Removing some session from the session cache if already too long in the cache

If we assume to provide one method for each specific task, our default session managerat least will contain three methods. For their specific implementations we first have toagree about the storage medium we will use to cache the session objects. The defaultsession manager uses the Hashtable class of the java.util package as session cache.

A hashtable can be imagined as an storage medium that uses some kind of key forlocating a particular object within the storage. The key serves as index to the hashtable.Any object that is not the null object may be used as key for a hashtable, presuming thatthe corresponding key class supports implementations of the hashcode and equalsmethods of the java.lang.Object class for generating and comparing hashtable indices.

Each Hashtable object is characterized by a specific capacity and a specific load factorthat can be set when creating a new instance of the Hashtable class. The load factor valueshould be chosen to lie between 0.0 and 1.0. However, one may rely on the default settingsby using the standard constructor which sets the capacity to 101 and the load factor to 0.75.At every stadium of the lifetime of an hashtable object the actual capacity of the hashtableis controlled to not exceed the product of load factor and current capacity, causing anautomatically resizing of the hashtable´s total capacity. Since this controlling andincreasing process will claim for some time, it may be preferable to specify some largerload capacity and load factor already at the beginning when creating the hashtable object toreduce the number of times the hashtable has to be resized. Since for our demonstrationpurposes we don´t expect too much net traffic, we will implement the session cache ashashtable with default load capacity and load factor:

Hashtable activeSessions; //repository for the cached sessionsactiveSessions = new Hashtable();

Since sessions should be kept in the cache only for a certain time period, we have todetermine a particular resume period value. Every time an access is made to the cache, thecache has to be checked for sessions to be removed because already exceeding the definedresume period. We voluntary decide to set the resume period to 2 hours meaning that asession has to be removed from the cache when its creation time dates back more than twohours:

long resumePeriod; //after this time a session is removed from the cache

resumePeriod = 1000*60*60*2; //resume period in milliseconds

For statistical purposes we also introduce a counter indicating the number of sessionsthat have been removed from the cache since the cache hashtable has been created:

Page 63: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

63

int removed; //number of removed cache entries

removed = 0;

Now we are ready to implement the constructor of our default session manager. Sincethe iSaSiLk SSLContext object only supports a SessionManager object, but the defaultsession manager is an specific implementation of the session manager interface, we willuse a private constructor that only may be called inside the DefaultSessionManagerclass. For enabling access to the new created default session manager object from outsidethe class, we provide a special factory method that returns the new created default sessionmanager object as session manager implementation:

static SessionManager session_manager; //the session manager

static { session_manager = new DefaultSessionManager(); } //Return one session manager for all SSLSockets. public synchronized static SessionManager getManager() { return session_manager; } Hashtable activeSessions; // repository for the cached sessions long resumePeriod; // after this time a session is removed

// from the cache int removed; // number of removed cache entries

//Create only one session manager for all SSLSockets. private DefaultSessionManager() { activeSessions = new Hashtable(); resumePeriod = 1000*60*60*2; // 2 hours removed = 0; off = false; }

Note that we have defined the session manager to be a static instance since we only willneed one single session manager throughout the client´s (respectively server´s) lifetime.The first time the getManager() method is called from outside theDefaultSessionManager class by writing

SessionManager session_manager;session_manager = DefaultSessionManager.getManager();

an instance of the DefaultSessionManager class is created. Every further call of thegetManager() method will access this one particular instance and not create a newsession manager object. The getManager() method additionally is defined to besynchronized forbidding more than one access at a time.

The next task is to implement a method for putting a session into the session cache.Since the session cache is implemented as a hashtable, we make use of the Hashtable

Page 64: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

64

class´ put method for adding the new session. As index key for the hashtable serves theInet address of the peer which is extracted from the socket object that wants to cache thesession:

/** * Put a session into the session cache. * * @param socket the SSL socket which wants to cache this session * @param session the session to cache */ public void cacheSession(SSLSocket socket, Session session) { deleteOldSessions(); activeSessions.put(socket.getInetAddress(), session); }

Since we decided to remove all sessions that exceed the resume period every time whenaccessing the cache, we also have to check the cache for sessions to be deleted when wewant to add a new session. Old sessions are removed by means of thedeleteOldSessions() method:

//Delete sessions which are longer in cache than resume periodprivate void deleteOldSessions() {

long time = System.currentTimeMillis(); for (Enumeration e = activeSessions.keys(); e.hasMoreElements();) { Object key = e.nextElement(); Session s = (Session)activeSessions.get(key); if (time - s.getCreationTime() > resumePeriod) { activeSessions.remove(key); removed++; } }

}

First the current time (in milliseconds) is evaluated. Then the session cache hashtable issearched key by key. For every key the corresponding session object is obtained from thehashtable. Note that an explicit cast is necessary to derive a session object from theHashtable get(key) method which per default returns an generalized Object instance.For each session the getCreationTime() method returns the time (in milliseconds) theparticular session object has been created. If the session´s creation time dates back morethan the resumePeriod value, the corresponding session is removed from the cache.

After providing methods for putting sessions into the cache and deleting old sessionsfrom the cache, the remaining task is to implement a method for getting sessions from thecache. Since both, client and server shall be able to use the default session manager, wemust consider client accesses as well as server accesses.

The template for the getSession(..) method is already predicted by theSessionManager interface:

Page 65: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

65

public Session getSession(SSLSocket socket, SessionID sessionID);

The default manager uses the Inet address of the peer as key for searching the sessioncache hashtable. This address is extracted from the socket that wants to search the cacheand that is supplied the getSession() method as first parameter object :

Session s = (Session)activeSessions.get(socket.getInetAddress());

After a particular session is derived from the cache, the further proceeding has toincorporate client as well as server requests. A client may call the getSession(..)method to ask if there is any session in the cache that has been held with the particularserver identified by the server´s Inet address. Therefore the client may not specify anysession identifier when calling the getSession(..) method:

Session session;

session = context.getSessionManager().getSession(socket, null);

On the other side, the server when receiving a particular session identifier from theclient indicating some session to be resumed, searches the cache for any session thatexactly matches to the specified session id. The server therefore has to supply the sessionidentifier when calling the getSession(..) method.

Session session;

session = context.getSessionManager().getSession(socket, session_id);

When an appropriate session - matching the server´s Inet address - has been found in thecache after a client´s inquiry, the getSession(..) method immediately can return thesession. Note that a client´s call to the getSession method is marked by a null SessionID:

Session s = (Session)activeSessions.get(socket.getInetAddress());if (sessionID == null) return s;

When an appropriate session - matching the client´s Inet address - has been found in thecache after a server´s inquiry, this session first has to be compared with the SessionID theclient has sent. If the two session identifiers are identical, the session derived from thecache may be resumed and can be returned by the getSession method. Before comparingthe two session identifiers, we first have to ensure, that there has been detected any sessionin the cache that matches to the client´s Inet address. Otherwise an error may occur:

Page 66: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

66

Session s = (Session)activeSessions.get(socket.getInetAddress());

if (s != null) { if (sessionID.equals(s.getID())) return s;}

And finally, the getSession method may get a session from the cache that matches tothe client´s Inet address, but not to the session identifier the client has sent. Since thissession is not of interest, the getSession method removes it from the cache and returnsthe null object indicating the server to create a complete new session object:

activeSessions.remove(socket.getInetAddress());return null;

Remember, that before searching the cache, all sessions have to be removed which arelonger in the cache than allowed by the resume period. This may lead to the followinggetSession implementation within the default session manager class:

/** * Returns a session form the cache. * @param socket the SSL socket which wants to look for a session * @param sessionID the ID of the session which should be resumed

* or null if this method is called by a SSL client. *

* @return the session from the cache or null */ public Session getSession(SSLSocket socket, SessionID sessionID) { deleteOldSessions(); //search the cache for a session that matches the peer´s //InetAddress Session s = (Session)activeSessions.get(socket.getInetAddress());

//if client request or no proper session in cache if (sessionID == null || s == null) return s; //if server request check, for ID match if (sessionID.equals(s.getID())) return s; //if InetAddress match, but no ID match activeSessions.remove(socket.getInetAddress()); return null; }

After successfully implemented our three basic methods for putting sessions to thecache, and deleting or getting sessions from the cache, additionally we will provide apossibility for querying and changing the resume period from outside the default sessionmanager class:

Page 67: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

67

/**

* Set the resume period of cached sessions.

*

* @param period the resume period in seconds

*/

public void setResumePeriod(long period) {

resumePeriod = period*1000;

}

/**

* Return the resume period of this session manager.

*

* @return the resume period in seconds

*/

public long getResumePeriod() {

return resumePeriod/1000;

}

Now we are ready to put all together for realizing our default session managerimplementation. Perhaps it would be advantageously to include some kind of switchmaking it possible to enable respectively disable the session manager for some reason.Suppose you wish to test the correct working of all the implemented cipher suites. Forcontinuously testing one cipher suite after the another throughout one single programexecution (take a look at the demo CipherSuiteTest source code), it may be useful toswitch of the session manager for disabling any kind of session caching.

import java.util.*;import java.net.InetAddress;

public class DefaultSessionManager implements SessionManager { static SessionManager session_manager; // the session manager static { session_manager = new DefaultSessionManager(); } /** * Return one session manager for all SSLSockets. * * @return the session manager */ public synchronized static SessionManager getManager() { return session_manager; }

Hashtable activeSessions; // repository for the cached sessions long resumePeriod; // after this time a session is removed

// from the cache

Page 68: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

68

int removed; // number of removed cache entries boolean off; // useful when testing different cipher suites

// Create only one session manager for all SSLSockets. private DefaultSessionManager() { activeSessions = new Hashtable(); resumePeriod = 1000*60*60*2; // 2 hours removed = 0; off = false; }

/** * Disables or enables the DefaultSessionManager. *

* @param on true to enable the DefaultSessionManager * false to disable the DefaultSessionManager */ public void enable(boolean on) { off = !on; }

// Set the resume period of cached sessions. public void setResumePeriod(long period) { resumePeriod = period*1000; }

// Get the resume period of this session manager. public long getResumePeriod() { return resumePeriod/1000; } // Put a session into the session cache. public void cacheSession(SSLSocket socket, Session session) {

if (off) return;

deleteOldSessions(); activeSessions.put(socket.getInetAddress(), session); }

// Get a session form the cache. public Session getSession(SSLSocket socket, SessionID sessionID) {

if (off) return null;

deleteOldSessions(); //search the cache for a session that matches the peer´s //InetAddress Session s = (Session)activeSessions.get(socket.getInetAddress()); // if client request or no proper session in cache if (sessionID == null || s == null) return s;

Page 69: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

69

// if server request, check for ID match if (sessionID.equals(s.getID())) return s; // if InetAddress match, but no ID match activeSessions.remove(socket.getInetAddress()); return null; } // Deletes sessions which are longer in cache than resume period. private void deleteOldSessions() {

long time = System.currentTimeMillis();

for (Enumeration e = activeSessions.keys(); e.hasMoreElements();) { Object key = e.nextElement(); Session s = (Session)activeSessions.get(key);

if (time - s.getCreationTime() > resumePeriod) { activeSessions.remove(key); removed++; } } } /** * Get some statistics about the sessions cache. * * @return a string representation of some statistics */ public String toString() { StringBuffer buf = new StringBuffer(); if (off) buf.append("DefaultSessionManager disabled.\n"); else { buf.append("DefaultSessionManager ensabled:\n"); buf.append("Sessions in cache: "+activeSessions.size()+"\n"); buf.append("Removed sessions: "+removed+"\n"); } return buf.toString(); }}

You also may get a demo version of this default session manager - calledDemoSessionManager - in your iSaSiLk demo directory.

If you have implemented your own session manager - let´s call it MySessionManager -you have to incorporate it into the actual context object by using thesetSessionManager(..) method of the SSLContext class:

SessionManager manager = MySessionManager.getManager();

context.setSessionManager(manager);

Page 70: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

70

To obtain the actually installed session manager from the context object, use thegetSessionManager() method. Suppose, the default session manager is the activesession manager of the current context object and you intend to change the resume periodto one hour. Remember that the setResumPeriod(..) method expects to specify thetime value in seconds:

DefaultSessionManager session_manager; session_manager = (DefaultSessionManager)context.getSessionManager(); session_manager.setResumePeriod(60*60);

Note that an explicit cast to DefaultSessionManager is necessary sincegetSessionManager() returns a SessionManager object that doesn´t support thesetResumePeroiod method.

After this expensive discussion of the session caching management, we can proceed tothe next - an already last - part of the SSLCLientContext introduction - the trust deciderclass.

3.4.1.1.5 The Trust Decider

The TrustDecider interface provides the user a template of abstract methods forimplementing her/his own policy for trusting or rejecting a certificate that has been sentfrom the peer.

On the client´s side, additionally the trust decider has to supply the client handshakerwith certificates and keys the client handshaker will need to satisfy a certificate requestpossibly coming from the server.

If no trust decider is implemented, every certificate derived from the peer will betrusted. On the client´s side the absence of a trust decider implementation additionally willlead to a ´No certificate´ warning indicating the server that the client is not able to sufferthe server´s certificate request.

Simplified, the general proceeding during a handshake dialogue can be described asfollows:

The server handshaker, when receiving the certificate of the client, first checks if thereis any trust decider implemented and incorporated into the server context. It therefore triesto extract the proper trust decider from the server context by calling the context´sgetTrustDecider() method:

TrustDecider trust_decider = serverContext.getTrustDecider();

If no trust decider is returned by the getTrustDecider() method, either no trustdecider is implemented at all, or no trust decider has been incorporated into the server

Page 71: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

71

context. In both cases, the getTrustDecider()method returns null and the clientcertificate is trusted per default.

Otherwise, if the getTrustDecider() method actually returns a trust decider object,the server handshaker consults this trust decider to inquire whether the received clientcertificate should be trusted or not. If the trust decider accepts the client certificate, thehandshake dialogue continues to the next stage. If the trust decider refuses the clientcertificate, a fatal bad certificate alert is triggered and the connection is closed with an´untrusted certificate´ SSL exception.

Somewhat different is the situation for the client handshaker. Of course, the clienthandshaker performs the same steps as described above for asking the client trust deciderwhether trusting a server certificate or not. However, it may be necessary for the clienthandshaker to consult the trust decider a second time if the server claims for a clientauthentication. In this case, the client handshaker first ensures that the trust deciderresponsible for dealing with certificate requests of the server, is implemented as instance ofthe ClientTrustDecider class (see 3.4.1.1.5.3). If not, the connection is closed by an´TrustDecider for client SSLSocket must be a ClientTrustDecider´ SSLException message.

If the trust decider actually is a client trust decider, the client handshaker asks the trustdecider to look for a proper certificate for suffering the server´s certificate request. If theclient trust decider cannot supply the required certificate, a ´No client certificate´ warningis sent to the server that thereupon has to decide whether closing the connection oraccepting the anonymity of the client.

Since the task of deciding whether the peer certificate has to be trusted or not, may befulfilled by a particular server as well as client trust decider implementation, whereas theproviding of certificates only has to be done by a client trust decider, we first will discuss asimple server trust decider implementation, followed by the introduction of the client trustdecider.

Basically, iSaSiLk provides three interface classes leaving the user some scope forimplementing her/his own certificate trusting policy:

//interface of abstract methods to let the user implement her/his own certificate trusting policy

public interface TrustDecider//interface for implementing a server trust decider

public interface ServerTrustDecider extends TrustDecider//interface for implementing a client trust decider

public interface ClientTrustDecider extends TrustDecider

Unlike the session manager arrangement, where one single session managerimplementation may be used for managing the session caching for both, client and server,iSaSiLk demands on distinguishing between client trust decider and server trust deciderimplementation. Both interfaces, ClientTrustDecider and ServerTrustDeciderextend the basic interface TrustDecider, but ClientTrustDecider is not a subclassof ServerTrustDecider, although in principle one may think that theClientTrustDecider class extends the ServerTrustDecider class about the features necessaryto get certificates enabling for client authentication.

Page 72: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

72

3.4.1.1.5.1 public interface TrustDecider

The TrustDecider interface is the basic interface class of iSaSiLk´s trust deciderarchitecture. It is already extended within the iSaSiLk standard environment by theServerTrustDecider respectively ClientTrustDecider interfaces which on theirturn may be implemented by the user to realize her/his own certificate trusting policy.

The TrustDecider interface only provides one single abstract method for deciding ifthe certificate sent from the peer is to be trusted or not. If the corresponding server(respectively) client handshaker successfully has ensured that a proper trust decider hasbeen implemented and incorporated into the actual context object, it calls this method tocheck if the peer certificate is trustworthy:

/** * Decides if the peer certificate is trustworthy or not. * * @param certificate the SSLCertificate message containing the peer´s certificate (list) * @return true if the peer is trusted or false otherwise */

public abstract boolean isTrustedPeer(SSLCertificate certificate);

If this method returns false, the handshaker terminates the connection with a fatal badcertificate error. Otherwise - if isTrustedPeer returns true, the handshake dialogueproceeds to the next stage.

Note that SSLCertificate represents a handshake message for transfering acertificate chain. Since isTrustedPeer has to check the trustworthiness of the peer´sX.509 certificate chain received with this SSLCertificate message, the certificate chain hasto be "extracted" from the handshake message using the getCertificateChain()method of the SSLCertificate class:

public X509Certificate[] getCertificateChain();

It should be emphasized that an application don´t has to confirm with the conventionalway of checking the trustworthiness of the peer certificate already during the handshakephase by calling the proper trust decider. Also the certificate may be checked at any latertime during the client-server conversation. For obtaining the peer´s certificate chain, theSSLSocket class provides the method getPeerCertificateChain():

/** * Returns the certificate chain sent by the peer or null if the * peer has no certificate. * * X509Certificate[0] contains the peer certificate. * X509Certificate[len-1] contains the top CA certificate. *

Page 73: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

73

* @return the certificate chain sent by the peer */

public X509Certificate[] getPeerCertificateChain();

3.4.1.1.5.2 public interface ServerTrustDeciderextends TrustDecider

Since the only task of the server trust decider is to decide about the trustworthiness ofthe certificate derived from the client, the ServerTrustDecider interface is equippedwith nothing but an empty body that may be ´filled´ by a specific server trust deciderimplementation of the user:

public interface ServerTrustDecider extends TrustDecider {}

An implementation of the ServerTrustDecider at least has to contain an implementationof the basic isTrustedPeer(SSLCertificate certificate) method for decidingabout the trustworthiness of the certificate sent by the client.

For the purpose of illustration, we may implement a SampleServerTrustDeciderclass for checking the consistency of the X.509 certificate chain derived from the client.Therefore the isTrustedPeer(..) method first shall print out the certificate chain andthen call a separate verifyCertificateChain(..) method for checking if thecertificate is to be trusted (return true) or not (return false). Remember, that before callingthe verifyCertificateChain(..) method, we have to extract the X.509 certificatechain from the SSLCertificate message received from the client.

If the client has not sent a certificate, the server handshaker calls the server trustdecider´s isTrustedPeer(..) method without supplying a certificate chain. The servertrust decider determines whether to accept the absence of a client certificate or not. In ourexample we will continue the handshake dialogue if the client doesn´t fullfill a certificaterequest:

/** * Shows the certificate chain sent by the client and * checks its consistency. * * @param certificate the certificate message with the client * certificate list * @return true, if the client certificate is trusted; false * otherwise */ public boolean isTrustedPeer(SSLCertificate[] certificate) {

Page 74: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

74

if (certificate == null) return true; // no certificate is o.k. // get the X.509 certifcate chain from the SSLCertifcate message X509Certificate[] CertChain = certificate.getCertificateChain(); debug("\nClient certificate chain:"); for (int i=0; i<certChain.length; i++) debug(certChain[i].getSubjectDN().toString());

return verifyCertificateChain(certChain); }

The verifyCertificateChain(..) method checks the supplied X.509 certificatechain certChain (i.e. the certificate chain derived from the client), starting with the self-signed top level CA certificate certChain[certChain.length-1] and leading to theactual client user certificate certChain[0]. For actually verifying each single certificateof the certificate chain to be checked, the verifyCertificateChain(..) methodmakes calls to the verify(..) methods of the X509Certificate class of the iaik.X509package. Thereby, the top level certificate is checked by using its inherent public key, andall the other certificates are verified by means of the public key belonging to the certificatelocated just one position higher in the certificate hierarchy. If an error is detected duringthe checking procedure, the client´s certificate will be refused by an fatal bad certificatealert:

/** * Verifies a certificate chain. * @chain the certificate chain to verify * @return true if the certificate chain is o.k., false otherwise */ public boolean verifyCertificateChain(X509Certificate[] chain) { int len = chain.length; try { chain[len-1].verify(chain[len-1].getPublicKey()); //TOP LEVEL

for (int i = len-1; i>0; i--) chain[i-1].verify(chain[i].getPublicKey()); } catch (Exception ex) { return false; } return true; }

The whole SampleServerTrustDecider class implementation also includes a debugmethod for printing information onto the screen if the constructor is supplied with theboolean true value:

import java.security.cert.X509Certificate;import iaik.security.ssl.*;

public class SampleServerTrustDecider implements ServerTrustDecider {

boolean debug;

Page 75: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

75

/** * Create a SampleServerTrustDecider. * * @param printDebugInfo if true debug information is printed to * System.out */ public SampleServerTrustDecider(boolean printDebugInfo) { debug = printDebugInfo; }

/** * Verifies a certificate chain. * * The certificate of the peer is the first one in the list * (chain[0]), and the top level certificate is the last one. * * @chain the certificate chain to verify * @return true if the certificate chain is o.k., false otherwise */ public boolean verifyCertificateChain(X509Certificate[] chain) { int len = chain.length; try { chain[len-1].verify(chain[len-1].getPublicKey(); //TOP LEVEL

for (int i = len-1; i>0; i--) chain[i-1].verify(chain[i].getPublicKey()); } catch (Exception ex) { return false; } return true; }

/** * This method is called during the SSL handshake procedure to let * an application decide if the certificate sent by the client is * trustworthy. If this method returns false the SSL connection is * terminated with a fatal bad certificate error. * * This demo implementation just shows the certificate chain sent by * the client and checks its consistency. * * @param certificate the SSLCertificate message containing the * certificate chain sent from the client

* @return true, if the client certificate is trusted, * false otherwise */ public boolean isTrustedPeer(SSLCertificate certificate) { if (certificate == null) { debug("No client certificate!"); return true; // no certificate is o.k. }

X509Certificate[] certChain = certificate.getCertificateChain(); debug("\nClient certificate chain:");

Page 76: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

76

for (int i=0; i<certChain.length; i++) debug(certChain[i].getSubjectDN().toString()); return verifyCertificateChain(certChain); }

/** * If enabled print some debug information. * * @param s the string to print */ private void debug(String s) { if (debug) System.out.println(s); }}

To enable the SampleServerTrustDecider implementation, it has to beincorporated into the actual server context object. Note, that when creating aSampleServerTrustDecider object, we have to specify if debug information has to bereported:

SSLServerContext serverContext = new SSLServerContext();SampleServerTrustDecider trustDecider =

new SampleServerTrustDecider(true);ServerContext.setTrustDecider(trustDecider);

The active server trust decider may be obtained from the server context by means of thegetTrustDecider() method. If the active server trust decider is an instance of theServerTrustDecider class, an explicit cast will be necessary since per the default aTrustDecider object is returned:

//without cast a TrustDecider object is returnedTrustDecider trustdecider = serverContext.getTrustDecider();

//cast to SampleServerTrustDeciderSampleServerTrustDecider serverTd =

(SampleServerTrustDecider)serverContext.getTrustDecider();

Page 77: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

77

received client certificate

Server Trust Decider

The server trust decider checks the trustworthiness of the certificate received from the client.

Server Handshaker

Figure 3.3: The Server Trust Decider

Any application may realize its own server trust decider policy, which - of course - maybe more comprehensive than the example above. For a demonstration look at theDemoServerTrustDecider class of iSaSiLk´s Demo package.

3.4.1.1.5.3 public interface ClientTrustDeciderextends TrustDecider

Additionally to the task of checking the trustworthiness of the certificate sent by theserver, the client trust decider has to take care for providing appropriate certificates andkeys for suffering a client authentication request coming from the server.

If the server is a non anonymous server, it may claim for a client authentication bysending a certificate request message. If an anonymous server tries to request a certificatefrom the client, the connection is closed immediately by triggering a fatal handshakefailure.

In sending a certificate request message to the client, the server specifies thecertification authorities and certificate types it is willing to accept.

The client, when receiving the servers certificate request message, asks its client trustdecider whether it is able to fulfill the server´s specific certificate requirements. If no clienttrust decider is installed or no client trust decider is bound to the actual client context, theclient has to answer the server´s certificate request with a ´No certificate´ warning. Thesame warning has to be sent back to the server if the actual context object supports a clienttrust decider, but the client trust decider is not able to supply an appropriate certificate.

If the server receives a ´No certificate´ message from the client answering its certificaterequest message, it is left to the server to decide if the connection should be closed with afatal handshake failure or if the handshake dialogue should be continued.

Page 78: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

78

received server certificate

Client Trust Decider

The client trust decider checks the trustworthiness of the certificate received from the server.Additionally, the client trust decider has to take care for certificates and keys if the server requets a client authentication.

Client Handshaker

Figure 3.4: The Client Trust Decider

There are several types of certificates the server may request from the client whensending its certificate request message:

• rsa_sign: denotes a RSA certificate including the client´s public RSA key; can beused for signing

• dss_sign: denotes a DSS certificate including the client´s public DSA key; can beused for signing

• rsa_fixed_dh: denotes a RSA certificate including fixed Diffie Hellman parametersthat have to match to the DH parameters the client has received within the servercertificate; cannot be used for signing

• dss_fixed_dh: denotes a DSS certificate including fixed Diffie Hellman parametersthat have to match to the DH parameters the client has received within the servercertificate; cannot be used for signing

• rsa_ephemeral_dh: denotes a RSA certificate including the RSA public key; theephemeral Diffie Hellman parameters are sent with the Client Key Exchangemessage and have to match to the DH parameters the client has received within theserver key exchange message; can be used for signing

• dss_ephemeral_dh: denotes a DSS certificate including the DSA public key; theephemeral Diffie Hellman parameters are sent with the Client Key Exchangemessage and have to match to the DH parameters the client has received within theserver key exchange message; can be used for signing

• fortezza_dms: denotes a fortezza certificate; can be used for signing

Page 79: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

79

It is the responsibility of the implemented client trust decide whether a particularcertificate shall be supported or not. The client handshaker that receives the certificaterequest message from the server, expects from the client trust decider an easy mechanismfor obtaining appropriate certificates and keys to satisfy the server´s certificate request.

The iSaSiLk´s inherent ClientTrustDecider interface first defines some fixed keyvalues making it possible to uniquely identify a particular certificate type that may berequested from the server:

public static final byte rsa_sign = 1;public static final byte dss_sign = 2;public static final byte rsa_fixed_dh = 3;public static final byte dss_fixed_dh = 4;public static final byte rsa_ephemeral_dh = 5;public static final byte dss_ephemeral_dh = 6;public static final byte fortezza_dms = 20;

A SSL server may use these agreements to define the certificate types it wants to specifywithin its certificate request message. If the server, for instance, wishes to get a certificateof either rsa_sign, dss_sign, rsa_ephemeral_dh or dss_ephemeral_dh type, itsets the appropriate values and packs them into a byte array:

byte[] types = new byte[4];types[0] = ClientTrustDecider.rsa_sign;types[1] = ClientTrustDecider.dss_sign;types[2] = ClientTrustDecider.rsa_ephemeral_dh;types[3] = ClientTrustDecider.dss_ephemeral_dh;

Beside the definition of the certificate types, the ClientTrustDecider interfaceincludes two abstract methods that have to be implemented for enabling the clienthandshaker to easily access a particular certificate and private key for satisfying theserver´s certificate request:

/** * Returns a SSLCertificate handshake message containing the client certificate. * By implementing this interface someone can use his own procedure * to access the client certificates. * * @param certificateTypes the certificate types the server expects * @param certificateAuthorities the certification authorities the server accepts * @param keyExchangeAlgorithm the currently active key exchange * algorithm (from cipher suite) * @return a SSLCertificate handshake message containing the client certificate list (list[0] = client certificate) or null if no appropriate certificate is found. */

public abstract SSLCertificate[ ] getCertificate(byte[ ] certificateTypes, Principal[ ] certificateAuthorities,

String keyExchangeAlgorithm);

Page 80: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

80

/** * Returns the private key belonging to the certificate returned by * getCertificate(). * * @return the private key */

public abstract PrivateKey getPrivateKey();}

Note that the getCertificate(...) method has to return a SSLCertificatehandshake message object containing the client certificate chain to be sent to the server!

Now, if we intend to design a particular demo client trust decider implementation, wefirst have to reflect about the several tasks our client trust decider shall be able toaccomplish:

• taking care for obtaining the desired certificates and corresponding keys from somesource

• providing some methods making it possible for the client handshaker to have accessto the supplied certificates respectively private keys

• implementing the isTrustedPeer(..) method of the basic TrustDeciderinterface for deciding if the certificate derived from the server is trustworthy

If you think back to chapter 3.3.2 you may remember the discussion about the way aSSL server may follow to get certificates respectively keys for being able to support all thecipher suites implemented by iSaSiLk: first all certificates and keys - except for temporaryDiffie Hellman parameters which have to be generated separately - have been created from.der files containing DER encoded certifcate chains and key material. Following this, thederived certificate chains and keys have been incorporated into the actual server contextobject.

Of course, each particular application may use its own strategy to obtain certificates andkeys from some available source. However, for the purpose of demonstration we again willread in certificates and key material from the .der files of our certs subfolder holding IAIKKeyAndCertificates structures.

It is important to be aware about the difference between the server and client side whenproviding certificates and key material for authentication and key exchanging:

The server - after obtaining the certificates and keys from some source - makes themavailable for the corresponding server handshaker by immediately supplying them tothe actual server context object. Later, during the handshake dialogue, when theserver handshaker requires certificate/keys for authentication and key exchanging, itwill get them from the server context.

The client passes the certificate and key obtaining task to the client trust decider, andthe client handshaker - responsible for managing the handshake dialogue - getscertificates and keys from the client trust decider.

Page 81: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

81

Since the client trust decider at first has to take care for certificates and key material,this duty already may be included into the SampleClientTrustDecider constructorimplementation:

private X509Certificate[] rsa_cert;private PrivateKey rsa_private_key;private X509Certificate[] dsa_cert;private PrivateKey dsa_private_key;private X509Certificate[] dh_cert;private PrivateKey dh_private_key;private PrivateKey private_key;

//Constructor for creating a SampleClientTrustDecider objectpublic SampleClientTrustDecider() { try { KeyAndCertificate kac; EncryptedPrivateKeyInfo epki;

// set the RSA certificate/private key for RSA cipher suites kac = new KeyAndCertificate("certs/clientRSA1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("This is the passphrase!"); rsa_cert = kac.getCertificateChain(); rsa_private_key = epki.getPrivateKey();

// set the DSA certificate/private key for DSA cipher suites kac = new KeyAndCertificate("certs/clientDSA1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("This is the passphrase!"); dsa_cert = kac.getCertificateChain(); dsa_private_key = epki.getPrivateKey();

// set the DH certificate/private key for DH cipher suites kac = new KeyAndCertificate("certs/clientDH1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("This is the passphrase!"); dh_cert = kac.getCertificateChain(); dh_private_key = epki.getPrivateKey();

} catch (NoSuchAlgorithmException ex) { System.out.println("NoSuchAlgorithmException:"+ex.getMessage()); } catch (GeneralSecurityException ex) { System.out.println("GeneralSecurityException:"+ex.getMessage()); } catch (IOException ex) { System.out.println("IOException: "+ex.getMessage()); } }

Each specific kac object is created as instance of theiaik.utils.KeyAndCertificate class for generating the desired private key andbelonging certificate chain from DER encoded files. Since the inherent private key hasbeen protected by password based encryption, it has to be decrypted by instantiating the

Page 82: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

82

iaik.pkcs.pkcs8.EncryptedPrivateKeyInfo class when creating a "key holding"epki object (see 3.3.2).

Remember, that SSLv3 demands certificates according to the X.509 syntax, as returnedby the getCertificateChain() method of the iaik.utils.KeyAndCertificateclass.

Now, when a SampleClientTrustDecider object is created, it first looks forappropriate files in the certs directory and creates the required certificates and keys:

SampleClientTrustDecider clientTd =

new SampleClientTrustDecider();

Remember that this is a demo client trust decider implementation that reads incertificates from files. You may follow your own strategy for obtaining certificates andkeys. However, be sure to provide certificates according to the X.509 syntax!

After creating certificates and keys - regardless the way it is done - we have toimplement proper methods for supplying certificates to the client handhaker asking forthem.

When the client handshaker has received the certificate request message from theserver, it makes a call to the getCertificate(..) method of the client trust deciderthereby specifying the certification authorities and certificate types the server is willing toaccept. The client trust decider now searches the certificates created by its constructor toquery if it is able to fulfill the server requirements. Since the server may accept certificatesof more than only one type, the client handshaker additionally has to specify the actual keyexchange algorithm when calling the client trust decider´s getCertificate(..)method. Since client certificate and keys have to be in accordance with the negotiatedcipher suite, the client handshaker gets the key exchange algorithm from the active ciphersuite before calling the getCertificate(..) method of the client trust decider:

key_exchange_algorithm = cipher_suite.getKeyExchangeAlgorithm();SSLCertificate certificate =

((ClientTrustDecider)trust_decider).getCertificate( certificate_request.getCertificateTypes(), certificate_request.getCertificateAuthorities(),

key_exchange_algorithm);

Note that certificate_request denotes the certificate request message the clienthandshaker has derived from the server.

The following implementation of the getCertificate(..) method of theSampleClientTrustDecider class first reports all the certification authorities andcertificate types the server is willing to accept. Therefore a separate debug(..) methodis implemented doing nothing else than printing the supplied input String to the standardoutput stream:

Page 83: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

83

private void debug(String s) { System.out.println(s); }

After printing information onto the screen, the supplied key exchange algorithm is usedto determine the type of the certificate to be returned. Since a Java method only can returnone single entity, we have to use a extra method getPrivateKey() the client handshakermay call to get the private key matching to the certificate first derived by thegetCertificate(..) method:

public PrivateKey getPrivateKey() { return private_key; }

The private key returned by getPrivateKey() has been created by theSampleClientTrustDecider constructor and assigned to the global private_keyvariable within the getCertificate() method when determining the certificate typeand private key type that matches the active cipher suite´s key exchange algorithm. Thewhole getCertificate(..) method may look like (remember that we have to return aSSLCertificate handshake message containg the client certificate chain to be sent tothe server; we therefore construct a SSLCertificate object by supplying theSSLCertificate constructor with the proper certificate chain previously generated whencreating the actual SampleClientTrustDecider object):

/** * Returns a SSLCertificate handshake message containing the * client certificate. * * @param certificateTypes the certificate types the server requests * @param certificateAuthorities the certification authorities the * server accepts * @param keyExchangeAlgorithm the currently active key exchange * algorithm (from cipher suite) * @return the SSLCertificate message containing the * client certificate list */ public SSLCertificate getCertificate(byte[] certificateTypes, Principal[] certificateAuthorities,

String keyExchangeAlgorithm) { //print actual key exchange algorithm debug("Key exchange algorithm: "+keyExchangeAlgorithm); //print certification authorities accepted by the server debug("Server accepts the following CAs:"); for (int i=0; i<certificateAuthorities.length; i++) debug(certificateAuthorities[i].toString()); //print certificate types requested by the server debug("Server requests the following certificate types:"); for (int i=0; i<certificateTypes.length; i++) { switch (certificateTypes[i]) { case ClientTrustDecider.rsa_sign:

Page 84: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

84

debug("rsa_sign"); break; case ClientTrustDecider.dss_sign: debug("dss_sign"); break; case ClientTrustDecider.rsa_fixed_dh: debug("rsa_fixed_dh"); break; case ClientTrustDecider.dss_fixed_dh: debug("dss_fixed_dh"); break; case ClientTrustDecider.rsa_ephemeral_dh: debug("rsa_ephemeral_dh"); break; case ClientTrustDecider.dss_ephemeral_dh: debug("dss_ephemeral_dh"); break; case ClientTrustDecider.fortezza_dms: debug("fortezza_dms"); break; } }

//select proper certificate and private key according the active //cipher suite´s key exchange algorithm if (keyExchangeAlgorithm.startsWith("RSA") || keyExchangeAlgorithm.startsWith("DHE_RSA")) { debug("return RSA certificate..."); private_key = rsa_private_key; return new SSLCertificate(rsa_cert); } else if (keyExchangeAlgorithm.startsWith("DHE_DSS")) { debug("return DSA certificate..."); private_key = dsa_private_key; return new SSLCertificate(dsa_cert); } else if (keyExchangeAlgorithm.startsWith("DH_")) { debug("return DH certificate..."); private_key = dh_private_key; return new SSLCertificate(dh_cert); } return null; }

After having done all the work for obtaining certificates and keys and returning them,we shall not forget on the very own´s task of the client trust decider: checking if thecertificate derived from the server is trustworthy or not.

As already introduced when discussing the demo server trust decider, we again willimplement the isTrustedPeer(..) method of the basic TrustDecider interface toreport the received server certificate chain and check its consistency by using theverifyCertificateChain(certChain) method. Since, on the client side, a

Page 85: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

85

certificate chain coming from the server is always supplied when calling theisTrustedPeer() method, we don´t have to decide about a null argument:

//returns true if the certificate derived from the server is trusted //this demo version shows the received certificate chain and checks //its consistency public boolean isTrustedPeer(SSLCertificate certificate) {

// get the X.509 certificate chain from the SSLCertificate message X509Certificate[] certChain = certificate.getCertificateChain(); debug("Server certificate chain"); for (int i=0; i<certList.length; i++) debug(certChain[i].getSubjectDN().toString()); return verifyCertificateChain(certChain); }

As already seen when implementing the SampleServerTrustDecider (3.4.1.1.5.2), againwe have to be aware to extract the inherent X509Certificate chain from the suppliedSSLCertificate message for passing it to the verifyCertificateChain method.

Now we are ready to put all together for implementing the wholeDemoCleintTrustDecider class. To let the user decide if debug information should bereported or not, we include a special boolean debug variable that has to be initializedwhen calling the constructor:

import java.security.*;import java.io.*;import java.security.cert.X509Certificate;

import iaik.security.ssl.*;import iaik.asn1.*;import iaik.asn1.structures.Name;import iaik.security.rsa.*;import iaik.security.dsa.*;import iaik.security.dh.*;import iaik.pkcs.*;import iaik.utils.KeyAndCertificate;import iaik.pkcs.pkcs8.EncryptedPrivateKeyInfo;

public class SampleClientTrustDecider implements ClientTrustDecider { private X509Certificate[] rsa_cert; private PrivateKey rsa_private_key; private X509Certificate[] dsa_cert; private PrivateKey dsa_private_key; private X509Certificate[] dh_cert; private PrivateKey dh_private_key; private PrivateKey private_key; boolean debug;

Page 86: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

86

/** * Creates a SampleClientTrustDecider * * @param printDebugInfo if true debug information is printed to * System.out */ public SampleClientTrustDecider(boolean printDebugInfo) { debug = printDebugInfo; try { KeyAndCertificate kac; EncryptedPrivateKeyInfo epki;

// set the RSA certificate/private key for RSA cipher suites kac = new KeyAndCertificate("certs/clientRSA1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("This is the passphrase!"); rsa_cert = kac.getCertificateChain(); rsa_private_key = epki.getPrivateKey();

// set the DSA certificate/private key for DSA cipher suites kac = new KeyAndCertificate("certs/clientDSA1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("This is the passphrase!"); dsa_cert = kac.getCertificateChain(); dsa_private_key = epki.getPrivateKey();

// set the DH certificate/private key for DH cipher suites kac = new KeyAndCertificate("certs/clientDH1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("This is the passphrase!"); dh_cert = kac.getCertificateChain(); dh_private_key = epki.getPrivateKey();

} catch (NoSuchAlgorithmException ex) { System.out.println("NoSuchAlgorithmException:"+ex.getMessage()); } catch (GeneralSecurityException ex) { System.out.println("GeneralSecurityException:"+ex.getMessage()); } catch (IOException ex) { System.out.println("IOException: "+ex.getMessage()); } }

/** * Verifies a certificate chain. * * The certificate of the peer is the first one in the list * (chain[0]), and the top level certificate is the last one. * * @chain the certificate chain to verify * @return true if the certificate chain is o.k., false otherwise */ public boolean verifyCertificateChain(X509Certificate[] chain) {

int len = chain.length;

Page 87: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

87

try { chain[len-1].verify(chain[len-1].getPublicKey()); //TOP LEVEL for (int i = len-1; i>0; i--) chain[i-1].verify(chain[i].getPublicKey())) return false; } catch (Exception ex) { return false; } return true; }

/** * This method is called during the SSL handshake procedure to let * an application decide if the certificate sent by the server is

* trusted. If this method returns false the SSL connection is * terminated with a fatal bad certificate error. * * This demo implementation shows the certificate chain sent by * the server and checks its consistency. * * @param certificate the SSLCertificate maessage containing the * certificate chain sent by the server

* @return true, if the server certificate is trusted; false otherwise */ public boolean isTrustedPeer(SSLCertificate certificate) { X509Certificate[] certChain = certificate.getCertificateChain(); debug("Server certificate chain"); for (int i=0; i<certChain.length; i++) debug(certChain[i].getSubjectDN().toString());

return verifyCertificateChain(certChain);; }

/** * Returns a SSLCertificate handshake message conatining the * client certificate. * If there is no TrustDecider set in a SSLClientContext a * NoCertificate warning is sent to the server. * * This demo implementation shows the certificate types and CAs the * server requests. It returns a SSLCertificate object containing * the client certificate specified in the constructor of this * class. * * @param certificateTypes the certificate types the server requests * @param certificateAuthorities the certification authorities the * server accepts * @param keyExchangeAlgorithm the currently active key exchange * algorithm (from cipher suite) * @return the SSLCertificate object containing the client * certificate list */

Page 88: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

88

public SSLCertificate getCertificate(byte[] certificateTypes, Principal[] certificateAuthorities,

String keyExchangeAlgorithm) { //Print actual key exchange algorithm debug("Key exchange algorithm: "+keyExchangeAlgorithm);

//Print certification authorites accepted by the server debug("Server accepts the following CAs:"); for (int i=0; i<certificateAuthorities.length; i++) debug(certificateAuthorities[i].toString());

//Print certificate types requested by the server debug("Server requests the following certificate types:"); for (int i=0; i<certificateTypes.length; i++) { switch (certificateTypes[i]) { case ClientTrustDecider.rsa_sign: debug("rsa_sign"); break; case ClientTrustDecider.dss_sign: debug("dss_sign"); break; case ClientTrustDecider.rsa_fixed_dh: debug("rsa_fixed_dh"); break; case ClientTrustDecider.dss_fixed_dh: debug("dss_fixed_dh"); break; case ClientTrustDecider.rsa_ephemeral_dh: debug("rsa_ephemeral_dh"); break; case ClientTrustDecider.dss_ephemeral_dh: debug("dss_ephemeral_dh"); break; case ClientTrustDecider.fortezza_dms: debug("fortezza_dms"); break; } } //select proper certificate and private key according the active //cipher suite´s key exchange algorithm

if (keyExchangeAlgorithm.startsWith("RSA") || keyExchangeAlgorithm.startsWith("DHE_RSA")) {

debug("return RSA certificate..."); private_key = rsa_private_key; return new SSLCertificate(rsa_cert); } else if (keyExchangeAlgorithm.startsWith("DHE_DSS")) { debug("return DSA certificate..."); private_key = dsa_private_key; return new SSLCertificate(dsa_cert); } else if (keyExchangeAlgorithm.startsWith("DH_")) { debug("return DH certificate...");

Page 89: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

89

private_key = dh_private_key; return new SSLCertificate(dh_cert); }

return null; }

/** * Returns the private key belonging to the certificate returned by * getCertificate(). * * @return the private key specified in the constructor */ public PrivateKey getPrivateKey() { return private_key; }

/** * If enabled print some debug information. * * @param s the string to print */ private void debug(String s) { if (debug) System.out.println(s); }}

After creating the SampleClientTrustDecider object, it has to be enabled byincorporating it into the actual client context. Note, that when creating aSampleClientTrustDecider object, we have to specify if debug information has to bereported:

SSLClientContext context = new SSLclientContext();SampleClientTrustDecider trustDecider =

new SampleClientTrustDecider(true);context.setTrustDecider(trustDecider);

The active client trust decider may be obtained from the client context by means of thegetTrustDecider() method. If the active client trust decider is an instance of theSampleClientTrustDecider class, an explicit cast will be necessary since per thedefault a TrustDecider object is returned:

//without cast a TrustDecider object is returnedTrustDecider trustdecider = context.getTrustDecider();

//cast to SampleClientTrustDeciderSampleClientTrustDecider serverTd = (SampleClientTrustDecider)context.getTrustDecider();

Page 90: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

90

Any application may realize its own client trust decider policy, which may be morecomprehensive than the example above. For a demonstration look at theDemoClientTrustDecider class of iSaSiLk´s Demo package.

For summing up, the following two sections briefly describe what the serverrespectively client has to do for supporting trust deciding.

3.4.1.1.5.4 Trust Deciding: What the SSLServer has to do

Presuming that a server trust decider, for instance our SampleServerTrustDecider,has been implemented, the only thing to do is incorporating the trust decider into the servercontext:

SampleServerTrustDecider trustDecider = new SampleServerTrustDecider(true);

serverContext.setTrustDecider(trustDecider);

It may be necessary for the SSLServer to perform some additional tasks for configuringthe server trust decider, depending on the peculiarities of the installed server trust deciderimplementation. The, for example, DemoServerTrustDecider of iSaSilK´s Demopackage allows the SSLServer to specify ´trusted ´ signers for deciding about thetrustworthiness of the client certifcates (see DemoServerTrustDecider andSSLServer source codes of the iSaSiLk Demo package).

3.4.1.1.5.5 Trust Deciding: What the SSLClient has to do

Presuming that a client trust decider, for instance our SampleClientTrustDecider,has been implemented, the only thing to do is incorporating the trust decider into the clientcontext:

SampleClientTrustDecider trustDecider = new SampleClientTrustDecider(true);

context.setTrustDecider(trustDecider);

It may be necessary for the SSLServer to perform some additional tasks for configuringthe server trust decider, depending on the peculiarities of the installed server trust deciderimplementation.

Page 91: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

91

3.4.1.1.5.6 Client Authentication: What the SSLServer has to do

If the server claims for a client authentication, it has to send a certificate requestmessage to the client specifying the certification authorities and certificate types it iswilling to accept.

Since the server handshaker, which is responsible for managing the handshake dialoguewith the client, has to know whether it shall send a certificate request message or not, theserver must inform the server handshaker when it intends to request a client authentication.Therefore the ServerContext class is equipped with a special method the server maycall for telling the handshaker to send the certificate request message:

public void setRequireClientCertificate(byte[] certificateTypes, Name[ ] certificateAuthorities);

When calling the context´s setRequireClientCertificate method, the server hasto supply the proper certification types within a byte array and the accepted certificationauthorities within an array of Relative Distinguished Names.

For specifying the certificate types to be accepted, the server creates a proper byte arrayand fills it with the certificate type identifiers as defined within theClientTrustDecider class (see 3.4.1.1.5.3). Supposing to claim for a client certificateof either rsa_sign or dss_sign type, the server will need a two-byte array:

byte[] types = new byte[2];types[0] = ClientTrustDecider.rsa_sign;types[1] = ClientTrustDecider.dss_sign;

Since rsa_sign and dss_siqn are static variables (see 3.4.1.1.5.3), no extraClientTrustDecider object must be created for setting the certificate types.

The certification authorities to be accepted are defined as an array of Name objects ofthe IAIK-JCE iaik.asn1.structures package. The Name class of the iaik.asn1.structurespackage represents a X.500 Name structure consisting of OBJECT IDENTIFIER -value assertions pairs.

For instantiating the Name class, the server may use the default constructor, andsubsequently add some relative distinguished name by means of the Name class´addRDN(..) method:

/** * Adds a RelativeDistinguishedName to this Name. * @param oid the ObjectID of the RDN * @param value the value of the RDN */

public void addRDN(ObjectID oid, String value);

Page 92: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

92

We suppose that our SSL server wishes to specify only one particular certificationauthority:

Name[] acceptedCAs = new Name[1];Name verisign = new Name();verisign.addRDN(ObjectID.country, "US");verisign.addRDN(ObjectID.organization, "VeriSign, Inc.");verisign.addRDN(ObjectID.organizationalUnit,

"Class 1 Public Primary Certification Authority");acceptedCAs[0] = verisign;

After defining certification authorities and certificate types, the only remaining task forthe server is to indicate a request for a client certificate by informing the handshaker withthe setRequireClientCertificate(..) note:

serverContext.setRequireClientCertificate(types, acceptedCAs);

The server context can be seen as some kind of ´intermediary instance´ between serverand server handshaker: the server tells the context to inform the handshaker of the intendedcertificate request. The server handshaker gets the message from the context therebyreading the certification authorities and certificate types it has to specify when sending thecertificate request message to the client. If neither types nor acceptedCAs are set by theserver, no client authentication will be demanded.

3.4.1.1.5.7 Client Authentication: What the SSLClient has to do

Since all the work necessary for dealing with a certificate request of the server is doneby the client trust decider and client handshaker, a SSLClient implementation only has tobind the particular client trust decider into the context (as already done in 3.4.1.1.5.5):

SampleClientTrustDecider trustDecider = new SampleClientTrustDecider(true);

context.setTrustDecider(trustDecider);

Keep in mind, that implementing a client trust decider is an absolute necessity forsupporting client authentication!

Now we can close our SSLClientContext discussion with a short summary.

3.4.1.1.6 SSLClientContext: Summary

The SSLClientContext class extends the abstract SSLContext class for providingall the security features a SSLSocket may need to perform a SSL communictaion.

Page 93: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

93

An object of the SSLClientContext class may be created using either the defaultempty constructor or by defining a random number generator (3.4.1.1.1) to be used forgenerating all the random numbers required during the handshake procedure.

Several methods enable the user to set/get the security features of theSSLClientContext object.

Enabled cipher suites (3.4.1.1.2) and compression methods (3.4.1.1.3) define the keyexchange, symmetric encryption and MAC, respectively compression algorithms supportedby a particular SSLClientContext object.

Session Manager (3.4.1.1.4) and Trust Decider (3.4.1.1.5) interfaces provide templatesfor enabling the user to implement her/his own session caching repectively peer certificatetrusting policy.

To activate the security properties of a particular SSLClientContext object, it has tobe incorporated into the SSLSocket object for which it has been created:

SSLSocket socket = null;SSLClientContext context = new SSLClientContext();...supply the context object with user implemented properties (optional)...socket = new SSLSocket(serverName, serverPort, context);

At the beginning of this chapter, it has been mentioned that all the basic properties of aSSLClientContext object also are supported by a SSLServerContext object. Duringthe course of this chapter, several times when necessary it has been pointed ontodifferences between client and server implementation.

The following introduction to the SSLServerContext class therefore only brieflydescribes the additional features the server context may provide in extension to the clientcontext.

3.4.1.2 The SSLServerContext Class

The SSLServerContext class extends the SSLClientContext class about someproperties required only by the server socket of a SSL connection.

Remember the two tasks, a SSL server context must add to the functionality of a SSLclient context:

• The server delegates the task of obtaining certificates, private and temporary keysused for authentication and key exchange not to a trust decider. Rather certificatesand keys are directly supplied to the actual server context object. Therfore theSSLServerContext class has to provide appropriate methods making it easy toset/get the corresponding entities from a server context object.

• The server context object serves as a intermediary between the server and itshandshaker when sending a certificate request message to the client. Therefore the

Page 94: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

94

SSLServerContext class on the one hand includes a method for allowing theserver to specify certificate types and certification authorities for the certificaterequest message. On the other hand, the server handshaker will ask the contextwhether the server has directed to sent a certificate request message or not.

It already has been discussed in chapter 3.3.2 how the server may get proper certificatesand keys for authentication from files holding IAIK KeyAndCertificate structures (seealso 3.4.1.1.5.3 ). So it will do at this place only to repeat the binding of the severalcertificates/keys into the server context object:

// set the RSA certificate/private key for RSA cipher suitesserverContext.setRSACertificate(kac.getCertificateChain(),

epki.getPrivateKeyInfo());// set the DSA certificate/private key for DSA cipher suitesserverContext.setDSACertificate(kac.getCertificateChain(),

epki.getPrivateKeyInfo());

// set the DH certificate/private key for DH cipher suitesserverContext.setDHCertificate(kac.getCertificateChain(),

epki.getPrivateKeyInfo());

//set the temporary RSA key pair for RSA_EXPORT cipher suitesserverContext.setRSATempKeyPair(tempKeyPair);// set the DH parameter for ephemeral cipher suitesserverContext.setDHParameter(dhparam);

Remember, that each specific kac object is created as instance of theiaik.utils.KeyAndCertificate class for generating the desired private key andbelonging certificate chain from DER encoded files. Since the inherent private key hasbeen protected by password based encryption, it has to be decrypted by instantiating theiaik.pkcs.pkcs8.EncryptedPrivateKeyInfo class when creating a "key holding"epki object (see 3.3.2).

The getCertificateChain() method of the KeyAndCertificate class has to beused to obtain X.509 certificates as required by the server context. Any application mayimplement their own strategy for obtaining certificates and key material from someavailable source. However, it has to be noticed that the several set*Certificate(..)methods of the SSLServerContext class claim for certificates according to the X.509syntax.

The SSLServerContext class provides a particular utility method for automaticallyenabling all cipher suites that can be supported by the actual set of certificates and keys:

public CipherSuite[] updateCipherSuites()

Page 95: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLContext

95

In this way, supposing to already have set key and certifcates as describedabove, only the updateCipherSuites() has to be called for enabling allcorresponding cipher suites:

serverContext.updateCipherSuites();

The second additional task of the SSLServerContext class - serving as a intermediarybetween the server and its handshaker when sending a certificate request message to theclient - also has been described within the last sections (see 3.4.1.1.5.6).

After the server has defined certification authorities and certificate types it is willing toaccept, it makes them available for the server handshaker by preparing the server context:

serverContext.setRequireClientCertificate(types, acceptedCAs);

For providing a answer to the server handshaker´s question whether a certificate requestmessage has to be sent to the client or not, the SSLServerContext class uses a booleanmethod returning true if certificate request shall be sent and false otherwise:

public boolean getRequireClientCertificate();

After creating a SSLServerContext object and optionally supplying it with someuser-defined facilities, the server context has to be incorporated into the actualSSLServerSocket object:

SSLServerSocket serverSocket = null;SSLServerContext serverContext = new SSLServerContext();...supply the context object with user implemented properties (optional)...

serverSocket = new SSLServerSocket(port, serverContext);

In general, the incorporating a SSLClientContext object into a SSLSocket object -respectively a SSLServerContext object into a SSLServerSocket object - willcomplete the context intitialization phase. Correspondingly, we can close ourSSLContext discussion and proceed over to a short introduction of the SSLSocketclasses thereby concentrating on the properties that may be of main interest whenimplementing the client or server side of a SSL connection.

Page 96: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLSocket

96

3.4.3 The SSLSocket Class

An object of the Socket class of the java.net package implements one end-point of atwo-way communication link between two programs running on the network (javaTut]).

An object of the SSLSocket class extends a Socket object about SSL´s inherentsecurity features that mainly are determined by the corresponding SSLContext object.

Introducing we shall look back to section 3.1 where briefly has been described how aSSLClient implementation may open a SSL connection by instantiating the SSLSocketclass and supplying a SSLClientContext object for defining particular security features:

PrintWriter writer = null;BufferedReader reader = null;SSLSocket s = null;SSLClientContext context = new SSLClientContext();try {

s = new SSLSocket(serverName, serverPort, context); s.setDebugStream(System.out);

reader = new BufferedReader( new InputStreamReader(s.getInputStream()));

writer = new PrintWriter(s.getOutputStream()); ... communicate with server ...

s.close();} catch (UnknownHostException ex) { System.out.println("UnknownHostException: "+ex.getMessage());} catch (IOException ex) { System.out.println("IOException: "+ex.getMessage());}

First a new SSL stream socket is created for connecting to a server specified by its nameand listening on port serverPort. For the particular SSLSocket constructor used in theexample above it is necessary to identify the server by its name. As already might befamiliar from the conventional Socket class, the SSLSocket class provides a variety ofconstructors allowing to specify the communication partner by its InetAddress. Also thedefault constructor is included for creating a unconnected socket as may be used by theserver socket.

In addition to the initial example of section 3.1, now we will open not only an outputand input stream for writing to and reading from the socket, but also an debug stream forprinting debugging information during the handshake phase to System.out (look at thebold line in the program code fragment above). Note that for increasing efficiency we alsonow will buffer the strings read in from and written out to the socket.

For actually communicating with the server, in our example we make use of theprintln() and readLine() methods of the java.io.PrintWriter respectivelyjava.io.BufferedReader class to write/read strings to/from the socket streams.

Page 97: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLSocket

97

Supposing, the client wishes to get the homepage of the specified server, it prints acorresponding request onto the buffered output stream and subsequently flushes this streamforcing any buffered output bytes to be written out to the underlying output stream:

String request = new String("GET / HTTP/1.0");writer.println(request);writer.println();writer.flush();

Following this, the data sent back from the server are read in line by line from thesocket input stream and printed to System.out:

String line;while ((line = reader.readLine()) != null) { System.out.println("Server sends: "+line);}

After some communiction with the server, the connection is closed by first closing theserveral streams and subsequently closing the SSL socket.

So far, we have learned enough for being able to implement the client´s side of a SSLconnection by creating a SSLSocket object, initializing it with the corresponding contextobject for defining the security features, opening input and output streams onto the socket,performing some communication with the server, and finally closing streams and socket.

The remaining discussion of the SSLSocket class will introduce three properties thatmay be used by some application for

• implementing a connection over a SSL proxy

• obtaining the certificate chain sent by the peer directly from the SSLSocket object.

• renegotiating new security specifications for the current session

3.4.3.1 Connecting via a Proxy

If the SSL client wishes to connect to a particular server via a proxy, no SSL handshakedialogue should be performed when the client connects to the proxy asking for establishinga SSL connection to the server listening on a specified port number. Since the handshakeprocedure will start automatically as soon as any stream is opened onto a SSL socket, theclient explicitly has to direct its handshaker not to perform a handshake dialogue whencontacting the proxy. Later, when the proxy is ready to ´forward´ the connection to thedesired server, the client must start the handshake process manually.

Suppose, we have implemented an extra method for sending a ´connect-to-server´request to the proxy. This message will be sent to the proxy without being encrypted.Therefore we first open a SSL socket for connecting to the proxy and explicitly switch off

Page 98: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLSocket

98

the automatic handshake start (look at the bold line in the following program codefragment):

SSLSocket s = new SSLSocket(proxyName, proxyPort, context);s.setAutoHandshake(false);

Since the automatic handshake is turned off , now we can open input and output streamsonto the socket for sending the unencrypted ´connect-to-server´ message to the proxy.

reader = new BufferedReader( new InputStreamReader(s.getInputStream()));

writer = new PrintWriter(s.getOutputStream());//send ´connect to server´ message to proxyproxyConnect(serverName, serverPort);

For enabling the handshake dialogue between proxy and server, now we have to startthe handshake dialogue manually:

s.startHandshake();

If the following handshake procedure will be successfully completed, we can start theprotected communication with the server using the proxy as ´intermediary point´.

3.4.3.2 Obtaining the peer´s certificate

For providing an application a direct access to the certificate sent by the peer, theSSLSocket class is equipped with the getPeerCertificateChain() method theapplication may call to obtain the peer´s certificate chain for some reason (for instance forexplicitly checking if the peer´s certificate is trustworthy when not done so by a trustdecider). The following example reads in the peer´s certificate chain from the socket s andprints all the included certificates to System.out:

X509Certificate[] chain = s.getPeerCertificateChain();for (int i=0; i<chain.length; i++) System.out.println("Certificate "+i+": "+chain[i].getSubject());System.out.println();

In the same way we may get active cipher suite and compression method from theSSLSocket. Remember that the active cipher suite is the one specific cipher suite clientand server have negotiated for defining key exchange, symmetric encryption and MACalgorithms of the current session. Correspondingly, the active compression method definesthe compression algorithm for compressing the data records of the actual session.

Page 99: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLSocket

99

CipherSuite active_cs = s.getActiveCipherSuite();CompressionMethod active_cm = s.getActiveCompressionMethod();

3.4.3.3 Security Parameter Renegotiation

At any time during a SSL client-server communication, the server may decide to´refresh´ the security settings (active cipher suite, active compression method, ...) of thecurrent session by sending a Hello Request message indicating the client to start a newhandshake dialogue by transmitting a new Client Hello message. The Hello Requestmessage will be ignored by the client if it arrives actually during a handshake phase.Otherwise the client will start a complete new handshaking procedure by sending theClient Hello message. The only difference is that the handshake messages of this secondhandshaking procedure will already be protected by the cryptographic parameters whichhave been negotiated during the first handshaking procedure. So any attacker even wouldnot be able to see the normal unencrypted Hello and Key Exchange messages.

On the other hand, the client itself may initiate a parameter refreshment by sending aClient Hello message to the server.

The following section decribes parameter renegotiation within the iSaSiLk environmentfrom the server´s point of view. Renegotiation initiated from the client requires anequivalent proceeding.

iSaSiLk provides a quite simple mechanism for enabling a SSLServer implementation toinitiate a new handshake dialogue by sending a Hello Request message. Imaging the serverside somewhere during a SSL client-server conversation. The server communicates withthe client by means of streams that are opened on a SSLSocket object generated whenaccepting a client´s request at the beginning of the actual session:

SSLSocket s;s = (SSLSocket)serverSocket.accept();OutputStream os = s.getOutputStream();

InputStream is = s.getInputStream(); ...

Now the server decides for some reason - for instance, it wants to use a 128Bit key RC4cipher for data encryption instead of the originally negotiated 40Bit key RC4 - torenegotiate the security specifications of the current session. It can do so by simply callingthe SSLSocket class´ renegotiate() method ordering the server handshaker to send aHello Request message. Since this method may throw an IOException, the server must takecare for catch it:

Page 100: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLSocket

100

try { s.renegotiate(); } catch (IOException ex) { System.out.println("IOException: "+ex.getMessage()); }

A call to the SSLSocket´s renegotiate() method automatically will cause theserver handshaker to send the Hello Request message for initiating the client handshaker torespond with its Client Hello message.

However, before ordering the server handshaker to send the Hello Request message, theserver should change the context of the actual ´client-communicating´ SSLSocketaccording to the new security parameters it wants to renegotiate for the current session.Supposing the server wishes to ´force´ the SSL_RSA_WITH_RC4_128_MD5 cipher suitefor performing a 128Bit key RC4 data encryption, it first has to set the appropriate ciphersuite. For that reason the actual context object has to be obtained from the SSLSocket (wealternatively may create a new context object and supply it with the new settings; but if weonly want to ´refresh´ the enabled cipher suites, we can rely on all the other contextsettings that already have been established):

SSLContext con = s.getContext();

Following this, the obtained context object has to be refreshed according to the desiredcipher suite:

CipherSuite[] new_cs = new CipherSuite[1];new_cs[0] = CipherSuite.SSL_RSA_WITH_RC4_128_MD5;con.setEnabledCipherSuites(new_cs);

Finally, after incorporating the modified context object into the SSLSocket again, therenegotiation process may be initiated:

s.setContext(con);try { s.renegotiate();} catch (IOException ex) { System.out.println("IOException: "+ex.getMessage());}

Summing up, all the work that have to be done by a SSLServer for renegotiating thecryptographic parameters of the current session, may lead to a program code fragmentsimilar to (s further on denotes the SSLSocket object initially returned by the accept()method for communicating with the client):

//define a new cipher suite (or any new context parameters if desired)CipherSuite[] new_cs = new CipherSuite[1];new_cs[0] = CipherSuite.SSL_RSA_WITH_RC4_128_MD5;

Page 101: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLSocket

101

//get the actual context from the SSLSocketSSLContext con = s.getContext();//set the new cipher suite as enabled cipher suitecon.setEnabledCipherSuites(new_cs);//set the modified context for the SSLSocket agains.setContext(con);

//start the renegotiation process try {

s.renegotiate(); } catch (SSLException ex) {

System.out.println("SSLException: "+ex.getMessage()); }

On the other side, just the same program fragment may be used by a SSLClient thatitself wishes to initiate a security parameter regoniation. In this case, of course, the socket sfrom the example above will indicate the SSLSocket the client uses to communicate withthe server.

However, a server may want to refresh not only the security parameters of the currentclient session, but also set the new parameters for any further client request. Notice, that inthe example above, we have changed the cipher suite settings of the context objectbelonging to the SSLSocket object that is used to communicate with some particular client.We have not changed the server context object! When the server - at the beginning of thecurrent session - has called the SSLServerSocket´s accept() method, a SSLSocket objecthas been returned for communicating with the client. Thereby, inside the accept()method and not visible for the user, the new created SSLSocket object has been initializedwith the actual SSLServerContext for determining the several cryptographic settings(cipher suites, compression methods, ...) the sever handshaker has used to go into thehandshake dialogue with the client handshaker. In changing only the context of thisSSLSocket will redefine the server´s handshake conditions for renegotiating the securityparameters of the current session with this one particular client. All further incoming clientrequests still will be handled by the ´old´ server context settings, since the accept()method initializes each new created SSLSocket object with the unchanged server context.

If we want to define new server context settings not only for renegotiating thecryptographic parameters of the current session, but also for every further handshakedialogue, we directly may change the server context when starting the renegotiationprocess:

//define a new cipher suite (or any new context parameters if desired)CipherSuite[] new_cs = new CipherSuite[1];new_cs[0] = CipherSuite.SSL_RSA_WITH_RC4_128_MD5;//set the new cipher suite as enabled cipher suite for the actual//server contextserverContext.setEnabledCipherSuites(new_cs);//set the modified server context for the SSLSockets.setContext(serverContext);

//start the renegotiation processs.renegotiate();

Page 102: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLSocket

102

Note, that when implementing a SSLClient based on iSaSiLk, no care has to be takenabout any Hello Request message coming from some server just communicating to. All thework necessary to handle a server´s Hello Request is done by the client handshaker!

In addition of being able to realize all the basic tasks that are necessary forimplementing the client´s side of a SSL connection, now we may include a proxy and/orobtain the peer´s certificate directly from the SSL socket - quite enough for building areasonable SSLClient.

For implementing a SSLServer we also have to know something about theSSLServerSocket class.

3.4.4 The SSLServerSocket Class

An object of the ServerSocket class of the java.net package implements a serversocket waiting on requests coming from any calling client.

An object of the SSLServerSocket class extends a ServerSocket object aboutSSL´s inherent security features that mainly are determined by the correspondingSSLServerContext object.

Again, we shall look back to the example of section 3.2 introducing a simpleimplementation of the server side of a SSL connection:

SSLServerSocket server = null;SSLSocket s = null;SSLServerContext serverContext = new SSLServerContext();try {

server = new SSLServerSocket(serverPort, serverContext);} catch (IOException ex) { System.out.println("IOException: "+ex.getMessage());}while (true) { try {

s = (SSLSocket)server.accept(); OutputStream os = s.getOutputStream();

InputStream is = s.getInputStream(); ... communicate with client ...

s.close(); } catch (SSLException ex) { System.out.println("SSLException: "+ex.getMessage()); } catch (IOException ex) { System.out.println("IOException: "+ex.getMessage()); }}

Page 103: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLSocket

103

First a SSLServerSocket object is created and supplied with a SSLServerContextobject for defining particular security features. The constructor used in the example abovegenerates a server socket on an explicitly specified port the server shall listen for incomingconnection requests. There are many other constructors within the SSLServerSocketclass making it possible not to specify any port number and/or limiting the number ofincoming connection indications to be handled. If no particular port number is set, theserver socket is created at any free port. If no particular context object is supplied, theserver socket is created with a default context.

When a request for connect comes in over the network, the server socket accepts thisrequest and returns a new SSLSocket for communicating with the client. Since theSSLServerSocket´s accept() method per default returns a conventional Socket object,an explicit cast is necessary for obtaining a SSLSocket object.

Now output and input streams are opened onto the new created SSLSocket object foractually communicating with the requesting client.

For our example, we will implement a SSLServer waiting for a SSL connection comingfrom some browser. If the connection is accepted, the server only will return the string"SSL Test ok.".

First the client´s message is read from the input stream into a byte array andsubsequently printed to System.out:

byte[] arr = new byte[300];int l=-1;for (int i=0; i<10 && l<0; i++) l = is.read(arr);System.out.println("client sends: "+l);for (int j=0; j<l; j++) System.out.print((char)arr[j]);

For displaying the answering "SSL Test ok." message in the requesting browser, wehave to ´pack´ it into a HTML page and transfer it according to the hyper text transferprotocol (HTTP). Supposing to have implemented an extra methodaddLine(String line) for reading strings into a buffer byte array, we may fill thebuffer with our HTTP message:

//write to some buffer byte arrayaddLine("HTTP/1.0 200 OK");addLine("Content-Type: text/html");addLine("Server: IAIK-SSL Testserver");addLine("");addLine("<HTML><HEAD>");addLine("<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html;CHARSET=iso-8859-1\">");addLine("<TITLE>SSL Test</TITLE>");addLine("</HEAD>");addLine("<BODY>");addLine("<H1>SSL Test ok.</H1>");addLine("</BODY>");addLine("</HTML>");

Page 104: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLSocket

104

Finally we´ll send the message to the browser by putting the buffer contents onto theSSLSocket´s output stream and subsequently flushing the stream:

os.write(buffer, 0, pos);os.flush();

The variable pos indicates the number of bytes stored within the buffer to be writtenonto the stream. The value of pos automatically has been updated inside the addLine()method everytime a string has been read into the buffer:

static byte[] buffer = new byte[10000];//initially the buffer is emptystatic int pos = 0;//carriage return line feedstatic byte[] crlf = {13, 10};//method for reading a string into a byte arraypublic static void addLine(String line) { byte[] arr = line.getBytes(); int len = arr.length; System.arraycopy(arr, 0, buffer, pos, len); pos += len; System.arraycopy(crlf, 0, buffer, pos, 2); pos += 2;}

The method arraycopy(Object src, int src_pos, Object dst, int dst_pos) copies ansub array of the source array to the destination array. The sub array of the source arraystarts at src_pos and is copied to dst_pos within the destination array.

After sending the data to the browser, the server yet close SSLSocket thereby closingany stream onto the socket. When explicitly closing streams, the output stream must beclosed before closing the input stream. The server socket itself remains opened continuingto listen on incoming client requests:

os.close();is.close();s.close();

There are no more particular features of the ServerSocketClass for being of interestwhen implementing a SSL server.

The following concluding section will step through example SSLClient respectivelySSLServer implementations thereby repeating all the features we have learned during thecourse of this paper.

Page 105: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLClient and SSLServer

105

3.5 Example: SSLClient and SSLServer

During the course of this paper, several program code fragments have providedexamples for tasks that may be included by some particular SSLClient respectivelySSLServer implementation. Within this final chapter we will put all together forcompletely describing a sample SSLClient and SSLServer implementation.

According the general line of this paper, we will start in discussing the SSLClient andfinish with the description of the SSLServer.

3.5.1 A SSLClient Implementation Example

Our concluding SSLClient implementation is based on the client example brieflyintroduced in chapter 3.4.3 when presenting the SSLSocket class.

Remember, that this client connects to a server asking it to send its homepage. Forenabling the user to specify the server to be contacted, we extend our SSLClient exampleabout the possibility for reading in the server´s name and port number to be listening atruntime. Furthermore, optionally a proxy host and port may be supplied for connecting tothe desired server via a proxy.

Assuming that a specific client trust decider is implemented, we will include it into ourSSLClient implementation.

We won´t use some particular security provider. Rather we will rely on the default IAIKprovider making it superfluous to explicitly set some specific SecurityProviderimplementation (see 3.3.1).

We have to start with importing all the classes necessary for performing I/O, net andsecurity operations, adding a ptovider, dealing with RSA, PKCS and X.509 structures, andsupporting ssl objects:

import java.io.*;import java.net.*;import java.security.*;import java.security.cert.X509Certificate;

import iaik.security.ssl.*;import iaik.security.provider.IAIK;import iaik.security.rsa.*;import iaik.pkcs.*;

For realizing proxy connections we implement a seperate proxyConnect(..) methodthat has to be called with the server name and port the proxy shall connect to. Since thecontact to the proxy is established by operating on socket streams that are opened only later

Page 106: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLClient

106

within the main procedure, the corresponding class variables have to be declared global forproxyConnect and main method:

//stream for writing Strings to the SSLSocketstatic PrintWriter writer = null;//stream for reading Strings buffered from the SSLSocketstatic BufferedReader reader = null;

The proxyConnect(..) method itself only sends a request message to the proxy forconnecting to a specified server at a specified server port using the HTTP protocol. Both,proxy name and port as well as server name and port are supplied at runtime. Note that theproxyConnect(..) method don´t need to know the proxy´s name. The connection to theproxy is already established when the proxyConnect(..) method is called forforwarding the connection to the specified server. So the the proxyConnect(..) methodwill operate on streams already opened onto the socket for communicating with the proxy:

/** * This method is used for connecting over a SSL proxy. * * This method just sends "CONNECT host:port HTTP/1.0\n\n" (NOT * ENCRYPTED!) to the proxy and displays the messages sent back from * the proxy. * * @param host the host name where a SSL connection should be * established * @param port the port number of that host * * @exception IOException if any problem with the socket occurs */ public static void proxyConnect(String host, int port) throws IOException { String request =

new String("CONNECT "+host+":"+port+" HTTP/1.0"); //write request onto output stream writer.println(request); writer.println(); writer.flush(); //read and print the proxy´s answers String line; do { line = reader.readLine(); System.out.println("Proxy sends: "+line); } while (line.length() > 0); System.out.println(); }

Now we are ready to implement the several tasks of the main procedure of ourSSLClient class. First, we will read in server name and port just as proxy name and port. Ifthe user will hurt the input format, a failure message shall be printed onto the screen:

Page 107: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLClient

107

//read in server name and server port if (arg.length >= 1) serverName = arg[0]; else { System.out.println("Usage: server host:port [proxy:port]\n

You can try: ssl3.netscape.com:443\n"); System.exit(0); } //determine server name and server port int p = serverName.indexOf(58); if (p > 0) { serverPort = Integer.decode(serverName.substring(p+1)).intValue(); serverName = serverName.substring(0, p); } //read in proxy name and proxy port if (arg.length >= 2) { proxyName = arg[1]; //determine proxy name and proxy port p = proxyName.indexOf(58); // proxy port if (p > 0) { proxyPort = Integer.decode(proxyName.substring(p+1)).intValue(); proxyName = proxyName.substring(0, p); } }

W For supporting the IAIK-JCE cryptographic algorithm implementations, we must addthe IAIK provider (see section 3.3.2):

IAIK provider = new IAIK(); Security.addProvider(provider);

Within the next lines of program code we first will declare a SSLSocket object.Following this, we create a SSLClientContext object for preparing the security featuresof the SSLSocket. Assuming our client will support only the two cipher suitesSSL_RSA_WITH_IDEA_CBC_SHA and SSL_DH_DSS_WITH_DES_CBC_SHA, we first have todeclare an array for being able to hold two cipher suites and subsequently set theappropriate suites. Since our SSLClient shall include a client trust decider for checking thetrustworthiness of peer certificates and managing server certificate requests, we have tocreate a client trust decider object instantiating the SampleClientTrustDecider classas introduced in section 3.4.1.1.5.3. Instead of taking the SampleClientTrustDecider, youmay implement your own client trust decider. After defining cipher suites and client trustdecider, we have to incorporate them into the client context. Note, that we don´t haveimplemented a separate session manager. We agree with the default session manager(3.4.1.1.4.4) for managing the session cache.

Page 108: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLClient

108

SSLSocket s = null; SSLClientContext context = new SSLClientContext(); //define cipher suites to be supported CipherSuite[] cs = new CipherSuite[2]; cs[0] = CipherSuite.SSL_RSA_WITH_IDEA_CBC_SHA; cs[1] = CipherSuite.SSL_DH_DSS_WITH_DES_CBC_SHA; //enable the two cipher suites context.setEnabledCipherSuites(cs); //create a client trust decider SampleClientTrustDecider trustDecider =

new SampleClientTrustDecider(true); //enable the client trust decider

context.setTrustDecider(trustDecider);

Now, we can start the actual communication with the server. If a proxy name has beenspecified by the user, a proxy is used as ´intermediary point´. If no proxy is to be used, aSSLSocket is created and connected to the specified port number on the named host. Thesecurity features of the SSLSocket are defined by setting the client context. Output andinput streams are opened onto the socket for writing data to and reading data from thesocket. For printing debugging info to System.out, we enable the debugging stream.

If the connection shall go over a proxy, a SSLSocket is created and connected to thespecified port number on the named proxy. Since the ´connect-to-server´ message sent tothe proxy is not to be encrypted, the automatic handshake has to be disabled beforeopening any streams onto the socket. After the proxy has answered to the client´s request,the handshake has to be switched on manually for negotiating the security parameters withthe server:

if (proxyName == null) { // dont’t connect over a proxy s = new SSLSocket(serverName, serverPort, context); s.setDebugStream(System.out); //debugging info to System.out reader = new BufferedReader(

new InputStreamReader(s.getInputStream())); writer = new PrintWriter(s.getOutputStream());

} else { s = new SSLSocket(proxyName, proxyPort, context); s.setDebugStream(System.out);

//disbale automatic handshake start s.setAutoHandshake(false);

reader = new BufferedReader(new InputStreamReader(s.getInputStream())); writer = new

PrintWriter(s.getOutputStream()); //send connect-to-server request to proxy proxyConnect(serverName, serverPort);

//start handshake dialogue manually s.startHandshake(); }

Page 109: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLClient

109

After establishing streams onto the socket, our client can send the request for theserver´s homepage according to the HTTP protocol. It therefore puts the appropriatemessage onto the output streams. The headers sent back from the server are read in fromthe input stream and printed to System.out.

Before starting the actual data transfer, we will print active cipher suite andcompression method of this session onto the screen. Additionally we also will print thecertificate chain sent from the server. For obtaining the corresponding entities from thesocket, we use the proper methods as described in section 3.4.3:

System.out.println("Active cipher suite: " +s.getActiveCipherSuite().getName());

System.out.println("Active compression method: " +s.getActiveCompressionMethod().getName());

System.out.println("\nServer certificate chain:"); X509Certificate[] chain = s.getPeerCertificateChain(); for (int i=0; i<chain.length; i++) System.out.println("Certificate "+i+": "

+chain[i].getSubject()); System.out.println();

String request = new String("GET / HTTP/1.0");

System.out.println("Send request for server homepage..."); writer.println(request); writer.println(); writer.flush();

String line; do { line = reader.readLine(); System.out.println("Server sends: "+line); } while (line != null);

s.close();

Now, our SSLClient implementation is ready to put all the several parts together forobtaining a view of the complete SSLClient class implementation.

import java.io.*;import java.net.*;import java.security.*;import java.security.cert.X509Certificate;

import iaik.security.ssl.*;import iaik.security.provider.iaik;import iaik.security.rsa.*;import iaik.pkcs.*;/** * Demo SSL client implementation. */

Page 110: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLClient

110

public class SSLClient {

//stream for writing Strings to the SSLSocket static PrintWriter writer = null; //stream for reading Strings buffered from the SSLSocket static BufferedReader reader = null;

/** * This method is used for connecting over a SSL proxy. * * This method just sends "CONNECT host:port HTTP/1.0\n\n" (NOT * ENCRYPTED!) to the proxy and displays the messages sent back from * the proxy. * * @param host the host name where a SSL connection should be * established * @param port the port number of that host * * @exception IOException if any problem with the socket occurs */ public static void proxyConnect(String host, int port) throws IOException { String request =

new String("CONNECT "+host+":"+port+" HTTP/1.0"); //write request onto output stream writer.println(request); writer.println(); writer.flush(); //read and print the proxy´s answers String line; do { line = reader.readLine(); System.out.println("Proxy sends: "+line); } while (line.length() > 0); System.out.println(); }

/** * Connects to a SSL server and displays the headers sent back by * the server. * * Usage: server host:port [proxy:port] */ public static void main(String arg[]) throws IOException {

// for waiting till a key is pressed BufferedReader key = new BufferedReader(

new InputStreamReader(System.in));

String serverName = null; int serverPort = 443; String proxyName = null; int proxyPort = 9999;

System.out.println("add Provider IAIK...\n");

Page 111: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLClient

111

IAIK provider = new IAIK(); Security.addProvider(provider);

//read in server name and server port if (arg.length >= 1) serverName = arg[0]; else { System.out.println("Usage: server host:port [proxy:port]\n

You can try: ssl3.netscape.com:443\n"); System.exit(0); } //determine server name and server port int p = serverName.indexOf(58); if (p > 0) { serverPort = Integer.decode(serverName.substring(p+1)).intValue(); serverName = serverName.substring(0, p); } //read in proxy name and proxy port if (arg.length >= 2) { proxyName = arg[1]; //determine proxy name and proxy port p = proxyName.indexOf(58); // proxy port if (p > 0) { proxyPort = Integer.decode(proxyName.substring(p+1)).intValue(); proxyName = proxyName.substring(0, p); } }

SSLSocket s = null; SSLClientContext context = new SSLClientContext(); //define cipher suites to be supported CipherSuite[] cs = new CipherSuite[2]; cs[0] = CipherSuite.SSL_RSA_WITH_IDEA_CBC_SHA; cs[1] = CipherSuite.SSL_DH_DSS_WITH_DES_CBC_SHA; //ebable the two cipher suites context.setEnabledCipherSuites(cs); //create a client trust decider SampleClientTrustDecider trustDecider =

new SampleClientTrustDecider(true); //enable the client trust decider

context.setTrustDecider(trustDecider);

System.out.print("Connect to "+serverName+":"+serverPort);

if (proxyName != null) System.out.print(" via "+proxyName+":"+proxyPort);

System.out.println("\n");

try { if (proxyName == null) { // dont’t connect over a proxy

Page 112: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLClient

112

s = new SSLSocket(serverName, serverPort, context); s.setDebugStream(System.out); //debugging info to System.out reader = new BufferedReader(

new InputStreamReader(s.getInputStream())); writer = new PrintWriter(s.getOutputStream());

} else { s = new SSLSocket(proxyName, proxyPort, context); s.setDebugStream(System.out);

//disbale automatic handshake start s.setAutoHandshake(false); reader = new BufferedReader(

new InputStreamReader(s.getInputStream())); writer = new PrintWriter(s.getOutputStream());

//send connect-to-server request to proxy proxyConnect(serverName, serverPort);

//start handshake dialogue manually s.startHandshake(); } System.out.println("\nConnection established...\n"); System.out.println("Active cipher suite: "

+s.getActiveCipherSuite().getName()); System.out.println("Active compression method: "

+s.getActiveCompressionMethod().getName()); System.out.println("\nServer certificate chain:"); X509Certificate[] chain = s.getPeerCertificateChain(); for (int i=0; i<chain.length; i++) System.out.println("Certificate "+i+": "

+chain[i].getSubject()); System.out.println();

String request = new String("GET / HTTP/1.0"); System.out.println("Send request for server homepage..."); writer.println(request); writer.println(); writer.flush();

String line; do { line = reader.readLine(); System.out.println("Server sends: "+line); } while (line != null);

s.close(); } catch (UnknownHostException ex) { System.out.println("UnknownHostException: "+ex.getMessage()); } catch (IOException ex) { System.out.println(ex.getMessage()); } catch (Exception ex) { System.out.println("Exception: "+ex.getMessage()); } //wait till a key is pressed key.readLine(); }

Page 113: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLClient

113

}

Note, that the finished version of our SSLClient also includes exception handling.

Running the SSLClient we may get a screen output similar to:

send client_hello...received server_hello...Server doesn’t want to resume a previous session.CipherSuite selected by server: SSL_RSA_EXPORT_WITH_RC4_40_MD5CompressionMethod selected by server: NULLreceived Certificate...Server certificate chainC=AT, SP=8010 Graz, L=Steyrergasse 30/I, O=Technical University Graz,OU=Computing and Information Services Center, CN=cisc.tu-graz.ac.atC=US, O=RSA Data Security, Inc., OU=Secure Server Certification Authorityreceived server_hello_done...send ClientKeyExchange...send change_cipher_spec...send finished...received change_cipher_spec...received finished...

Connection established...

Active cipher suite: SSL_RSA_EXPORT_WITH_RC4_40_MD5Active compression method: NULL

Server certificate chain:Certificate 0: C=AT, SP=8010 Graz, L=Steyrergasse 30/I, O=Technical University Graz, OU=Computing and Information Services Center, CN=cisc.tu-graz.ac.atCertificate 1: C=US, O=RSA Data Security, Inc., OU=Secure Server Certification Authority

Send request for server homepage...

Server sends: HTTP/1.0 200 OKServer sends: Server: Netscape-Enterprise/2.0aServer sends: Date: Thu, 22 Jan 1998 12:05:47 GMTServer sends: Accept-ranges: bytesServer sends: Last-modified: Thu, 20 Mar 1997 08:55:28 GMTServer sends: Content-length: 2834Server sends: Content-type: text/htmlServer sends:Server sends: <HTML>Server sends:Server sends: <HEAD>Server sends: <TITLE>Enterprise Home Page</TITLE>Server sends: </HEAD>Server sends:Server sends: <BODY BGCOLOR="#ffffff" TEXT="#000000" LINK="#0000ff"

VLINK="#01424a">

Page 114: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLClient

114

...Server sends:Server sends: </BODY>Server sends: </HTML>

First the handshake messages are reported, followed by the data received from theserver including its HTML formatted home page lines.

The next - and already last - section provides a sample SSLServer implementation.

Page 115: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLServer

115

3.5.2 A SSLServer Implementation Example

As already done within the previous section when presenting a demo SSLServerimplementation, we will build up our concluding SSLServer onto the server examplebriefly introduced in chapter 3.4.4 when presenting the SSLServerSocket class.

Remember, that this server waits for a SSL connections coming from some browser andonly returns the string "SSL Test ok.".

Our SSLServer will support all the cipher suites that can be supported when using theactual set of certificates and keys, and it shall claim for client authentication by requestingthe client´s certificate.

Assuming that a specific server trust decider is implemented, we will include it into ourSSLServer implementation.

Cryptography parameter renegotiation can be switched on by an extra control variable.

We won´t use some particular security provider. Rather we will rely on the default IAIKprovider making it superfluous to explicitly set some specific SecurityProviderimplementation (see 3.3.1).

We have to start with importing all the classes necessary for performing I/O, net andsecurity operations, adding a provider, dealing with DSA, RSA, DH, PKCS, X.509 andASN.1 structures and supporting ssl objects. For "reading in" keys and certificates fromDER encoded files, we have to import iaik.utils.KeyAndCertificate, andpassword based private key de/encryption claims for importingiaik.pkcs.pkcs8.EncryptedPrivateKeyInfo.

import java.io.*;import java.net.*;import java.security.*;import java.math.BigInteger;import java.security.cert.X509Certificate;import javax.crypto.spec;

import iaik.security.ssl.*;import iaik.security.provider.IAIK;import iaik.security.dsa.*;import iaik.security.dh.*;import iaik.security.rsa.*;import iaik.pkcs.*;import iaik.asn1.structures.Name;import iaik.asn1.*;import iaik.utils.KeyAndCertificate;import iaik.pkcs.pkcs8.EncryptedPrivateKeyInfo;

The method addLine(String line) for writing Strings to a buffering byte arrayalready has been presented in section 3.3.4. Since the server´s "SSL Test o.k." messageshall be displayed by the browser connected to, the server creates the code for a HTMLpage that prints "SSL Test o.k.". This code line by line is written into the buffer array for

Page 116: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLServer

116

later putting it onto the socket´s output stream. The end of each line is marked by acarriage return line feed. The variable pos calculates the number of bytes read into thebuffer.

static byte[] buffer = new byte[10000];//initially the buffer is emptystatic int pos = 0;//carriage return line feedstatic byte[] crlf = {13, 10};//method for reading a string into a byte arraypublic static void addLine(String line) { byte[] arr = line.getBytes(); int len = arr.length; System.arraycopy(arr, 0, buffer, pos, len); pos += len; System.arraycopy(crlf, 0, buffer, pos, 2); pos += 2;}

The method arraycopy(Object src, int src_pos, Object dst, int dst_pos) copies ansub array of the source array to the destination array. The sub array of the source arraystarts at src_pos and is copied to dst_pos within the destination array.

The main procedure first adds the IAIK provider, declares a SSLSocket forcommunicating with the client, and creates a SSLServerContext object that may besupplied with particular properties.

IAIK provider = new IAIK(); Security.addProvider(provider); SSLSocket ssl = null; SSLServerContext serverContext = new SSLServerContext();

In contrast to a SSLClient implementation where it is the responsibility of the clienttrust decider to supply certificates and keys for authentication, the SSLServer immediatelyhas to take care for obtaining appropriate certificates, keys and parameters. Since ourSSLServer intends to support all the cipher suites implemented by iSaSiLk, it has to supplyall the cryptographic parameters required. Remember that for our example we will read incertificates and keys from files holding IAIK KeyAndCertificate structures (see 3.3.2):

try { // specify the DH parameters: BigInteger p = new BigInteger("da583c16d98522...", 16); BigInteger g = BigInteger.valueOf(2); DHParameterSpec dhparam = new DHParameterSpec(p, g); // set the DH parameter for ephemeral cipher suites serverContext.setDHParameter(dhparam); // create certificates and private keys and set them to the context: KeyAndCertificate kac; EncryptedPrivateKeyInfo epki; // set the RSA certificate/private key for RSA cipher suites

Page 117: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLServer

117

kac = new KeyAndCertificate("certs/serverRSA1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("This is the passphrase!"); serverContext.setRSACertificate(kac.getCertificateChain(),

epki.getPrivateKey()); // set the DSA certificate/private key for DSA cipher suites kac = new KeyAndCertificate("certs/serverDSA1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("This is the passphrase!"); serverContext.setDSACertificate(kac.getCertificateChain(),

epki.getPrivateKey());

// set the DH certificate/private key for DH cipher suites kac = new KeyAndCertificate("certs/serverDH1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("This is the passphrase!"); serverContext.setDHCertificate(kac.getCertificateChain(),

epki.getPrivateKey());

// set the temporary RSA key pair for RSA_EXPORT cipher suites RSAPrivateKey tsk = new RSAPrivateKey(

new FileInputStream("certs/tempRSAPrivateKey.der")); PublicKey tpk = tsk.getPublicKey(); KeyPair tempKeyPair = new KeyPair(tpk, tsk); serverContext.setRSATempKeyPair(tempKeyPair);

} catch (InvalidKeyException ex) { System.out.println("InvalidKeyException: "+ex.getMessage()); System.exit(0);} catch (NoSuchAlgorithmException ex) { System.out.println("NoSuchAlgorithmException:"+ex.getMessage()); System.exit(0);} catch (GeneralSecurityException ex) { System.out.println("GeneralSecurityException:"+ex.getMessage()); System.exit(0);} catch (IOException ex) { System.out.println("IOException: "+ex.getMessage()); System.out.println("No server certs found!");

System.exit(0);}

All generated certificates and corresponding private keys are incorporated into theserver context using the several set*certificate(..) methods. Remember, that theSSLServerContext class requires X.509 certificates, as returned by theKeyAndCertifcate´s method getCertificateChain (see 3.3.2).

Calling the updateCipherSuites() method of the SSLServerContext classautomatically will enable all the cipher suites that can be supported based on the particularkeys and certificates that just have been set: (see 3.4.1.2):

CipherSuite[] enabledCS = serverContext.updateCipherSuites();

Page 118: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLServer

118

We assume, that a server trust decider has been implemented for checking thetrustworthiness of certificates received from the client. We´ll take the demo server trustdecider of section 3.4.1.1.5.2 and set it for the server context:

// set a TrustDecider which checks the certificates sent by clientsSampleServerTrustDecider trustDecider = new

SampleServerTrustDecider(true);serverContext.setTrustDecider(trustDecider);

In supplying the SampleServerTrustDecider constructor with the boolean true value,we switch on the printing of debugging information to System.out.

Our SSLServer shall request a certificate from the client. Therefore, the server has tospecify the certification authorities and certificate types it is willing to accept. The serverinforms its server handshaker to send a certificate request message by supplying the servercontext´s setRequireClientCertificate(..) method with the intended certificationauthorities and certificate types (see section 3.4.1.1.5.6):

// specifiy the certification authorities to be accepted Name[] acceptedCAs = new Name[1];

Name verisign = new Name(); verisign.addRDN(ObjectID.country, "US"); verisign.addRDN(ObjectID.organization, "VeriSign, Inc."); verisign.addRDN(ObjectID.organizationalUnit,

"Class 1 Public Primary Certification Authority"); acceptedCAs[0] = verisign; // specify the certificate types to be accepted byte[] types = new byte[4]; types[0] = ClientTrustDecider.rsa_sign; types[1] = ClientTrustDecider.dss_sign; types[2] = ClientTrustDecider.rsa_ephemeral_dh; types[3] = ClientTrustDecider.dss_ephemeral_dh; // inform the handshaker to send a certificate request message serverContext.setRequireClientCertificate(types, acceptedCAs);

After defining and setting all particular security properties, a SSLServerSocketobject may be created to listen on a specific port for incoming client requests that areaccepted by creating a SSLSocket object for connecting to the client. Subsequently, outputand input streams are opened onto the socket for communicating with the client. A debugstream cares for printing debugging information to System.out.

First, the browser´s request is read in and printed to System.out, then the server sendsits HTML page lines using the HTTP protocol. If the boolean renegotiate variable isset to true, a renegotiation procedure is initiated for refreshing the cryptographic settings ofthe current session (see 3.4.3.3) before writing to the browser:

SSLServerSocket server = new SSLServerSocket(port, serverContext); while (true) {

Page 119: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLServer

119

try { ssl = (SSLSocket)server.accept();

// debug information to System.out ssl.setDebugStream(System.out); OutputStream os = ssl.getOutputStream(); InputStream is = ssl.getInputStream();

//read in data sent from the client byte[] arr = new byte[300]; int l=-1; for (int i=0; i<10 && l<0; i++) l = is.read(arr);

System.out.println("client sends: "+l); for (int j=0; j<l; j++) System.out.print((char)arr[j]);

if (renegotiate) { //initially set to false System.out.println("renegotiating cipher suite...");

CipherSuite[] new_cs = new CipherSuite[1]; new_cs[0] = CipherSuite.SSL_RSA_WITH_3DES_EDE_CBC_SHA;

SSLContext con = ssl.getContext(); //refresh the enabled cipher suites of this context con.setEnabledCipherSuites(new_cs); ssl.setContext(con);

//start renegotiation with client ssl.renegotiate(); }

System.out.println("send reply..."); // send data to client

pos = 0; addLine("HTTP/1.0 200 OK"); addLine("Content-Type: text/html"); addLine("Server: IAIK-SSL Testserver"); addLine(""); addLine("<HTML><HEAD>"); addLine("<META HTTP-EQUIV=\"Content-Type\"

CONTENT=\"text/html;CHARSET=iso-8859-1\">"); addLine("<TITLE>SSL Test</TITLE>"); addLine("</HEAD>"); addLine("<BODY>"); addLine("<H1>SSL Test ok.</H1>"); addLine("</BODY>"); addLine("</HTML>");

os.write(buffer, 0, pos); os.flush(); s.close();

} catch (UnknownHostException ex) { System.out.println("UnknownHostException: "+ex.getMessage()); } catch (SSLException ex) { System.out.println("SSLException: "+ex.getMessage());

Page 120: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLServer

120

} catch (IOException ex) { System.out.println("IOException: "+ex.getMessage()); } }

After closing the SSLSocket, the implementation of all intended tasks is completed andwe may take a look on the final version of our demo SSLServer:

import java.io.*;import java.net.*;import java.security.*;import java.math.BigInteger;import java.security.cert.X509Certificate;import javax.crypto.spec;

import iaik.security.ssl.*;import iaik.security.provider.iaik;import iaik.security.dsa.*;import iaik.security.dh.*;import iaik.security.rsa.*;import iaik.pkcs.*;import iaik.asn1.structures.Name;import iaik.asn1.*;import iaik.utils.KeyAndCertificate;import iaik.pkcs.pkcs8.EncryptedPrivateKeyInfo;

/** * Demo SSL server implementation. * * Waits for a SSL connection from a SSL browser and returns the * string: * "SSL Test ok.". */public class SSLServer {

static boolean renegotiate = false; //default: no renegotiation static int port = 4433;

static byte[] buffer = new byte[10000]; static int pos = 0; static byte[] crlf = {13, 10};

public static void addLine(String line) {

byte[] arr = line.getBytes(); int len = arr.length; System.arraycopy(arr, 0, buffer, pos, len); pos += len; System.arraycopy(crlf, 0, buffer, pos, 2); pos += 2; }

public static void main(String arg[]) throws IOException {

Page 121: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLServer

121

IAIK provider = new IAIK(); Security.addProvider(provider); SSLSocket ssl = null; SSLServerContext serverContext = new SSLServerContext();

try { // At this time we use this way of specifying the DH parameters // since not before JDK 1.2 a AlgorithmParameterGenerator will // be available BigInteger p = new BigInteger("da583c16d9852289d0e4af756f4cca92

dd4be533b804fb0fed94ef9c8a4403ed 574650d36999db29d776276ba2d3d412 e218f4dd1e084cf6d8003e7c4774e833" , 16);

BigInteger g = BigInteger.valueOf(2); DHParameterSpec dhparam = new DHParameterSpec(p, g); // set the DH parameter for ephemeral and anon cipher suites serverContext.setDHParameter(dhparam); // create certificates and private keys and set them to the // context: KeyAndCertificate kac; EncryptedPrivateKeyInfo epki; // set the RSA certificate/private key for RSA cipher suites kac = new KeyAndCertificate("certs/serverRSA1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("This is the passphrase!"); serverContext.setRSACertificate(kac.getCertificateChain(),

epki.getPrivateKey()); // set the DSA certificate/private key for DSA cipher suites kac = new KeyAndCertificate("certs/serverDSA1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("This is the passphrase!"); serverContext.setDSACertificate(kac.getCertificateChain(),

epki.getPrivateKey());

// set the DH certificate/private key for DH cipher suites kac = new KeyAndCertificate("certs/serverDH1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("This is the passphrase!"); serverContext.setDHCertificate(kac.getCertificateChain(),

epki.getPrivateKey());

// set the temporary RSA key pair for RSA_EXPORT cipher suites RSAPrivateKey tsk = new RSAPrivateKey(

new FileInputStream("certs/tempRSAPrivateKey.der")); PublicKey tpk = tsk.getPublicKey();

KeyPair tempKeyPair = new KeyPair(tpk, tsk); serverContext.setRSATempKeyPair(tempKeyPair);

} catch (InvalidKeyException ex) { System.out.println("InvalidKeyException: "+ex.getMessage()); System.exit(0); } catch (NoSuchAlgorithmException ex) { System.out.println("NoSuchAlgorithmException:"+ex.getMessage());

Page 122: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLServer

122

System.exit(0); } catch (GeneralSecurityException ex) { System.out.println("GeneralSecurityException:"+ex.getMessage()); System.exit(0); } catch (IOException ex) { System.out.println("IOException: "+ex.getMessage()); System.out.println("No server certs found!");

System.exit(0); }

// enable all possible cipher suites CipherSuite[] enabledCS = serverContext.updateCipherSuites();

// set a TrustDecider to check the certificates sent by clients SampleServerTrustDecider trustDecider =

new SampleServerTrustDecider(true); serverContext.setTrustDecider(trustDecider);

// specifiy the certification authorities to be accepted Name[] acceptedCAs = new Name[1];

Name verisign = new Name(); verisign.addRDN(ObjectID.country, "US"); verisign.addRDN(ObjectID.organization, "VeriSign, Inc."); verisign.addRDN(ObjectID.organizationalUnit,

"Class 1 Public Primary Certification Authority"); acceptedCAs[0] = verisign;

// specify the certificate types to be accepted byte[] types = new byte[4]; types[0] = ClientTrustDecider.rsa_sign; types[1] = ClientTrustDecider.dss_sign; types[2] = ClientTrustDecider.rsa_ephemeral_dh; types[3] = ClientTrustDecider.dss_ephemeral_dh; // inform the handshaker to send a certificate request message serverContext.setRequireClientCertificate(types, acceptedCAs);

System.out.println(serverContext);

System.out.println("listening on port "+port+"..."); SSLServerSocket server = new SSLServerSocket(port, serverContext);

while (true) { try {

ssl = (SSLSocket)server.accept(); // debug information to System.out

ssl.setDebugStream(System.out); OutputStream os = ssl.getOutputStream(); InputStream is = ssl.getInputStream();

//read in data sent from the client byte[] arr = new byte[300]; int l=-1; for (int i=0; i<10 && l<0; i++)

Page 123: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLServer

123

l = is.read(arr); System.out.println("client sends: "+l); for (int j=0; j<l; j++) System.out.print((char)arr[j]);

if (renegotiate) { //initially set to false System.out.println("renegotiating cipher suite..."); CipherSuite[] new_cs = new CipherSuite[1]; new_cs[0] = CipherSuite.SSL_RSA_WITH_3DES_EDE_CBC_SHA;

SSLContext con = ssl.getContext(); //refresh the enabled cipher suites of this context con.setEnabledCipherSuites(new_cs); ssl.setContext(con);

//start renegotiation with client ssl.renegotiate(); }

System.out.println("send reply..."); pos = 0; addLine("HTTP/1.0 200 OK"); addLine("Content-Type: text/html"); addLine("Server: IAIK-SSL Testserver"); addLine(""); addLine("<HTML><HEAD>"); addLine("<META HTTP-EQUIV=\"Content-Type\"

CONTENT=\"text/html;CHARSET=iso-8859-1\">"); addLine("<TITLE>SSL Test</TITLE>"); addLine("</HEAD>"); addLine("<BODY>"); addLine("<H1>SSL Test ok.</H1>"); addLine("</BODY>"); addLine("</HTML>");

os.write(buffer, 0, pos); os.flush(); s.close();

} catch (UnknownHostException ex) { System.out.println("UnknownHostException: "+ex.getMessage()); } catch (SSLException ex) { System.out.println("SSLException: "+ex.getMessage()); } catch (IOException ex) { System.out.println("IOException: "+ex.getMessage()); } } }}

When running the SSLServer we may get the following screen output reportingSSL security features of the server:

add Provider IAIK...

enabled cipher suites:

Page 124: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLServer

124

SSL_RSA_WITH_NULL_MD5 SSL_RSA_WITH_NULL_SHA SSL_RSA_EXPORT_WITH_RC4_40_MD5 SSL_RSA_WITH_RC4_MD5 SSL_RSA_WITH_RC4_SHA SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5 SSL_RSA_WITH_IDEA_CBC_SHA SSL_RSA_EXPORT_WITH_DES40_CBC_SHA SSL_RSA_WITH_DES_CBC_SHA SSL_RSA_WITH_3DES_EDE_CBC_SHA SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA SSL_DH_DSS_WITH_DES_CBC_SHA SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA SSL_DH_RSA_WITH_DES_CBC_SHA SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA SSL_DHE_DSS_WITH_DES_CBC_SHA SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA SSL_DHE_RSA_WITH_DES_CBC_SHA SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA SSL_DH_anon_EXPORT_WITH_RC4_40_MD5 SSL_DH_anon_WITH_RC4_MD5 SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA SSL_DH_anon_WITH_DES_CBC_SHA SSL_DH_anon_WITH_3DES_EDE_CBC_SHA

enabled compression methods: NULL

RSA certificate chain: C=AT, O=IAIK, CN=einstein, OU=RSA Server Certificate C=AT, O=TU Graz, OU=IAIK, CN=IAIK Test Certification AuthorityRSA private key: RSA Private Keytemporary rsa key pair: RSA Private Key

DSA certificate chain: C=AT, O=IAIK, CN=einstein, OU=DSA Server Certificate C=AT, O=TU Graz, OU=IAIK, CN=IAIK Test Certification AuthorityDSA private key: DSA

DH certificate chain: C=AT, O=IAIK, CN=einstein, OU=DH Server Certificate C=AT, O=TU Graz, OU=IAIK, CN=IAIK Test Certification AuthorityDH private key: DH Private Key

DH parameter: OK

require client certificate: yes

Page 125: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

iSaSiLk SSLServer

125

listening on port 4433...

When the server indicates to listen on port 4433 we can start a SSL supporting browser(f.i. Netscape Communicator 4.x or Microsoft Internet Explorer 4.x) and enter theURL: "https://<hostname>:4433". After accepting the certificate, the browser shall displaythe "SSL Test o.k." message:

Page 126: Copyright © 1997 -1999 Institute for Applied Information ...jce.iaik.tugraz.at/mailarchive/iaik-ssl/pdf00000.pdfCopyright © 1997 -1999 Institute for Applied Information Processing

126

References

[JCA] Sun Microsystems, Inc., "JavaTM Cryptography Architecture

API Specification & Reference" , December 1997

http://java.sun.com/products/JDK/1.1/docs/guide/security/CryptoSpec.html

[javaTut] M. Campione, K. Walrath, "The Java Tutorial", December 1997

http://java.sun.com/docs/books/tutorial/index.html

[SSL] A. Freier, P. Karlton and P. Kocher, "SSL 3.0 SPECIFICATION",

http://home.netscape.com/eng/ssl3/index.html, March 1996

[Schneier] Bruce Schneier, „Applied Cryptography - Second Edition“, Published by

John Wiley & Sons, Inc., 1996, ISBN 0-471-1709-9