Você está na página 1de 70

Secure Client - Server Communication through SSL

A PROJECT REPORT

Submitted by

M.Lakshmi Narayana,
G.Jayanthu Babu,
K.Rajesh Kumar.

in partial fulfillment for the award of the degree

of

BACHELOR OF TECHNOLOGY
IN

INFORMATION TECHNOLOGY

VELAGAPUDI RAMAKRISHNA SIDDHARTHA


ENGINEERING COLLEGE,
KANURU, VJA.

ACHARYA NAGARJUNA UNIVERSITY

APRIL-2007

1
DEPARTMENT OF INFORMATION TECHNOLOGY
V.R.SIDDHARTHA ENGINEERING COLLEGE
VIJAYAWADA

BONAFIDE CERTIFICATE

Certified that this project report “Secure Client – Server Communication

through SSL” is the bona fide work of

M.Lakshmi Narayana Y3 IT 025

G.Jayanth babu Y3 IT 062

K.Rajesh kumar Y1 IT 037

who carried out the project work under my supervision.

SIGNATURE SIGNATURE

JAYA LAKSHMI (lecturer) PROF. T LAKSHMI

PROJECT COORDINATOR HEAD OF THE DEPARTMENT

DEPARTMENTT OF DEPARTMENT OF
INFORMATION TECHNOLOGY INFORMATION TECHNOLOGY

V R SIDDHARTHA ENGINEERING V R SIDDHARTHA ENGINEERING


COLLEGE ,VJA COLLEGE,VJA

2
ACKNOWLEDGEMENTS

We take this opportunity to thank Prof, T. Lakshmi, Head of Department,


and Dept of Information Technology for her constant support and guidance
through timely suggestions.

We would also like to thank our project guide Mrs. Jaya Lakshmi,
lecturer, Department of Information Technology, for her support and
encouragement throughout the duration of the project. Her words of
encouragement motivated us to get along with the project.

We also thank all others who have helped us at various stages of this
project work.

Project Associates

3
Abstract:

Computer security has become one of the most important concerns in the
entire discipline of computing. The recent explosive growth of the Internet
and the World Wide Web has brought with it a need to protect sensitive
communications over the open networks.
In the past, security violations were generally done by Young adults, just for
fun. But as technology and usage of internet increased, there is always the
threat of planned attack (cyber terrorists), where the loss of money could be
large in billions.
So we have chosen this area of network security, and studied regarding VPN
(Virtual Private Networks) and SSL (Secure Socket Layer) protocol, the
current driving topics in the field of security.
In the recent past SSL protocol has revolutionized the area of VPN (Virtual
Private Network). SSL based VPN products allow users to establish secure
communication from virtually any Internet-connected web browser. It is
simpler and efficient than its predecessor (IPSec), in implementing a secure
remote access.
Security of client – server communication is achieved by achieving the
principles of security, like Authentication and Encryption. These techniques
are achieved using new packages of J2SDK, v 1.4, like JSSE and Key tool.
The rest of the Application code is developed using JAVA SWINGS.

4
APPENDIX 3

TABLE OF CONTENTS

CHAPTER NO. TITLE PAGE NO.

ABSTRACT iv

List of Figures vii

List of Tables viii

1. INTRODUCTION 1

1.1 Motivation: Virtual Private networks 1


1.2 Classification 2
1.2.1 Secure VPN’s 2
1.2.2 Trusted VPN’s 3
1.3 Architectures of VPN 3
1.4 Typical elements of VPN 4
1.5 Advantages of VPN 5
1.6 OSI Network Model 6
1.7 Important security protocols 7

2. Secure Socket Layer 10

2.1 Introduction 10
2.2 SSL in Tcp/Ip protocol stack 12
2.3 Establishing Secure Tunnels Using SSL 14
2.4 Goals of SSL. 15
2.5 SSL Architecture 16
2.6 SSL Hand Shake messages. 17
2.7 SSL Limitations 20

5
3. Java Secure Socket Extension 23

3.1 Programming with JSSE 24


3.1.1 JSSE debugging utilities 24
3.2 Key tool: Key management utility 25
3.2.1 Keystore Entries 26
3.2.2 Keystore Aliases 26
3.2.3 Keystore Location 27
3.2.4 Keystore Creation 28
3.2.5 Keystore Implementation 28
3.2.6 Supported Algorithms and Key Sizes 31

4. Implementation of Secure Client-Server Application. 32

4.1 Generating a Server key. 32


4.2 Programming Server Application with JSSE. 34
4.3 Exporting and Importing key. 39
4.4 Programming Client Application with JSSE. 41
4.5 Deploying Browser application with JAVA 45

Appendix A Basics of Tunneling Technology 53

Bibliography 59

6
List of Figures

Fig 1.1 VPN Architectures


Fig 1.2 VPN Technologies and the OSI Model

Fig 2.1 screen shot of SSL enabled webpage


Fig 2.2 SSL vs. IPSec
Fig 2.3 SECURE TUNNEL using SSL
Fig 2.4 SSL Architecture
Fig 2.5 SSL Handshake protocol - Messages
Fig 2.6 SSL Record protocol

Fig 3.1 JCA Architecture


Fig 3.2 Debugging options provided by JSSE

Fig 4.1 screen shot for generating a Server key


Fig 4.2 Compilation of Server code
Fig 4.3 Execution of Server code
Fig 4.4 Importing key
Fig 4.5 Compilation of Client code
Fig 4.6 Compilation of Browser code
Fig 4.7 Execution of Browser code
Fig 4.8 Screen shot of SSL enabled browser

7
List of Tables

Table 3.1 Various Key tool options

8
Chapter 1 “INTRODUCTION”

In this we would introduce you the topic of VPN ‘Virtual Private Network’,
the back bone of this project. This gave us motivation regarding secure
remote access, to learn it, deploy and find new implementations.

A Virtual Private Network is a private communications network usually used


within a company, or by several different companies or organizations, to
communicate over a public network.
VPN has attracted the attention of many organizations looking to both
expand their networking capabilities and reduce their costs.
A study of VPN involves many interesting aspects of network protocol
design, Internet security, network service outsourcing, and technology
standards.
Virtual private network technology is based on the idea of tunneling. VPN
tunneling involves establishing and maintaining a logical network
connection (that may contain intermediate hops). On this connection,
packets constructed in a specific VPN protocol format are encapsulated
within some other base or carrier protocol, then transmitted between VPN
client and server, and finally de-encapsulated on the receiving side.
Each packet is encapsulated can provide:
Confidentiality, Integrity, Authenticity, Non-repudiation.
Obviously these are the four basic properties of Information Security. For
example in a military environment, the most important security property is
probably confidentiality. In a bank, confidentiality is important, too, but
even more important is the integrity of the data. Integrity confines that data
has not been modified in the path of communication.

9
Authenticating is just confirming that the sender is reliable and trustworthy.
And finally non-repudiation means that it can be verified that the sender and
the recipient were, in fact, the parties who claimed to send or receive the
message, respectively. In short, non-repudiation of origin proves that data
has been sent, and non-repudiation of delivery proves it has been received.

Classification:
The Virtual private networks can be classified into two main categories as
follows: Secure and Trusted.
Secure VPNs use cryptographic tunneling protocols to provide the
necessary confidentiality (preventing snooping), sender authentication
(preventing identity spoofing), and message integrity (preventing message
alteration) to achieve the privacy intended. When properly chosen,
implemented, and used, such techniques can provide secure communications
over unsecured networks. Because such choice, implementation, and use are
not trivial, there are many insecure VPN schemes on the market. Secure
VPN technologies may also be used to enhance security as a 'security
overlay' within dedicated networking infrastructures.
Secure VPN protocols include the following:
* IPSec (IP security), an obligatory part of IPv6.
* SSL used either for tunneling the entire network stack, such as in
OpenVPN, or for securing what is essentially a web proxy. Although the
latter is often called a "SSL VPN" by VPN vendors, it is not really a fully-
fledged VPN.
* PPTP (point-to-point tunneling protocol), developed jointly by a number
of companies, including Microsoft.

10
Some large ISPs now offer "managed" VPN service for business customers
who want the security and convenience of a VPN but prefer not to undertake
administering a VPN server themselves. In addition to providing remote
workers with secure access to their employer's internal network, sometimes
other security and management services are included as part of the package,
such as keeping anti-virus and anti-spyware programs updated on each
client's computer.

Trusted VPNs do not use cryptographic tunneling, and instead rely on the
security of a single provider's network to protect the traffic. Multi-protocol
label switching (MPLS) is commonly used to build trusted VPNs. Other
protocols for trusted VPNs include:
* L2F (Layer 2 Forwarding), developed by Cisco.
* L2TP (Layer 2 Tunneling Protocol), including work by both Microsoft and
Cisco.
* L2TPv3 (Layer 2 Tunneling Protocol version 3).

VPN Architectures:
• Intranet VPN: VPN is used to make connection among
fixed locations such as branch offices. This kind of LAN-
to-LAN VPN connection joins multiple remote locations
into a single private network.
• Extranet VPN: VPN is used to connect business partners
such as suppliers and customers. This kind of VPN
allows various parties to work in a shared environment.

11
• Remote Access VPN: This is a user-to-network
connection for the home user and mobile user
connecting to corporate private network from various
remote locations. This kind of VPN permits secure,
encrypted connections between a corporate private
network and remote users.

Employees
Intranet
Applications
Web
Email Extranet
Database Partners
Mainframe
E-Commerce (Remote
Access)
Citizens

Fig 1.1 VPN architectures

Typical Elements of a VPN connection:


• VPN server: A computer accepts VPN connections from VPN
clients. A VPN server can provide a remote access VPN connection
or a gateway-to-gateway VPN connection.
• VPN client: A computer initiates a VPN connection to a VPN server.
A VPN client can be a remote computer obtaining a remote access
VPN connection or a router obtaining a gateway-to-gateway VPN
connection.
• VPN tunnel: The portion of the connection in which data is
encapsulated and encrypted.
• Tunneling protocols: The communication standards used to manage
tunnels and encapsulate data.

12
• Tunneled data: Data that is encapsulated and encrypted, and sent
across a private link.
• Transit network: The shared or public network such as a private
intranet or the Internet where the encapsulated data passes through it.

Advantages of Using VPN:


Listed below are some benefits provided by VPN:
• Extend geographic connectivity: VPNs employ the Internet for inter -
connectivity between remote parts of an intranet. Because the Internet
is accessible globally, even the most far flung branch offices, users,
and mobile users (such as salesmen) can easily connect to the
corporate intranet.
• Improve security for remote user and network connection: Because
VPNs use the tunneling technology to transmit data across
"unsecured" public networks; data transactions are secure to an extent.
In addition to the tunneling technology, VPNs use extensive security
measures, such as encryption, authentication, and authorization to
ensure the safety, confidentiality, and integrity of the data transmitted.
As a result, VPNs offer a considerably high degree of transaction
security.
• Reduce Implementation and operational costs: VPNs cost
considerably less than the traditional solutions, which are based on
leased lines, Frame Relay, ATM, or ISDN. This is because VPNs
eliminate the need for long-distance connections by replacing them
with local connections to a carrier network. By reducing the long-
distance telecommunication costs, VPNs also bring down WAN-based
network operation costs a considerable extent, the reason behind the

13
lowered cost of operation is explained by the fact that the organization
does not need to employ as many trained and expensive networking
personnel as it would if the VPN were managed by the organization
itself.
• Provide broadband networking compatibility: In the case of Internet
connectivity based on leased lines, the bandwidth is entirely wasted in
the absence of an active Internet connection. VPNs, on the other hand,
create logical tunnels to transmit data as and when required. As a
result, the network bandwidth is used only when there is an active
Internet connection. Therefore, there is considerably less chance of
available network bandwidth waste.
• Reduce time and transportation costs for remote users
• Improve productivity since resources can be accessed from remote
networks.
• Simplify network topology in certain scenarios.
• Provide global networking opportunities.
• Provide telecommuter support.
• Provide faster ROI (return on investment) than traditional
leased/owned WAN lines: Show a good economy of scale.

OSI Network Model:


In 1984, Open Systems Interconnect, a group dedicated to providing
international standards, released an abstract framework for classifying
technologies involved in inter-computer communications. It consists of
seven layers (or levels) and their corresponding VPN technologies are
shown in the following figure.

14
Historically, VPN tunneling was typically performed at the Network Layer
or lower (e.g., IPSec, which operates at the Network Layer). SSL VPNs
work differently. They establish connectivity using SSL, which functions at
Levels 4-5. They also encapsulate information at Levels 6-7 and
communicate at the highest levels in the OSI model. Today, some SSL

Figure 1-2. VPN Technologies and the OSI Model

VPNs are also able to tunnel network level information over SSL, making
SSL the most versatile remote access VPN technology available.

Important Security protocols:


There are two main trusted and widely used protocols in the implementation
of these VPNs: IPSec and SSL, as mentioned above both come into category
of Secure VPNs

15
“Internet Protocol Security” Protocol (IPSec) provides enhanced security
features such as better encryption algorithms and more comprehensive
authentication. IPSec has two encryption modes: tunnel and transport.

IPSec uses three main protocols:


• IP Authentication Header (AH), IP protocol 51, provides
authentication of the origin of the data, ensures data integrity, and
protects against replay.
• IP Encapsulating Security Payload (ESP), IP protocol 50, protects data
from viewing by third parties, and provides the same features as AH.
• The Internet Security Association and Key Management Protocol
(ISAKMP) is a protocol framework that defines payload formats, the
mechanics of implementing a key exchange protocol, and the
negotiation of a security association.

IPSec can be used in two modes: Tunnel encrypts the header and the payload
of each packet while transport only encrypts the payload.
• Transport mode is normally used between the end points of a
connection - for example, to establish a secure connection such as a
VPN between a client device and a server.
• Tunnel mode is normally used between two systems where one or
both of them are not the endpoint of the connection. For example, to
communicate between a firewall and a VPN server on a LAN, or
between a remote dial-in system and an edge device such as a router
or gateway, you might use tunnel mode (or IPSec tunneling).
Tunnel mode and transport mode are implemented in different ways. In
transport mode, the IP header of a packet is modified, and has a trailing

16
IPSec header added to it. In tunnel mode, the entire packet is wrapped with a
new IP header that has a trailing IPSec header attached to it.

“Secure Sockets Layer” (SSL) protocol, on the other hand, is the standard
security technology for establishing an encrypted link between a web server
and a browser. This link ensures that all data passed between the web server
and browsers remain private and integral. SSL is an industry standard and is
used by millions of websites in the protection of their online transactions
with their customers.
Let us review in deep, regarding this SSL in the next chapter.

17
Chapter 2 “Secure Socket Layer”

“Secure Sockets Layer” protocol is the standard security technology for


establishing an encrypted link between a web server and a browser. This was
developed by Netscape in 1994, which allows clients (Web browsers,
typically) and HTTP servers to communicate over a secure connection. This
link ensures that all data passed between the web server and browsers
remain private and integral. SSL is an industry standard and is used by
millions of websites in the protection of their online transactions with their
customers.
SSL VPN products allow users to establish secure remote access sessions
from virtually any Internet-connected web browser.
There are several versions of SSL: SSL 1.0 was introduced in the Mosaic
browser in 1994, SSL 2.0 has security weaknesses and is hardly used today;
SSL 3.0 is universally supported; and finally the Transport Layer Security
(TLS), which is an improvement on SSL 3.0, has been adopted as an Internet
standard and is supported by almost all recent software.
In 1996, as the relevance of the World-Wide Web as a respectable
mainstream business channel and communications mechanism became
assured, and as SSL emerged as an effectively unchallenged de facto
standard, the Internet Engineering Task Force (IETF) began formal
standardization of the SSL protocol. In 1999, it completed its work and
established SSL as the official standard for secure Web communications
under the name Transport Layer Security (TLS).
SSL/TLS is the most widely deployed security protocol in the world
[Res01]. As such, it has undergone extensive scrutiny and has yet to be
degraded by any known weakness. This does not mean it is guaranteed

18
secure for the future, but it does mean that many of the brightest minds in
cryptography and mathematics have been unable to find any holes in its
cryptographic armor. In the past, SSL/TLS was a general protocol that would
be tightly coupled with specific applications, thus the extreme confusion
about what an SSL VPN really is. It would be used to secure session
communication between two hosts using a single application or protocol at a
time. The most well known use of SSL is in the HTTPS protocol to enable
secure web-based ecommerce. SSL is the default security solution for
application to application needs, but it has never been implemented to
handle arbitrary multiple protocols at the same time, until now.
SSL encrypted pages had the prefix HTTPS whereas non-encrypted pages
used a prefix of HTTP. Today in addition to the change in the URL, most
browsers display some icon indicating that the session is encrypted—a lock,
a key, etc.
HTTPS is the web protocol that utilizes SSL to encrypt HTTP, and is used
worldwide today for secure web communications. HTTPS should not be
confused with S-HTTP, an alternative method for encrypting web
communications. S-HTTP competed with HTTPS in the early days of secure
web sessions, but was generally considered inferior to HTTPS for e-
commerce use (as it did not encrypt some session information), and is no
longer used. S-HTTP is an extension to the HTTP protocol used to support
sending data securely over the World Wide Web. S-HTTP is designed to
send individual messages securely where as SSL is designed to establish a
secure connection between two computers.

19
FIG 2.1 SCREEN SHOT OF SSL ENABLED WEBPAGE

Today, servers typically provide regular web service HTTP on port 80, and
SSLencrypted web traffic HTTPS over port 443. Overleaf is an HTTPS
encrypted web page. Note the https at the start of the URL and the lock icon
near the bottom right of the screenshot:

SSL in TCP/IP Protocol Stack:


As the name Secure Sockets Layer indicates, SSL connections act like
sockets connected by TCP. Therefore, you can think of SSL connections as
secure TCP connections since the place for SSL in the protocol stack is right
above TCP and below the application layer as shown in Figure 1. It is
important to note, however, that SSL doesn't support some of the TCP
features such as out-of-band data.

20
TCP/IP
Protocol Model

Application
SSL / TLS
(RFC 2246) Transport
Between Application
and Transport Layer
Network IPsec
Over Network Layer
Link Layer

Fig 2.2 “SSL vs. IPSec”

Among the features of SSL that have made it the de facto standard vehicle
for secure e-commerce transactions is its support for negotiable encryption
and authentication algorithms. The designers of SSL realized that not all
parties will use the same client software and consequently not all clients will
include any particular encryption algorithm. The same is true for servers.
The client and server at the two ends of a connection negotiate the
encryption and decryption algorithms (cipher suites) during their initial
handshake. It may turn out that they do not have sufficient algorithms in
common, in which case the connection attempt will fail.
Security’s worst enemy is complexity and SSL VPN defeats this enemy.
Note that while SSL allows both the client and the server to authenticate
each other, typically only the server is authenticated in the SSL layer. Clients
are customarily authenticated in the application layer, through the use of
passwords sent over an SSL-protected channel. This pattern is common in
banking, stock trading, and other secure Web applications.
Compared to IPSec VPNs, SSL VPNs provide:
• Clientless Access,

21
• Compatibility with any Remote Access situation,
• More Security, with granular access control,
• More control for IT,
• Easier management, with lower total cost of ownership.
• Provide faster ROI (return on investment) than other protocols: Return
of Investment is your annual benefit divided by your investment
amount. By replacing your IPSec VPN with SSL VPN, you will see
bottom line benefits in the areas of operations, security productivity,
and business partner collaboration. Statistics show that by upgrading
only 1000 IPSec VPN users to SSL, over three years you could expect
operational benefits of $115,200 and productivity benefits of
$3,600,000, by extending it to 1000of your business partners over an
extranet, you could also add additional collaborative benefits of
$300,000, resulting in cumulative benefits of $4,015,200.
Clientless SSL VPN solutions are easier, cheaper, and faster to deploy than
IPSec VPNs, because there is no difficult-to-configure, difficult-to-manage,
and difficult-to-support components.

Establishing Secure Tunnels Using SSL:


Now that we understand what SSL is and how it works, let us discuss how
SSL allows us to create tunnels.
A secure tunnel between computers can best be understood as a secure
channel of communication between two machines that have an insecure
environment between them. The communications tunnel is like a tunnel
under a river that allows automobiles to travel from point A on one side of

22
the river to point B on the other side and prevents environmental elements
like water from interfering with the traffic as shown in the diagram below.
The communications tunnel allows communications between
two computers over public networks securely so that other
computers on those networks
cannot access the communications between the two
machines.

FIG 2.3 SECURE TUNNEL using SSL

However, unlike the example of the tunnel under the river,


network tunneling does not employ a physical barrier
between the two computers communicating and other
machines. Rather, computer-related tunneling involves
encrypting all communications between the two computers
so that even if another computer were to receive the
communications, it would not be able to decipher the
contents of the actual message between the machines
SSL VPNs create secure tunnels by achieving or
implementing its goals.

Goals of SSL:

23
Encryption protects data from unauthorized use by converting it to an
apparently meaningless form before transmission. The data is encrypted by
one side (the client or the server), transmitted, decrypted by the other side,
and then processed.

Source Authentication is a method of verifying the data sender's identity.


The first time a browser or other client attempts to communicate with a Web
server over a secure connection, the server presents the client with a set of
credentials in the form of a certificate. Certificates are issued and validated
by trusted authorities known as certification authorities (CAs). A certificate
represents the public-key identity of a person. It is a signed document that
says: I certify that the public key in this document belongs to the entity
named in this document. Signed (certificate authority). Well-known CAs
include VeriSign, Entrust, and Thawte. Note that the certificates used with
SSL/TLS today are X.509 certificates.

Data integrity refers to means of ensuring that data has not been modified
in transit. Besides protecting data through encryption, SSL uses hashing to
ensure that the contents of a communications session are not modified
between the time one computer sends a message and the time the recipient
reads it. It offers encryption, source authentication, and data integrity as
means to protect information exchanged over insecure, public networks.
Basic understanding of SSL will help us understand the workings of SSL
VPNs, so let us look in to the Architecture of SSL protocol.

SSL Architecture:

24
This consists of three major sub protocols namely: Handshake protocol,
Record protocol, and Alert protocols.
• Handshake: This mechanism is called Session creation, and allows
client and server authentication.
• Record protocol : This provides Confidentiality and Message
Integrity.

Handshake Change Alert


Protocol cipher spec Protocol

Record protocol

Fig 2.3 SSL Architecture

• Alert protocol : use to report errors


The Change Cipher Spec sub-protocol is used to change the keying material
used for encryption between the client and server. It consists of a single
message to tell other party in the SSL/TLS session, who is also known is the
peer, that the sender wants to change to a new set of keys. The key is
computed from the information exchanged by the Handshake protocol.

Before data can be sent across an SSL connection, the two ends must
negotiate and exchange key information. We won't go into much detail about
the handshake protocol here, because it isn't necessary for our purposes. The
SSL full handshake protocol is illustrated in the next figure. It shows the
sequences of messages exchanged during the SSL handshake.

SSL hand Shake messages: These messages individually explained as


follows,

25
• ClientHello: The client sends the server information such as SSL
protocol version, session id, and cipher suites information such
cryptographic algorithms and key sizes supported.
• ServerHello: The server chooses the best cipher suite that both the
client and server support and sends this information to the client.
• Certificate: The server sends the client its certificate which contains
the server's public key. While this message is optional, it is used when
server authentication is required. In other words, it is used to confirm
the server's identity to the client.
• Certificate Request: This message is sent only if the server requires
the client to authenticate itself. Most e-commerce applications do not
require the client to authenticate itself.
• Server Key Exchange: This message is sent if the certificate, which
contains the server's public key, is not sufficient for key exchange.
• ServerHelloDone: This message informs the client that the server
finished the initial negotiation process.
• Certificate: This message is sent only if the server requested the client
to authenticate itself.

26
Fig 2.2 “SSL Messages”

• Client Key Exchange: The client generates a secret key to be shared


between the client and server. If the Rivest-Shamir-Adelman (RSA)
encryption algorithm is used, the client encrypts the key using the
server's public key and sends it to the server. The server uses its
private or secret key to decrypt the message and retrieves the shared
secret key. Now, client and server share a secret key that has been
distributed securely.
• Certificate Verify: If the server requested to authenticate the client,
this message allows the server to complete the authentication process.
• Change Cipher Spec: The client asks the server to change to encrypted
mode.

27
• Finished: The client tells the server it is ready for secure
communication.
• Change Cipher Spec: The server asks the client to change to encrypted
mode.
• Finished: The server tells the client it is ready for secure
communication. This marks the end of the SSL handshake.
• Encrypted Data: The client and server can now start exchanging
encrypted messages over a secure communication channel.

The Alert sub-protocol is used to report errors like:


• Unexpected message
• Bad record MAC
• Decompression failure
• Handshake failure
• Illegal parameters
• To notify closure of connection
• To notify absence of certificate
• To notify that a bad or unknown certificate
• To notify that a certificate is expired.

The Record sub-protocol provides Confidentiality and Message Integrity.


This is explained with neat diagram.

28
Fig 2.6 SSL Record protocol

The Change Cipher Spec sub-protocol is used to change the keying material
used for encryption between the client and server. It consists of a single
message to tell other party in the SSL/TLS session, who is also known, is the
peer that the sender wants to change to a new set of keys. The key is
computed from the information exchanged by the Handshake protocol.

SSL Limitations

The SSL protocol, like any other technology has its limitations. And because
SSL provides security services, it is it is especially important to understand
its limits. After all, a false sense of security may be worse than no security.
The limitations of SSL fall generally into three categories. First are
fundamental constraints of SSL. These are consequences of the design of
SSL. The SSL protocol also inherits some weaknesses from the tools it uses,
namely encryption and signature algorithms. If these algorithms have
weaknesses, SSL generally cannot rehabilitate them. Finally the
environments in which SSL is deployed have their own shortcomings and
limitations, some of which SSL is helpless to address.
Fundamental Protocol Limitations

29
Though its design includes considerations for many different applications,
SSL is definitely focused on securing Web transactions. For example, SSL
requires a reliable transport protocol such as TCP. That is a completely
reasonable requirement in the world of web transactions, because the HTTP
itself requires TCP. The decision means, that SSL cannot operate using a
connectionless transport protocol like UDP (User DataGram Protocol).
Another role that SSL fails to fill is support for a particular security service
known as non- repudiation. Non- repudiation associates the digital
equivalent of a signature with data;
Tool Limitations
The secure socket layer is simply a communication protocol, and any SSL
implementation will rely on other components for many functions, including
the cryptographic algorithms. These algorithms are the mathematical tools
that actually perform tasks such as encryption and decryption, no SSL
implementation can be any stronger than the cryptographic tools on which it
is based.
Some common cryptographic algorithms, however, have been successfully
attacked. So in general, SSL implementations must consider not only the
security of SSL, but also that of the cryptographic services on which it is
built.
Environmental Limitations
A network protocol alone can only provide security for information as it
transits a network. No network protocol protects data before it is sent or after
it arrives at its destination.
Security in any computer network, whether the public network or private
facilities, is a function of all the elements that make up that network. It

30
depends on the network security protocol, the computer systems that use and
the human beings who use those.
These SSL protocol is a strong and effective security tool, but it is only a
single tool. True security requires many such tools, and a comprehensive
plan to employ them.

Chapter 3 “Java Secure Socket Extension”

The Java Secure Socket Extension (JSSE) provides a framework and a 100%
Pure Java implementation of the SSL and TLS protocols. It provides
mechanisms for data encryption, server authentication, message integrity,
and optional client authentication.
What is fascinating about JSSE is that is abstracts the complex underlying
cryptographic algorithms and thus minimizes the risk of creating subtle and

31
dangerous security vulnerabilities. In addition, it makes the development of
secure applications quite simple by allowing you to seamlessly integrate SSL
into your applications. The JSSE framework is capable of supporting many
different secure communication protocols such as SSL 2.0, 3.0 and TLS 1.0.
The Java platform's security and encryption features have grown
tremendously over the last few years. The JDK 1.4 (a.k.a. Merlin) release
now comes bundled with many security-related packages, including the Java
Cryptography Extension (JCE), the Java Secure Socket Extension (JSSE),
and the Java Authentication and Authorization Service (JAAS). All of these
components are pieces of the Java Cryptography Architecture (JCA), as
illustrated in the figure below:

JCA

JAAS JCE JSSE

Fig 3.1 JCA Architecture


Programming with JSSE
The JSSE APIs supplement the java.security and java.net packages by
providing extended networking socket classes, trust and key managers, and a
socket factory framework for encapsulating socket creation behavior. These
classes are included in the packages javax.net and javax.net.ssl.
JSSE Debugging Utility
Sun's JSSE implementation provides dynamic debug tracing support that can
be accessed using the system property javax.net.debug. This utility, which is
not an officially supported feature of JSSE, allows you to see what goes on

32
behind the scenes during the SSL communications. This utility can be used
from the command line as follows:
Prompt> java -Djavax.net.debug=option[debugSpecifiers] MySSLApp
If you use the help option, it will display a list of the debug options. The
current options in J2SE 1.4.1 are:

Fig 3.2 Debugging options provided by JSSE

You must specify the option ssl or all, optionally followed by debug
specifiers. One or more debug specifiers can be used, and a separator such as
":" or "," is not needed but can help with readability. Here are some
examples:
Prompt> java -Djavax.net.debug=all MyApp
Prompt> java -Djavax.net.debug=ssl MyApp
Prompt> java -Djavax.net.debug=ssl:handshake:trustmanager MyApp

Key tool
key tool is a key and certificate management utility. It enables users to
administer their own public/private key pairs and associated certificates for

33
use in self-authentication (where the user authenticates himself/herself to
other users/services) or data integrity and authentication services, using
digital signatures. It also allows users to cache the public keys (in the form
of certificates) of their communicating peers.
key tool stores the keys and certificates in a so-called keystore. The default
Keystore implementation implements the Keystore as a file. It protects
private keys with a password.
The jarsigner tool uses information from a keystore to generate or verify
digital signatures for Java ARchive (JAR) files. (A JAR file packages class
files, images, sounds, and/or other digital data in a single file). Jarsigner
verifies the digital signature of a JAR file, using the certificate that comes
with it (it is included in the signature block file of the JAR file), and then
checks whether or not the public key of that certificate is "trusted", i.e., is
contained in the specified keystore.
Please note: the key tool and jarsigner tools completely replace the java key
tool provided in JDK 1.1. These new tools provide more features than java
key, including the ability to protect the keystore and private keys with
passwords, and the ability to verify signatures in addition to generating
them. The new keystore architecture replaces the identity database that java
key created and managed. It is possible to import the information from an
identity database into a keystore, via the
-identitydb key tool command.

Keystore Entries
There are two different types of entries in a keystore:
key entries - each holds very sensitive cryptographic key information, which
is stored in a protected format to prevent unauthorized access. Typically, a

34
key stored in this type of entry is a secret key, or a private key accompanied
by the certificate "chain" for the corresponding public key. The keytool and
jarsigner tools only handle the latter type of entry that is private keys and
their associated certificate chains.
trusted certificate entries - each contains a single public key certificate
belonging to another party. It is called a "trusted certificate" because the
keystore owner trusts that the public key in the certificate indeed belongs to
the identity identified by the "subject" (owner) of the certificate. The issuer
of the certificate vouches for this, by signing the certificate.

Keystore Aliases
All keystore entries (key and trusted certificate entries) are accessed via
unique aliases. Aliases are case-insensitive; the aliases Hugo and hugo
would refer to the same keystore entry.
An alias is specified when you add an entity to the keystore using the
-genkey command to generate a key pair (public and private key) or the
-import command to add a certificate or certificate chain to the list of trusted
certificates. Subsequent keytool commands must use this same alias to refer
to the entity.
For example, suppose you use the alias duke to generate a new
public/private key pair and wrap the public key into a self-signed certificate
(see Certificate Chains) via the following command:
keytool -genkey -alias duke -keypass dukekeypasswd
This specifies an inital password of "dukekeypasswd" required by
subsequent commands to access the private key associated with the alias
duke. If you later want to change duke's private key password, you use a
command like the following:

35
keytool -keypasswd -alias duke -keypass dukekeypasswd -new newpass
This changes the password from "dukekeypasswd" to "newpass".
Please note: A password should not actually be specified on a command line
or in a script unless it is for testing purposes, or you are on a secure system.
If you don't specify a required password option on a command line, you will
be prompted for it. When typing in a password at the password prompt, the
password is currently echoed (displayed exactly as typed), so be careful not
to type it in front of anyone.

Keystore Location
Each keytool command has a -keystore option for specifying the name and
location of the persistent keystore file for the keystore managed by keytool.
The keystore is by default stored in a file named .keystore in the user's home
directory, as determined by the "user.home" system property. Given user
name uName, the "user.home" property value defaults to
C:\Winnt\Profiles\uName on multi-user Windows NT systems
C:\Windows\Profiles\uName on multi-user Windows 95 systems
C:\Windows on single-user Windows 95 systems
Thus, if the user name is "narayan", "user.home" defaults to
C:\Winnt\Profiles\narayan on multi-user Windows NT systems
C:\Windows\Profiles\narayan on multi-user Windows 95 systems

Keystore Creation
A keystore is created whenever you use a -genkey, -import, or -identitydb
command to add data to a keystore that doesn't yet exist.
More specifically, if you specify, in the -keystore option, a keystore that
doesn't yet exist, that keystore will be created.

36
If you don't specify a -keystore option, the default keystore is a file named
.keystore in your home directory. If that file does not yet exist, it will be
created.

Keystore Implementation
The KeyStore class provided in the java.security package supplies well-
defined interfaces to access and modify the information in a keystore. It is
possible for there to be multiple different concrete implementations, where
each implementation is that for a particular type of keystore.
Currently, two command-line tools (keytool and jarsigner) and a GUI-based
tool named ‘Policy Tool’ make use of keystore implementations. Since
KeyStore is publicly available, JDK users can write additional security
applications that use it.
There is a built-in default implementation, provided by Sun Microsystems. It
implements the keystore as a file, utilizing a proprietary keystore type
(format) named "JKS". It protects each private key with its individual
password, and also protects the integrity of the entire keystore with a
(possibly different) password.
Keystore implementations are provider-based. More specifically, the
application interfaces supplied by KeyStore are implemented in terms of a
"Service Provider Interface" (SPI). That is, there is a corresponding abstract
KeystoreSpi class, also in the java.security package, which defines the
Service Provider Interface methods that "providers" must implement. (The
term "provider" refers to a package or a set of packages that supply a
concrete implementation of a subset of services that can be accessed by the
Java Security API.) Thus, to provide a keystore implementation, clients must
implement a "provider" and supply a KeystoreSpi subclass implementation,

37
as described in How to Implement a Provider for the Java Cryptography
Architecture.

Applications can choose different types of keystore implementations from


different providers, using the "getInstance" factory method supplied in the
KeyStore class. A keystore type defines the storage and data format of the
keystore information, and the algorithms used to protect private keys in the
keystore and the integrity of the keystore itself. Keystore implementations of
different types are not compatible.
keytool works on any file-based keystore implementation. (It treats the
keytore location that is passed to it at the command line as a filename and
converts it to a FileInputStream, from which it loads the keystore
information.) The jarsigner and policytool tools, on the other hand, can read
a keystore from any location that can be specified using a URL.
For keytool and jarsigner, you can specify a keystore type at the command
line, via the -storetype option. For Policy Tool, you can specify a keystore
type via the "Change Keystore" command in the Edit menu.
If you don't explicitly specify a keystore type, the tools choose a keystore
implementation based simply on the value of the keystore.type property
specified in the security properties file. The security properties file is called
java.security, and it resides in the JDK security properties directory,
java.home\lib\security, where java.home is the runtime environment's
directory (the jre directory in the SDK or the top-level directory of the Java
2 Runtime Environment).
Each tool gets the keystore.type value and then examines all the currently-
installed providers until it finds one that implements keystore of that type. It
then uses the keystore implementation from that provider.

38
The KeyStore class defines a static method named getDefaultType that lets
applications and applets retrieve the value of the keystore.type property. The
following line of code creates an instance of the default keystore type (as
specified in the keystore.type property):
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
The default keystore type is "jks" (the proprietary type of the keystore
implementation provided by Sun). This is specified by the following line in
the security properties file:
keystore.type=jks
To have the tools utilize a keystore implementation other than the default,
you can change that line to specify a different keystore type.
For example, if you have a provider package that supplies a keystore
implementation for a keystore type called "pkcs12", change the line to
keystore.type=pkcs12
Note: case doesn't matter in keystore type designations. For example, "JKS"
would be considered the same as "jks".

Supported Algorithms and Key Sizes


keytool allows users to specify any key pair generation and signature
algorithm supplied by any of the registered cryptographic service providers.
That is, the keyalg and sigalg options for various commands must be
supported by a provider implementation. The default key pair generation
algorithm is "DSA". The signature algorithm is derived from the algorithm
of the underlying private key: If the underlying private key is of type
"DSA", the default signature algorithm is "SHA1withDSA", and if the
underlying private key is of type "RSA", the default signature algorithm is
"MD5withRSA".

39
When generating a DSA key pair, the key size must be in the range from 512
to 1024 bits, and must be a multiple of 64. The default key size for any
algorithm is 1024 bits. The table that follows explains each option in the
command.

Table 3.1 Various Keytool options

Chapter 4 “Implementation of Secure Client-Server Application”

Generating a Server Key


As I mentioned earlier, SSL uses certificates for authentication. Certificates
must be created for clients and servers that need to communicate securely
using SSL. JSSE uses certificates created using the Java keytool shipped
with J2SE. I used the following command to create an RSA certificate for
the HTTP server.
prompt> keytool -genkey -keystore serverkeys -keyalg rsa -alias qusay
This command will generate a certificate referenced by the alias qusay, and
will be stored in a file named serverkeys. The tool prompted me for
information to generate the certificate. The information I entered is
highlighted in bold: Enter keystore password: hellothere

40
What is your first and last name?
[Unknown]: vrsiddhartha
What is the name of your organizational unit?
[Unknown]: itdepartment
What is the name of your organization?
[Unknown]: students
What is the name of your City or Locality?
[Unknown]: vijayawada
What is the name of your State or Province?
[Unknown]: ap
What is the two-letter country code for this unit?
[Unknown]: in
Is CN=vrsiddhartha, OU=itdepartment,
O=students, L=vijayawada, ST=ap, C=in correct?
[yes/no]: yes <enter>
Enter key password for <qusay>
(RETURN if same as keystore password): hiagain

41
Fig 4.1 screen shot for generating a Server key
As you can see, the keytool prompted me to enter a password for the
keystore meaning that in order for the server to access the keystore it must
know that password. Also, the tool asked me to enter a password for the
alias. If you like, such password information can be related on the keytool
command line using the options -storepass and -keypass. Note that I used the
name "ultra.domain.com" for the first and last name. This name is the
hypothetical name of my machine. You should enter the hostname or the IP
address of the server's machine.
When you run the keytool command, it may take a few seconds to generate
the certificate depending on the speed of your machine.
Once a certificate for my server has been generated, I can revise my
HttpServer to make it secure. If you examine the HttpServer class, you'll
notice that the getServer method is used to return a server socket. This
means, the only method I need to modify is the getServer method so that it
returns a secure server socket. The changes are highlighted in bold in Code
Sample 2. Notice that I have changed the port number to 443. This is the

42
default port number for HTTPs. It is important to note that port numbers
between 0 and 1023 are reserved. If you run HttpsServer on a different port
number, the url should be: https://localhost:portnumber but if you run it on
443 then the URL is: https://localhost.

Programming Server Application with JSSE


HttpsServer.java

import java.io.*;
import java.net.*;
import javax.net.*;
import javax.net.ssl.*;
import java.security.*;
import java.util.StringTokenizer;

/**
* This class implements a multithreaded simple HTTPS server that supports
the GET
* request method. It listens on port 443, waits client requests and serves
documents.
*/

public class HttpsServer {

String keystore = "serverkeys";


char keystorepass[] = "hellothere".toCharArray();
char keypassword[] = "hiagain".toCharArray();

public static final int HTTPS_PORT = 443;

public ServerSocket getServer() throws Exception {

KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(keystore), keystorepass);
KeyManagerFactory kmf = eyManagerFactory.getInstance("SunX509");

43
kmf.init(ks, keypassword);
SSLContext sslcontext = SSLContext.getInstance("SSLv3");
sslcontext.init (kmf.getKeyManagers(), null, null);
ServerSocketFactory ssf =sslcontext.getServerSocketFactory();
SSLServerSocket serversocket = (SSLServerSocket)
ssf.createServerSocket(HTTPS_PORT);
return serversocket;
}

// multi-threading -- create a new connection for each request

public void run() {


ServerSocket listen;
try {
listen = getServer();
while(true) {
Socket client = listen.accept();
ProcessConnection cc = new
ProcessConnection(client);
}
} catch(Exception e) {
System.out.println("Exception: "+e.getMessage());
}
}

// main program
public static void main(String argv[]) throws Exception {
HttpsServer https = new HttpsServer();
https.run();
}
}

class ProcessConnection extends Thread {


Socket client;
BufferedReader is;
DataOutputStream os;

44
public ProcessConnection(Socket s) {
client = s;
try {
is = new BufferedReader(new InputStreamReader client.getInputStream()));
os = new DataOutputStream(client.getOutputStream());
}
catch (IOException e) {
System.out.println("Exception: "+e.getMessage());
}
this.start(); // Thread starts here...this start() will call run()
}

public void run() {


try { // get a request and parse it.
String request = is.readLine();
System.out.println( "Request: "+request );
StringTokenizer st = new StringTokenizer( request );
if ( (st.countTokens() >= 2) && st.nextToken().equals("GET") ) {
if ( (request = st.nextToken()).startsWith("/") )
request = request.substring( 1 );
if ( request.equals("") )
request = request + "index.html";
File f = new File(request);
shipDocument(os, f);
}
else {
os.writeBytes( "400 Bad Request" );
}
client.close();
}
catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}

45
}

/**
* Read the requested file and ships it to the browser if found. */

public static void shipDocument(DataOutputStream out, File f) throws


Exception {
try {
DataInputStream in = new DataInputStream(new FileInputStream(f));
int len = (int) f.length();
byte[] buf = new byte[len];
in.readFully(buf);
in.close();
out.writeBytes("HTTP/1.0 200 OK\r\n");
out.writeBytes("Content-Length: " + f.length() +"\r\n");
out.writeBytes("Content-Type: text/html\r\n\r\n");
out.write(buf);
out.flush();
} catch (Exception e) {
out.writeBytes("<html><head><title>error</title></head><body>\r\n\
r\n");
out.writeBytes("HTTP/1.0 400 " + e.getMessage() + "\r\n");
out.writeBytes("Content-Type: text/html\r\n\r\n");
out.writeBytes("</body></html>");
out.flush();
} finally {
out.close();
}
}

46
}

The lines:
String keystore = "serverkeys";
char keystorepass[] = "hellothere".toCharArray();
char keypassword[] = "hiagain".toCharArray();
specify the name of the keystore, its password, and the key password.
Hardcoding the passwords into the code is not a good idea for production
code, however. They can be specified on the command line when running
the server.
The rest of the JSSE related code is in the getServer method:
It access the serverkeys keystore. The JKS is the Java Key Store (a type of
keystore created by keytool).
The KeyManagerFactory is used to create an X.509 key manager for the
keystore.
An SSLContext is an environment for implementing JSSE. It is used to
create a ServerSocketFactory that in turn used to create a SSLServerSocket.
Although we specify SSL 3.0, the implementation that is returned will often
support other protocol versions, such as TLS 1.0. Older browsers, however,
use SSL 3.0 more widely.

To experiment with the HttpsServer class:


Compile the HttpsServer.java using javac
Run the HttpsServer. By default it runs on port 443, but if you cannot start it
on this port, choose another port number greater than 1024.

47
Open a web browser and enter the request: https://localhost or
https://127.0.0.1. This assumes the server is running on port 443. If not, then
use: https://localhost:port

Fig 4.2 Compilation of Server code

Fig 4.3 Execution of Server code

Exporting and Importing keys


To explain how to export and import certificates, I will use my own HTTPS
server which is discussed in the first part of the article. To get started, do the
following:
Run the HTTPS server as discussed in Part I.
Run the ReadHttpsURL1: java ReadHttpsURL1 localhost. You will receive
the same exception as the one described above.
Export the server's certificate using the following keytool command that
says:
Export the server's certificate from the file serverkeys, whose alias is qusay

48
Save the exported certificate in a file called server.cert, which will be created
by the keytool
As you can see, I was asked to enter the password. Upon successful entry of
the password, the server's certificate got exported and saved in the file
server.cert.
Prompt> keytool -export -keystore serverkeys -alias qusay -file server.cert
Enter keystore password: hellothere
Certificate stored in file <server.cert>
Copy the server.cert file to the directory where ReadHttpsURL1 is located.
Use the keytool to create a new keystore and import the server's server.cert
certificate into it. Here is a sample command:
Prompt> keytool -import -keystore trustedcerts -alias qusay -file server.cert
This command produces the following output.
I was asked to enter a password. This is a new password for the trustedcerts
keystore. This keystore is created by the keytool. At the end of the output, I
got asked if I wish to trust this certificate. My answer was yes.
Enter keystore password: clientpass
Owner: CN=localhost, OU=Training and Consulting, O=javacourses.com,
L=Toronto, ST=Ontario, C=CA
Issuer: CN=localhost, OU=Training and Consulting, O=javacourses.com,
L=Toronto, ST=Ontario, C=CA
Serial number: 3dcf988a
Valid from: Mon Nov 11 06:46:18 EST 2002 until: Sun Feb 09 06:46:18
EST 2003
Certificate fingerprints:
MD5: 37:35:4D:3A:2B:7E:B5:09:A5:41:B3:FA:E4:3C:1D:C4
SHA1: CB:7C:77:36:79:A2:37:26:E2:98:61:C2:9D:10:50:69:

49
99:F9:B9:1B
Trust this certificate? [no]: yes
Certificate was added to keystore
Now run the ReadHttpsURL1 and inform it where to look for certificates
using the following command:
Prompt> java -Djavax.net.ssl.trustStore=trustedcerts ReadHttpsURL1
localhost

Fig 4.4 Importing key


This will contact your HTTPS server, verify its certificate and if it is valid,
will download the default page index.html.
Programming Client Applications with JSSE

The JSSE APIs supplement the java.security and java.net packages by


providing extended networking socket classes, trust and key managers, and a
socket factory framework for encapsulating socket creation behavior. These
classes are included in the packages javax.net and javax.net.ssl.

50
The javax.net.ssl.SSLSocketFactory class is an object factory for creating
secure sockets. An instance of SSLSocketFactory can be obtained in two
ways:
Get the default factory by calling SSLSocketFactory.getDefault. The default
factory is configured to enable server authentication only (no client
authentication). Note that most e-commerce web sites do not require client
authentication.
Once an instance of SSLSocketFactory has been created, you can create an
instance of SSLSocket by invoking a createSocket method on the
SSLSocketFactory instance. Here is an example that creates a socket
connection to Sun's WWW server through the SSL port 443, which is the
default port number for HTTPS.
// Get a Socket factory
SocketFactory factory = SSLSocketFactory.getDefault();
// Get Socket from factory
Socket socket = factory.createSocket("www.sun.com", 443);
Working with Low-level SSL Sockets
Now, let's see a complete code of opening an SSL socket connection to an
HTTPS server using low-level sockets. In this application, an SSL socket
connection will be opened to an HTTPS server, and then we read the content
of the default document. The instructions that open the SSL socket are
highlighted in bold. As you can see, the rest of the application is regular Java
code for input/output streams.

ReadHttpsURL1.java

import java.net.*;
import javax.net.*;

51
import javax.net.ssl.*;

public class ReadHttpsURL1 {


static final int HTTPS_PORT = 443;

public static void main(String argv[]) throws Exception {


if (argv.length != 1) {
System.out.println("Usage: java ReadHttpsURL1 ");
System.exit(0);
}

// Get a Socket factory


SocketFactory factory = SSLSocketFactory.getDefault();

// Get Socket from factory


Socket socket = factory.createSocket(argv[0], HTTPS_PORT);

BufferedWriter out = new BufferedWriter(new


OutputStreamWriter(socket.getOutputStream()));
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
out.write("GET / HTTP/1.0\n\n");
out.flush();
String line;
StringBuffer sb = new StringBuffer();
while((line = in.readLine()) != null) {
sb.append(line);
}
out.close();
in.close();
System.out.println(sb.toString());

52
}
}

To experiment with this application:


Copy and paste the code of the ReadHttpsURL1 class into a file named
ReadHttpsURL1.java, and save this file in a directory of your choice.
Compile the ReadHttpsURL1.java using javac.
Run the ReadHttpsURL1 and provide the domain of an HTTPS url. Here is
an example:
Prompt> java ReadHttpsURL1 www.sun.com

Fig 4.5 Compilaiton of Client code


After a few seconds, you will note that tons of HTML code is displayed on
your screen. Note that even though we are providing the domain
www.sun.com, we are opening a connection to https://www.sun.com. This is
because the port number we are using, 443, is the default port number for
HTTPS.
Try another example, such as:
Prompt> java ReadHttpsURL1 www.jam.ca
This will throw the following exception. Can you guess why?

53
Exception in thread "main" javax.net.ssl.SSLHandshakeException:
java.security.cert.CertificateException: Couldn't find trusted certificate
at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.a(DashoA6275)
It didn't work for a good reason. This was caused by the remote server
sending a certificate that is unknown to the client. As I mentioned in the first
part of the article, when a client connects to a server, the server sends its
certificate to the client for authentication. Well, in the first example, where
you entered www.sun.com, that server did send its certificate, but Java
checks the default certificate store and realized that the certificate was
generated by one of the trusted Certificate Authorities that Java trusts by
default. In the second example where you entered www.jam.ca, the
certificate for that site was either self-generated or generated by a
Certification Authority unknown to Java, and therefore it wasn't trusted.
Note: If the system clock is not set correctly, the perceived time may be
outside the validity period of the certificate, the server will assume the
certificate is invalid and therefore a CertificateException will be thrown.
In order to make that example work, you'd need to import the certificate of
the Web site www.jam.ca into the store of certificates trusted by Java.

Deploying Browser Application with JAVA SWINGS


Developing an SSL-enabled web browser.
A web browser works as follows:
• The user enters a URL and the browser retrieves it.

• The browser opens a connection to the domain name of the URL.

• The browser sends HTTP commands.

• The browser waits for an answer from the HTTP/HTTPS server.

54
• The browser receives an HTML reply.

• The browser parses the HTML and displays the rendered page.

The browser we create will support and handle any URLs such as HTTP,
HTTPS and ftp. Note that I parse the HTML using the kit in the class
javax.swing.text.html.HTMLEditorKit, which provides support for HTML
3.2. The code for the browser, SSLBrowser, is shown in Code Sample 3.
Note that the SSLBrowser is implementing the Runnable interface. I did this
because this browser doesn't provide a STOP button. Therefore, if a request
freezes for some reason, multiple downloads can still be instantiated
concurrently as you can see from the run method.

SSLBrowser.java

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SSLBrowser implements ActionListener, Runnable {


private JFrame frame;
private JButton go;
private JEditorPane content;
private JTextField url;
private JLabel statusLine;
// default constructor
public SSLBrowser () {

55
buildBrowserInterface();
}

private void buildBrowserInterface() {


frame = new JFrame(“SSL's Browser");
// on close, exit the application using
System.exit(0);
frame.setDefaultCloseOperation (3);
url = new JTextField("", 25);
go = new JButton("Go Get It");
go.addActionListener(this);
JPanel controls = new JPanel(new FlowLayout ());
controls.add(new JLabel("URL:"));
controls.add(url);
controls.add(go); // HTML text. Use the kit in the class
content = new JEditorPane(); //javax.swing.text.html.HTMLEditorKit,
content.setEditable(false); //which provides support for HTML 3.2
content.setContentType("text/html");
content.setText("<center><h1>SSL's Browser</h1><p> </center>");
statusLine = new JLabel("Initialization Complete");

JPanel panel = new JPanel(new BorderLayout (0, 2));


frame.setContentPane(panel);

panel.add(controls, "North");
panel.add(new JScrollPane (content), "Center");
panel.add(statusLine, "South");
frame.pack();

56
frame.setVisible(true);
}
/** * You cannot stop a download with QBrowser
* The thread allows multiple downloads to start concurrently in case a
download freezes */

public void actionPerformed (ActionEvent event) {


Thread thread = new Thread(this);
thread.start();
} // this is the Thread's run method
public void run () {
try {
String str = url.getText();
URL url = new URL(str);
readURL(url);
} catch (IOException ioe) {
statusLine.setText("Error: "+ioe.getMessage());
showException(ioe);
}
}

private void showException(Exception ex) {


StringWriter trace = new StringWriter ();
ex.printStackTrace (new PrintWriter (trace));
content.setContentType ("text/html");
content.setText ("<h1>" + ex + "</h1><pre>" + trace + "</pre>");
}
/** The URL class is capable of handling http:// and https:// URLs */

57
private void readURL(URL url) throws IOException {
statusLine.setText("Opening " + url.toExternalForm());
URLConnection connection = url.openConnection();
StringBuffer buffer = new StringBuffer();
BufferedReader in=null;
try {
in = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
buffer.append(line).append('\n');
statusLine.setText("Read " + buffer.length () + " bytes...");
}
} finally {
if(in != null) in.close();
}
String type = connection.getContentType();
if(type == null) type = "text/plain";
statusLine.setText("Content type " + type);
content.setContentType(type);
content.setText(buffer.toString());
statusLine.setText("Done");
}

public static void main (String[] args) {


SSLBrowser browser = new SSLBrowser();
}
}

58
The QBrowser handles both HTTP and HTTPS requests since it uses the
URL class. You can test the QBrowser using both HTTP and HTTPS URLs.

Fig 4.6 Compilation of Browser code

Fig 4.7 Execution of Browser code

59
Fig 4.8 Screen shot of SSL enabled browser

60
Looking To The Future

In the present day world, VPN or remote access is used by many companies
on a large scale. So for them, the question is not whether to add SSL remote
access, but when. Is this the right time to get into SSLVPN? The decision
making depends upon each company’s circumstances and remote access
requirements.

The future demands that each and every browser has to be enabled with this
SSL technology, and transform every bit of data securely, through this vast
Internet. Because, Security is the concept, that Internet Designers had
neglected, in the early stages of (DARPA) Defense Advanced Research
Projects Administration net, the first version of an IP based network, funded
by the US Department of Defense in 1969.

No technology solves every problem, and no deployment comes without


cost or growing pain. Finally we hope this project work has provided a
foundation for understanding what SSL technology is, its benefits and
limitations and a detailed explanation of how they can be Implemented.

61
Appendices A “Basics of Tunneling Technology”

As you learned in the previous chapter, tunneling lies at the core of VPN
technology. While the cost effectiveness of VPNs is attributed to the use of
the Internet, the safety and security that VPNs offer are the direct result of
tunneling.

In this chapter, you'll learn about the basics of tunneling technology and the
role it plays to ensure the safety of transactions across a widely
heterogeneous internetwork, such as the Internet. You'll learn about the
components of tunneling, the working of tunneling technology, and the
format of a tunneled packet. You'll also learn about the different types of
tunnels and tunneling protocols.

Understanding Tunneling Technology

Tunneling is the most significant component of VPN technology. It allows


organizations to create virtual networks across the Internet and other public
networks. This virtual network cannot be accessed by "outsiders"—users or
computers that are not a part of the organization's intranet.

Tunneling is the technique of encapsulating an entire data packet in the


packet of another protocol format. In other words, the header of the
tunneling protocol is appended to original packet. The resultant packet is
then transferred to the destination node or network across the intermediate
infrastructure.

The most important aspect of tunneling is that the original data packet, also
referred to as the payload, can belong to an unsupported protocol. Instead of

62
transferring the original packet, which might not be routable across the
intermediate infrastructure, the underlying tunneling protocol appends its
header to the tunneled packet. This header provides the requisite routing
information so that the packet can be successfully delivered across the
internetwork.

Tunneling is analogous to sending a letter. After you write a letter, you place
it in an envelope. This envelope displays the address of the recipient. When
you post this letter, it is delivered to the recipient according to the address on
the envelope. The recipient then needs to open the envelope to read the
letter. In tunneling technology, the letter is equivalent to the original payload
and the envelope represents the packet of the routable protocol in which the
payload is encapsulated. The address on the envelope represents the routing
information that is appended to the packet.

When a tunneled packet is routed to the destination node, it travels across


the internetwork through a logical path. This logical path is referred to as a
tunnel. Upon receiving a tunneled packet, the recipient returns the packet to
its original format. Figure 4-1 depicts the process of tunneling.

Advantages of Tunneling

Tunneling offers a few advantages that have made a significant impact on


networking technology. These advantages are listed below:

• Simplicity and ease of implementation. Because the basic idea


behind tunneling is simple, the technology itself is simple and easy to
implement. Moreover, there is no need to change the existing
infrastructure to accommodate tunneling technology, which makes

63
tunneling a viable and lucrative solution for largeas well as
mediumscale organizations.
• Security. An organization's tunnel access is prohibited to
unauthorized users. As a result, data traveling through the tunnels is
relatively safe—despite the fact that the data is being transmitted
across an unsafe and public medium, such as the Internet.
• Cost-effectiveness. Tunneling uses public networks as the
intermediate internet-works to transfer data to a destination. This
makes tunneling an extremely cost-effective solution, especially when
you compare it to the cost of implementing private intranets that span
the globe or long-distance leased lines. In addition, an organization
can save the considerable amount of money that it would have to
spend annually on the administration and maintenance of these
expensive solutions.
• Protocol indifference. Data belonging to non-routable protocols, such
as Network Basic Input/Output System (NetBIOS), and NetBIOS
Enhanced User Interface (NetBEUI) is not compatible with the
Internet protocols TCP and IP. Therefore, these data packets cannot be
routed as-is across the Internet. However, tunneling allows you to
route such non-IP packets successfully to the destination by
"enveloping" them within IP packets.
• IP address savings. As mentioned earlier, tunneling allows protocols
with non-routable non-IP addresses to be inserted within a packet that
uses a globally unique public IP address. As a result, instead of having
to buy and assign a globally unique IP address (also known as a public
IP address) for each node within the network, the network can buy a
small block of globally unique IP addresses. When a node within this

64
private network establishes a VPN connection, any of the available IP
addresses from the block can be appended to the non-IP data packets.
Thus, the private network can reduce an organization's need for
globally unique IP addresses.

Now that you have the basic ideas of tunneling technology, you're ready to
move to a discussion of tunneling components.

Components of Tunneling

To successfully establish a tunnel between the two communicating ends,


four tunneling components are required.

• Target network. The network that contains the resources that needs
to be accessed by the remote client, which initiated the VPN session
request. (The target network is also referred to as home network in
some VPN-related documentations.)
• Initiator node. The remote client or server that initiates the VPN
session. The initiator node can be a part of a local network or can be a
mobile user using a laptop.
• HA (Home Agent). The software interface that generally resides at the
network access node (router) in the target network. However, a
destination node, such as a dial-up access server, can also host the
HA. The HA receives and authenticates the incoming requests to
verify that they are from trusted hosts. Upon successful initiator
authentication, the HA allows the establishment of a tunnel.
• FA (Foreign Agent). The software interface that resides either at the
initiator node or at the network access node (router) of the network to

65
which the initiator node belongs. The initiator node uses the FA to
request a VPN session from the HA at the target network.

Tunneled Packet Format


As described earlier, before it is delivered to the target network across the
tunnel, the original data packet is encrypted by the FA. This encrypted
packet is referred to as the tunneled packet. A tunneled packet consists of
three parts. These parts follow:

• Header of the routable protocol. This header field contains the


addresses of the source (FA) and the destination (HA). Because
transactions over the Internet are predominantly IP-based, this header
is generally the standard IP header and contains the IP addresses of the
FA and HA involved in the transaction.
• Tunnel packet header. This header contains the following five fields:
o Protocol type. This field indicates the type of the original data
packet (or pay-load) protocol.
o Checksum. This field contains the checksum that is used to
check whether the packet was corrupted during the
transmission. This information is optional.
o Key. This information is used to identify or authenticate the
actual source of data (initiator).
o Sequence number. This field contains a number that indicates
the sequence number of the packet in the series of packets that
are being transmitted.
o Source routing. This field contains additional routing
information. This field is optional.

66
• Payload. The original packet sent by the initiator to the FA. It also
contains the original header.

Tunneling Protocols

Tunneling technology makes use of three types of protocols.

• Carrier protocol. These protocols are used to route tunneled packets


to their intended destination across the internetwork. The tunneled
packets are encapsulated within the packets of this protocol. Because
it must route the packets across a heterogeneous internetwork, such as
the Internet, this protocol must be widely supported. As a result, if
tunnels are created across the Internet, the carrier protocol that is used
predominantly is IP. However, in the case of private intranets, native
routing protocols can also serve as carrier protocols.
• Encapsulating protocol. These protocols are used to encapsulate the
original payload. In addition, the encapsulating protocol is also
responsible for the creation, maintenance, and termination of the
tunnel. Today, PPTP, L2TP, and IPSec are the most commonly used
encapsulating protocols.
• Passenger protocol. The original data that needs to be encapsulated
for the purpose of transmission across the tunnel belongs to this
protocol. PPP and SLIP (Serial Line Internet Protocol) are commonly
used passenger protocols.

67
REFERENCES

Andrew S. Tanenbaum, “Computer Networks“, Fourth Edition, pp.37-48.

Aventail corporation, “Now an SSL VPN can replace IPSec for Remote
Access, A vendor white paper.

Aventail corporation, “ROI comparision: SSL VPNs or IPSec VPNs for


remote access?”, A vendor white paper.

Charlie Scott, Paul Wolfe, and Mike Erwin, “Virtual Private Networks“,
Publisher: O'Reilly, Second Edition, ISBN: 1-56592-529-7, pp.6-40.

David Wagner University of California, Berkeley, and Bruce Schneier


Counterpane Systems, “Analysis of the SSL 3.0 protocol” A Research
paper.

David M. Piscitello and Lisa Phifer, “Simplifying Secure Remote


Access: SSL VPNs”, a white paper from Business
Communications Review on Network security, APR 2003
edition.

Greg travis, “Using JSSE for secure socket communication”, A white


paper from IBM Developer works.

James Henry Carmouche, “IPsec Virtual Private Network fundamentals“,


Publisher: Cisco Press, ISBN-13: 978-1-58705-207-1, chapter no1.

Meeta Gupta, “Building a VPN“ Premier Press, ISBN:1931841810,


chapter 1, 2, 3.

Stephen Thomas, “SSL and TLS Essentials, Securing the Web”,


Publisher: Wiley, pp.12-14 & 37-60.

VPN

68
http://compnetworking.about.com/od/vpn/a/what_is_a_vpn.htm
http://www.consumer-research-
guide.com/vpn.htm?gclid=CM7ewZyW7IcCFSGTYAodx3RXfQ
http://www.infosec.gov.hk/english/itpro/sectips/VPN_eng.pdf
http://www.pcnetworkadvisor.com

VPN forums
http://www.tek-tips.com/threadminder.cfm?pid=463
http://www.vpnc.org/vpn-technologies.html

Configuration of VPN connections


http://kb.iu.edu/data/akko.html

Tcp/Ip guide
http://www.tcpipguide.com/free/t_toc.htm

IPSec
http://send2press.com/newswire/2006-11-1130-004.shtml
http://www.vpnlabs.com/

SSL / TLS
http://info.ssl.com/
http://www.cse.wustl.edu/~jain/cse473-05/ftp/i_isec/sld008.htm
http://www.PacktPub.com/book/ssl_vpn
http://www.ietf.org/html.charters/tls-charter.html
http://www.cs.bris.ac.uk/~bradley/publish/SSLP/chapter4.html
http://www.csi.uottawa.ca/~istvan/ecomm/SSL.html
http://www.codeproject.com/cs/internet/socketsincs.asp
http://home.comcast.net/~fjhirsch/SSL/tlstut_html/sld017.htm

Ipsec vs.ssl
http://www.unixwiz.net/techtips/iguide-ipsec.html
http://www.cisco.com/en/US/netsol/ns340/ns394/ns50/ns140/networking
_solutions_white_paper09186a0080136858.shtml
http://docs.sun.com/source/816-6156-10/contents.htm

Security Issues
http://e-docs.bea.com/wle/security/concepts.htm

69
http://searchsecurity.techtarget.com/sDefinition/0,,sid14_gci343029,00.ht
ml
http://www.openssl.org/docs/ssl/ssl.html
http://home.comcast.net/~fjhirsch/SSL/tlstut_html/index.htm
http://www.musicahead.com/manual/mod/mod_ssl/ssl_intro.html
http://httpd.apache.org/docs/2.0/ssl/ssl_faq.html
http://tldp.org/HOWTO/SSL-Certificates-HOWTO/index.html

JSSE
http://www.onjava.com/pub/a/onjava/2001/05/03/java_security.html?pag
e=1
http://java.sun.com/developer/JDCTechTips/2004/tt0817.html#1
http://java.sun.com/j2se/1.4.2/docs/guide/security/jsse/JSSERefGuide.ht
ml
http://builder.com.com/5100-6370-1050055.html

Client-Server communications
http://www.codeproject.com/cs/internet/AsyncSocketServerandClien.asp

Rfc’s of protocols
http://tools.ietf.org/html/rfc2764
tls http://www.ietf.org/rfc/rfc2246.txt

Implementation:
http://java.sun.com/developer/technicalArticles/Security/secureinternet/
http://java.sun.com/developer/technicalArticles/Security/secureinternet2/

70

Você também pode gostar