Sie sind auf Seite 1von 21

Security in the Java Platform

Waldir Ribeiro Pires Junior


wpjr2@yahoo.com
Professor: Dr Fabrício Jailson Barth
fabricio.barth@poli.usp.br
2005.03.03

Abstract Acronyms and Definitions


For the project article in the Distributed Objects in Java J2ME
Acronym Definition
J2EE subject of the post-graduate course in Mobile and
JVM Java Virtual Machine
convergent Systems in Cellular Telephony, this article was
written with the objective to present the security features of the API Abstract Programming Interface
Java Platform, including core security mechanisms, security DES Digital Encryption Standard
extensions and security in the J2ME Platform. ITU International Telecommunication Union
SSL Secure Socket Layer
TSL Transport Layer Security
IETF Internet Engineering Task Force
Index RFC Request For Comments
Acronyms and Definitions ..........................................................1 MIDP Mobile Information Device Profile
1 Introduction .......................................................................2 CLDC Connected Limited Device
1.1 The Java Platform ...............................................2 Configuration
1.2 General Concept of Security ...............................2 CDC Connected Device Configuration
1.3 Security Resources in the Java 2 Platform ..........3 HTTPS Hyper Text Transfer Protocol Secure
2 Java Sandbox.....................................................................4 IEEE Institute of Electrical and Electronic
2.1 The Java Sandbox Model ....................................4 Engineers
2.2 Anatomy of a Java Application...........................5 RMI Remote Method Invocation
3 Java Security Extensions ...................................................7 JCP Java Community Process
3.1 JCE – Java Cryptography Extension ...................7 JSR Java Specification Request
3.2 JSSE – Java Secure Sockets Extension ...............9 SOAP Simple Object Access Protocol
3.3 Java Authentication and Authorization Service 11 JCA Java Cryptography Architecture
3.4 GSS API – Generic Security Services API .......13 LDAP Lightweight Directory Access Protocol
3.5 JSR 28 - SASL – Simple Authentication and
Secure Layer....................................................................14
4 Security in the J2ME Platform ........................................14
4.1 J2ME/ MIDP 2.0/ CLDC 1.1 ............................14
4.2 SATSA – Security and Trust Services API for
J2ME 17
4.3 JSR 219 – Foundation Profile 1.1 .....................19
5 Conclusion.......................................................................19
Glossary ....................................................................................20
References.................................................................................21
analysis of the context involved in the application. Some
security requirements can be:
1 Introduction
Security has become an important issue in the society where o Safety from malevolent programs: Programs should not
information is very important and must be protected from be allowed to harm a user' s computing environment. This
unauthorized entities. Applications were then required to have includes Trojan horses as well as harmful programs that can
security features for allowing data processing and transfer in a replicate themselves--computer viruses.
safe manner. However providing security at the application level o Non-intrusiveness: Programs should be prevented from
has proven to be quite ineffective, since this resource won’t be discovering private information on the host computer or the
accessible for other applications that may also require it. By host computer's network.
providing it at lower levels, applications would then be able to
utilize it whenever necessary, isolating the service for better o Authentication: The identity of parties involved in the
upgrade support, alterations and so on. Thus providing security program should be verified.
APIs at the platform level can be considered the best approach o Encryption: Data that the program sends and receives
to security because it “incorporates” security into the platform should be encrypted.
model. The breaches of security tend to be less in this approach
also. All operations in upper layers will then be done in a secure o Auditing: Potentially sensitive operations should always be
way by the lower layers, for example, in the operating system. logged.
The Java Platform was designed from the start taking into o Well-defining: A well-defined security specification would
account the security issue for its applications. be followed.

This document presents the security features of the o Verifying: Rules of operation should be set and verified.
Java Platform. It will describe the general concept of security, o Well-behaving: Programs should be prevented from
the resources and JSRs available, extensions and some specific consuming too many system resources.
security features of the J2ME platform.
o C2 or B1 certified: Programs should have certification
from the U.S. government that certain security procedures
1.1 The Java Platform are included

The Java platform is composed primarily of the Java Language,


some libraries or APIs and the Java Virtual Machine. As it will From all these security requirements, only some have
be shown, all these components will complement each other in been incorporated into the Java Platform. The default security
the capacity of delivering a “secure” environment for Java model of Java 1.0 for example had only provided safety from
applications to run. The Java Programming Language was malevolent programs and non-intrusion for its applet
designed from the start to provide protection to the developer applications. Since the beginning it was desired for the security
and to the end user of the application. This is so in terms of architecture in Java to be evolvable, therefore authentication was
accessing the resources of the operating system in which he/she added in version 1.1 and encryption was added only in the Java
requires or does not require. The language itself provides 2 core version 1.4. As the platform evolves, other security
interesting factors so as to guarantee a safe environment for the features may be added in the future, as required. It is believed
programs. APIs have also been proposed and incorporated into that they will all eventually make their way into Java.
the Java Language, providing some additional functionality such
as cryptography, authentication, authorization, key and The whole demand for security in Java originated from
certificate management, etc. To conclude the set, the JVM also its ability for programs/applets to be downloaded through the
contains some security features which prevent Java objects from network and be run on another machine in Java enabled
accessing the resources underlying the operating system. browsers. Along with the widespread increase of size of the
Internet usage and its accessibility, the platform’s ability to do
The Java Platform itself brought a lot of interest for such tasks brought a great deal of acceptance on the market.
many reasons. Its cross-platform capabilities, ease of
programming, robustness, memory management and even The main feature that prevented Java programs to
security. These reasons have caused a considerable amount of install and run viruses, create security breaches is the fact that
developers to select it as the killer platform for their Java programs are considered safe. This is so because
development needs. theoretically they cannot install, run or propagate viruses. They
also cannot perform any action that is harmful to the operating
system or the user’s computing environment. The purpose was
1.2 General Concept of Security to bring safety into the platform itself, thus providing security
from within. For this reason, from all the security requirements
The concept of security is rather complex to define, since presented above, only a few had been selected for the first
different types of applications will have different security version releases. In this case, only the first one had been chosen
requirements, depending on its running environment, its to be a part of the first release of the platform.
accessibility, its capability to transfer data through some means
of communication, etc. As stated in [1], security means different
things for different people. The term requires a discussion and
1.3 Security Resources in the Java 2
Platform

The Java 2 Platform provides the following security features:

o Protections within the Java language


o A configurable security policy for accessing resources with
features such as:
o Message digest capability
o digital signature and key creation and management Figure 1: Security Policy for Java code
o An infrastructure through APIs or extensions to support all
features above. 1.3.3 APIs Infrastructure
This infrastructure provides a set of APIs to enable security
1.3.1 Java Language Security
services such as authentication, authorization, cryptography and
key/certificate management. They used to be extensions (outside
The Java Language itself was designed in the beginning to be a
the standard Java core APIs) up to version 1.3, becoming a part
“safe” programming language. Its object orientation feature
of the core APIs after 1.4. Before version 1.4, Java provided a
permits only single inheritance of classes, usage of interfaces
small set of security APIs regarded as the JCA (Java
and a strong encapsulation of data within the classes. Its strong
Cryptography Architecture). The APIs in version 1.4 security
typing feature prohibits the conversion of illegal types and array
core (J2SE and J2EE) and the security features of J2ME are:
bound checks are always done. One of the main features of the
platform is its garbage collection mechanism, picking up objects
o For J2SE and J2EE:
that are no longer being used in memory, minimizing the risk of
o JCE - Java Cryptography Extension
security breach. The usage of references for objects at runtime
o JSSE - Java Secure Sockets Extension
instead of pointers, the usage of exceptions and strong thread
o JAAS - Java Authentication and Authorization
control provide a theoretically safe environment for developers
Service
to implement their applications without causing any serious
o GSS API – Generic Security Services API
security harm to the system.
o JSR 28 – SASL – Simple Authentication and
Secure Layer
1.3.2 Configurable Security Policy o For J2ME:
o MIDP 2.0/CLDC 1.1 Security Policy Model
Regarding the platform itself, a customizable security policy for o JSR 177 – SATSA – Security and Trust Services
the platform was designed. The goal was to allow expansion and API
adaptation of the features to specific application domains and o JSR 219 – J2ME Foundation Profile 1.1
enable future upgrades. This policy is composed of:
These extensions are complementary to each other
o Management of message digests and digital signatures regarding security services provisioning. As it is shown in
o Key and certificate management Figure 2, some APIs or standards are related to others when
o Access control for Java programs of the machine resources. main security features are compared. There are three main sets
of features defined: cryptography (JCE), secure sockets handling
From all the features listed above, the last one has been (JSSE) and authentication/authorization (JAAS). The JSRs
incorporated into the platform security model using the concept listed above and shown below specify some functionalities that
of a sandbox. This will be more detailed later in this document. are related to these three main security features shown below.
The main security model premise in Java is the fact that it aims More information will be presented in the next sections of this
to protect the information from unauthorized access and document. Some subsets of the APIs are actual implementations
alterations yet allowing Java programs to be executed in the of requested and defined JSRs.
computer. The main reason for this as mentioned in 1.2 was the
convenience for Java programs to be downloaded through the
Web, Intranet, etc. According to the domain defined in the JVM
for the application type (local or remote), Java programs are
confined in a specified location, whether having access to all
resources or confined in the Sandbox. This will be better
detailed in section 2.

Figure 2: Complementary view of the extensions.


2 Java Sandbox
Java language creators needed a creative solution to provide
safety in programs when accessing the machine’s resources.
This solution would have to both enable the program itself to
execute and perform its desired function (in a controlled
manner) and at the same time restrict access to resources that
they are not allowed to have. The JVM must be capable of
determining the safety level of the program to be executed
(regardless of it being local or remote), providing this access
and at the same time ensuring the machine integrity.

The main idea behind this model is that when a


program is allowed to execute on the local machine, this
program will require an environment where it can play or run, Figure 4: Security levels in Java Sandbox
but this program needs to be confined in a “play” area only. This
program can have toys to play with, meaning that some access
to the system resources can be given to it, but always in a
limited fashion. The sandbox is made up of several different
systems operating together. These systems range from security
managers running inside of the application which imported the
applet, to safety features built into the Java language and the
virtual machine.

Java 1.0

Java 1.1

Figure 3: Java Sandbox and the JVM

2.1 The Java Sandbox Model

The Java Sandbox model provides a safe environment for


programs to execute, protecting a number of resources by
establishing access levels. The resources of a typical machine
can be:
Java 2.0
o Local memory (RAM) Figure 5: Java Security Architecture Evolution.
o File system
o Web server (for applets) In earlier versions of the Java Platform, specifically
o Peripherals, such as the keyboard, mouse and the screen. version 1.0, only applets were allowed to run in a Sandbox,
meaning that all other applications were considered trustable. In
There are four security levels within the Sandbox for version 1.1, applets that were digitally signed were considered
Java programs to run. The figure below demonstrates the levels trustable, having more access to resources that the ones that
and examples of resources these programs can have access to. were not signed. In version 2.0, a whole new architecture was
From Minimal to Open, the Sandbox can restrict access to developed, being based on security policies. All programs
practically all system resources in the machine to the programs, (applets or local programs) now have the potential to run within
preventing unauthorized access. a Sandbox. The only difference is for applications, where
security policies are not mandatory. This can be configured via
command line. Applications can also establish and modify their
security policies. However, this can be managed by the user or
system administrator, for example, by permitting all Java than one class loader inside the JVM. Classes can be loaded in
programs to run in a customized Sandbox defined by them. customized ways thanks to its flexible architecture.

2.2 Anatomy of a Java Application There are two types of class loaders: a “primordial”
class loader and class loader objects. The first one (and there is
only one) is part of the JVM implementation. It loads trusted
Java applications (applets, local, etc) pass through specific steps classes, including the ones from the Java APIs, normally located
before running in the JVM of the system. The figure below on the local disk. The latter one loads classes in custom ways,
demonstrates the features that play a role in the development of which can be installed by the Java application at runtime. For
the Sandbox. example, classes can be downloaded through a network and
loaded into the JVM. The classes loaded by the class loader
objects are considered suspicious in the eyes of the primordial
class loader. These objects are written in Java, compiled into
classes, loaded into the virtual machine and instantiated just like
any other object, contrasting with the first class loader (the
primordial one) which is a part of the JVM implementation.

Thanks to these class loader objects, there is no need to


know at compile time all the classes that take part in running the
desired Java application. This application can be dynamically
extended at runtime. As it runs, the desired application can
determine which classes it needs and can also load them through
the class loader objects. Class loader objects are dependant on
other class loaders, at least to the primordial class loader.

The class loader architecture contributes to Java'


s
sandbox in two ways:
Figure 6: Elements of the Java Sandbox
o It prevents malicious code from interfering with benevolent
code.
These elements are: o It guards the borders of the trusted class libraries.

• The Bytecode verifier


• The class loader
• The access controller
• The security manager
• The security APIs
• The key database

2.2.1 The bytecode verifier


Figure 7: Java class loader architecture
It ensures that Java class files follow the rules of the Java
language. In terms of resources, the bytecode verifier helps
The class loader architecture also guards the borders of
enforce memory protection for all Java programs. Before
the trusted class libraries by making sure untrusted classes can't
running a newly imported applet, the class loader invokes the
pretend to be trusted. If a malicious class could successfully
verifier. The verifier checks that the applet conforms to the Java
trick the JVM into believing it was a trusted class from the Java
language specification and that there are no violations of the
API, that malicious class potentially could break through the
Java language rules or name space restrictions. The verifier
Sandbox barrier. By preventing untrusted classes from
checks for common violations of memory management, like
impersonating trusted classes, the class loader architecture
stack underflows or overflows, and illegal data type casts, which
blocks one potential approach to compromising the security of
could allow a hostile applet to corrupt part of the security
the Java runtime condition. By providing protected namespaces
mechanism or to replace part of the system with its own code.
for classes loaded by different class loaders, this architecture
prevents malicious code from interfering with benevolent code.
2.2.2 The class loader

Class loaders are responsible for importing binary data that


defines the running program’s classes and interfaces. Classes are
introduced into the Java environment when they are referenced
by name in a class that is already running. Once the first class is
running (class defined with a main() method), future attempts of
loading classes are done by the class loader. There may be more
Figure 8: Class loader in action for example, a trusted applet from the local disk may be trying
to read the disk, or an imported untrusted applet may be trying
to connect back to its home server — the virtual machine will
When an applet is to be imported from the network, the
then perform the action. Otherwise, the virtual machine raises a
web browser calls the applet class loader. In addition to fetching
security exception and writes an error to the Java console. The
an applet’s executable code from the network, the class loader
security manager will not allow an untrusted applet to read or
enforces the name space hierarchy. A namespace controls what
write to a file, delete a file, get any information about a file,
other portions of the Java Virtual Machine an applet can access.
execute operating system commands or native code, load a
By maintaining a separate namespace for trusted code which
library, or establish a network connection to any machine other
was loaded from the local disk, the class loader prevents
than the applet’s home server. This list is not exhaustive but
untrusted applets from gaining access to more privileged, trusted
does give a representative sample of the restrictions placed on
parts of the system. Applets downloaded from the net cannot
applets. An application or a web browser can only have one
create their own class loaders. Downloaded applets are also
security manager. This assures that all access checks are made
prevented from invoking methods in the system’s class loader.
by a single security manager enforcing a single security policy.
The security manager is loaded at start-up and cannot be
In Java's sandbox, the class loader architecture is the
extended, overridden or replaced. For obvious reasons, applets
first line of defense against malicious code. It is the class loader,
can not create their own security managers.
after all, that brings code into the JVM -- code that could be
hostile.
An important note to mention is that the security
manager is optional for local Java applications and standard for
2.2.3 The access controller remote Java code (applets). The application itself has the
responsibility to start its security manager. Without the security
The access controller allows (or prevents) most access from the manager, the application will have access to all Java APIs
core API to the operating system. While the security manager is without restrictions. Once the application starts the security
the key to the security model of the Java sandbox, the access manager, the latter one will be responsible for the whole lifetime
controller is the mechanism that the security manager actually of the application. From this point on, only API requests granted
uses to enforce its protections. The access controller is actually by the manager will be accessible to the application. Security
somewhat redundant. The purpose of the security manager is to policies can also be customized, to check for API access, source
determine whether or not particular operations should be of the request (direct or indirect access from class loaders),
permitted or denied. The purpose of the access controller is loading information (local or remotely downloaded), etc.
really the same: it decides whether access to a critical system Despite having only one security manager per application, that
resource should be permitted or denied. Hence, the access security manager can establish a flexible security policy that can
controller can do everything the security manager can do. vary based on the trustworthiness of the code requesting the
action.
The reason there is both an access controller and a
security manager is mainly historical: the access controller is
only available in Java 1.2 and subsequent releases. Before the
access controller existed, the security manager had to rely on its
internal logic to determine the security policy that should be in
effect, and changing the security policy required changing the
security manager itself. Starting with 1.2, the security manager
is able to defer these decisions to the access controller. Since the
security policy enforced by the access controller can be
specified in a file, this allows a much more flexible mechanism
for determining policies. The access controller also gives us a
much simpler method of granting fine-grained, specific
permissions to specific classes.

2.2.4 The security manager


Figure 9: The security manager
The security manager is the primary interface between the core
API and the operating system; it has the ultimate responsibility In general, the security manager is responsible for:
for allowing or preventing access to all system resources. In 1.2,
the security manager uses the access controller for most (but not o Accepting a socket connection from a specified host and
all) of those decisions; in 1.0 and 1.1, the security manager is port number
solely responsible for those decisions. It is considered to be the o Modifying a thread (change its priority, stop it, and so on)
“ultimate line of defense”. o Opening a socket connection to a specified host and port
number
The security manager enforces the boundaries around o Creating a new class loader
the sandbox. Whenever an applet tries to perform an action o Deleting a specified file
which could corrupt the local machine or access information, the o Creating a new process
JVM first asks the security manager if this action can be o Causing the application to exit
performed safely. If the security manager approves the action — o Loading a dynamic library that contains native methods
o Waiting for a connection on a specified local port number The last two items on this list have broad applicability
o Loading a class from a specified package (used by class beyond expanding the Java sandbox. With respect to the
loaders) sandbox, digital signatures play an important role, because they
o Adding a new class to a specified package (used by class provide authentication of who actually owns the Java class. This
loaders) provides the ability for end users and system administrators to
o Accessing or modify system properties grant very specific privileges to individual classes or signers.
o Accessing a specified system property But a digital signature might be used for other applications that
o Reading from a specified file require authentication for data access.
o Writing to a specified file
Controlling Access to the core APIs
o
3 Java Security Extensions
There are two actions not listed above however that
could potentially be unsafe are allocation of memory and As presented earlier, extensions added to the Java Platform
invocation of threads. Currently, a hostile applet can crash a throughout the versions helped increase the amount of security
user'
s browser by: services that users and/or programs may require. They can
function independently or in a complementary fashion. For
o Allocating memory until it runs out example, in a J2EE server, enterprise applications may require
o Firing off threads until everything slows to a crawl authentication and cryptographic services for tasks that are
unique or different within the server.
These kinds of attacks are called denial of service
attacks (DOS), because they deny users the ability to use their
own computers. The security manager does not allow you to
enforce any kind of limit on allocated memory or thread
creation. (There are no checkAllocateMemory() or
checkCreateThread() methods in the security manager class.)
The following are other kinds of hostile applets that currently
are possible:

o Applets that send unauthorized e-mail from the user' s


computer
o Applets that make annoying noises even after you leave the
Web page
o Applets that display offensive images or animations
Figure 10: Java Platform Security Extensions
A security manager therefore isn' t enough to prevent
every possible action that could render a machine useless. 3.1 JCE – Java Cryptography Extension
Despite the attacks, the security manager attempts to provide a
check method that allows you to control access to almost all
potentially unsafe actions. JCE provides a variety of cryptographic operations:

o Encryption (Ciphers) support for symmetric, asymmetric,


2.2.5 The security APIs block and stream ciphers. It also supports secure streams
and sealed objects.
The security APIs (that is, classes in the java.security package o Secure Key Exchange
composing the JCA) forms the basis for authenticating signed o Secure Message Digests via Message Authentication Code
Java classes. Although it is only a small box in the diagram, the (MAC) algorithms.
security package is a complex API. This API includes: o An alternate key management system
o Support to various encryption algorithms
o The security provider interface, the means by which o DES, DESede, Blowfish, PBEwithMD5AndDES,
different security implementations may be plugged into the gerenciamento de chaves Diffie-Hellman,
security package TripleDES, MD5 e SHA1
o Message digests o AES (Java 1.4.2)
o Keys and certificates
o Digital signatures
o Encryption (an optional extension to the security package) 3.1.1 Export Controls
JCE was designed in a way that other cryptographic libraries can
2.2.6 The key database be plugged in as service providers, allowing new algorithms to
be inserted seamlessly. JCE was created to extend the Java
This database contains a set of keys used by the security Cryptography Architecture (JCA) APIs already available in the
manager and access controller to verify the digital signature that Java 2 Platform that were restricted to usage inside the US only.
accompanies a signed class file. In the Java architecture, it is JCA offers only the basic architecture and interfaces and
part of the security package, though it may be manifested as an fundamental objects in cryptography. It also provides a service
external file or database. provider architecture that allows each provider to include
specific algorithms. JCE contains the actual implementation of o Key Agreement: provides the functionality of a key
the cryptography algorithms themselves. agreement protocol. The keys involved in establishing a
shared secret are created by one of the key generators
Many cryptographic algorithms however are subjected (KeyPairGenerator or KeyGenerator), a KeyFactory, or as
to US export control regulations. The U.S. is not the only a result from an intermediate phase of the key agreement
government that regulates the use of encryption, and encryption protocol.
software can face import restrictions as well as export
o Mac: provides the functionality of a Message
restrictions. Other countries have regulations for cryptography,
Authentication Code (MAC).
but in most cases they are less onerous than those of the United
States. Even though the U.S. has relaxed its export rules, some
restrictions still apply. JCE or JSSE may not be exported (and,
hence, any programs that use them) for example, to the
following countries: Afghanistan, Cuba, Iran, Iraq, Libya, North
Korea, Serbia/Montenegro (Yugoslavia), Sudan, Syria and
parties listed on the Denied and Restricted Parties List (available
at http://bxa.fedworld.gov/prohib.html).

The encryption extensions, like many aspects of the


Java platform, allow for third-party implementations of JCE.
However, many of the popular algorithms that are used by the
extensions are patented, which also restricts their use. RSA Data
Security, Inc. holds a patent in the U.S. on several algorithms
involving RSA encryption and digital signatures; Ascom System Figure 11: JCA and JCE
AG in Switzerland holds both U.S. and European patents on the
IDEA method of performing encryption. If you live in a country
The main packages of JCE are:
where these patents apply, you can' t use these underlying
algorithms without paying a licensing fee to the patent holder. In
o java.security (JCA)
particular, this means that many of the third-party security
o Access control to resources
providers and third-party implementations of JCE cannot be
o Message digests
used within the United States because of patents held by RSA.
o Public key, digital signature and certificate
Sun for example has an agreement with RSA Data Security to
management, (X.509 v2 e v3)
redistribute its implementation of the RSA algorithms.
o Safe random number generator
o RSA (symmetric cypher algorithm) and DSA
3.1.2 Core Classes (Digital Signature Algorithm)
o javax.crypto (JCE)
The Core classes of JCE are: o Cipher handling
o Diffie-Hellman Key Generation and management
o Cipher: provides the functionality of a cryptographic o javax.security (JCE)
cipher used in the encryption and decryption. It constitutes o Kerberos authentication protocol
the core of the JCE framework. o Digital certificate management

o Cipher Streams: JCE presents the concept of secure Following below an example of JCE using Blowfish:
streams, combined with InputStream or OutputStream with
a Cipher object. They basically encrypt or decrypts the data /*
* Copyright 1997-2001 by Sun Microsystems, Inc.,
passing through. * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
* All rights reserved.
o Key Generator: used to generate secret keys for symmetric *
* This software is the confidential and proprietary information
algorithms. * of Sun Microsystems, Inc. ("Confidential Information"). You
* shall not disclose such Confidential Information and shall use
o Secret Key Factory: represents a factory for secret keys. It * it only in accordance with the terms of the license agreement
* you entered into with Sun.
is used to convert keys of type java.security.Key into key */

specifications (transparent representations of the underlying import java.security.*;


import javax.crypto.*;
key material in a understandable format) and vice-versa. It import javax.crypto.spec.*;
operates only on secret keys (symmetric). /**
* This program generates a Blowfish key, retrieves its raw bytes, and
o Sealed Object: enables a programmer to create an object * then reinstantiates a Blowfish key from the key bytes.
and protect its confidentiality with a cryptographic * The reinstantiated key is used to initialize a Blowfish cipher for
* encryption.
algorithm. If an object can implement the */

java.io.Serializable interface, a sealed object can be created, public class BlowfishKey {


encapsulating the original object in a serialized format and public static void main(String[] args) throws Exception {
sealing (by means of encryption) its serialized contents KeyGenerator kgen = KeyGenerator.getInstance("Blowfish");
using a cryptographic algorithm to protect its SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
confidentiality. SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish");

Cipher cipher = Cipher.getInstance("Blowfish");


cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted =
cipher.doFinal("This is just an example".getBytes());
}
}

The key generator is instantiated using the Blowfish


algorithm. Then the secret key is generated and converted into
raw data (bytes). The secret key specification is then instantiated
using the raw data and the algorithm. The cipher object is then
created and initialized with the key specification. At the end the
data is encrypted and stored into a byte array format.

3.2 JSSE – Java Secure Sockets


Extension

This extension enables secure Internet communications. It


provides a framework and an implementation for a Java version
of the SSL and TLS protocols and includes functionality for data
encryption, server authentication, message integrity, and Figure 12: Interaction between SSL client and Server.
optional client authentication. Using JSSE, developers can The SSL messages are sent in the following order:
provide secure passage of data between a client and a server
running any application protocol, such as Hypertext Transfer
Protocol (HTTP), Telnet, or FTP, over TCP/IP. By abstracting 1. Client hello - The client sends the server information
the complex underlying security algorithms and "handshaking" including the highest version of SSL it supports and a list of
mechanisms, JSSE minimizes the risk of creating subtle, but the cipher suites it supports. This information includes
dangerous security vulnerabilities. Furthermore, it simplifies cryptographic algorithms and key sizes.
application development by serving as a building block which 2. Server hello - The server chooses the highest version of
developers can integrate directly into their applications. SSL and the best cipher suite that both the client and server
support and sends this information to the client.
JSSE was previously an optional package to the Java 2
SDK versions 1.2 and 1.3, but it has now been integrated into 3. Certificate - The server sends the client a certificate or a
the J2SDK, v 1.4. JSSE provides both an application certificate chain. A certificate chain typically begins with
programming interface (API) framework and an implementation the server' s public key certificate and ends with the
of that API. The JSSE API supplements the "core" certificate authority'
s root certificate. This message is
cryptographic services defined in the Java 2 SDK, v 1.4 optional, but is used whenever server authentication is
java.security and java.net packages by providing extended required.
networking socket classes, trust managers, key managers, SSL 4. Certificate request - If the server needs to authenticate the
Contexts, and a socket factory framework for encapsulating client, it sends the client a certificate request. In Internet
socket creation behavior. It also provides a limited public key applications, this message is rarely sent.
certificate API that is compatible with Java Development Kit
1.1-based platforms. However, this limited javax.security.cert 5. Server key exchange - The server sends the client a server
certificate API is provided only for backward compatibility with key exchange message when the public key information
JSSE 1.0.x and should not be used. Instead, the standard sent in 3) above is not sufficient for key exchange.
java.security.cert certificate API should be used. 6. Server hello done - The server tells the client that it is
finished with its initial negotiation messages.
Version 1.0.2 takes advantage of the relaxed export
restrictions of the U.S. and is exportable. Unlike JCE, however, 7. Certificate - If the server requests a certificate from the
there are still two different versions of JSSE: one for domestic client in Message 4, the client sends its certificate chain,
use (use within the United States and Canada) and one for just as the server did in Message 3. Only a few Internet
global use. The difference between these two versions is that the server applications ask for a certificate from the client.
domestic version allows you to substitute new implementations 8. Client key exchange - The client generates information
of the SSL algorithms. Such substitution is still prohibited by used to create a key to use for symmetric encryption. For
export rules, so the global version does not allow it. However, RSA, the client then encrypts this key information with the
both versions provide exactly the same API and the same key server'
s public key and sends it to the server.
strength for their encryption.
9. Certificate verify - In internet applications, this message is
rarely sent. Its purpose is to allow the server to complete the
process of authenticating the client. When this message is
used, the client sends information that it digitally signs
using a cryptographic hash function. When the server
decrypts this information with the client' s public key, the
server is able to authenticate the client.
10. Change cipher spec - The client sends a message telling
the server to change to encrypted mode.
11. Finished - The client tells the server that it is ready for
secure data communication to begin.
12. Change cipher spec - The server sends a message telling
the client to change to encrypted mode.
13. Finished - The server tells the client that it is ready for
secure data communication to begin. This is the end of the
SSL handshake.
14. Encrypted data - The client and the server communicate
using the symmetric encryption algorithm and the
cryptographic hash function negotiated in Messages 1 and Figure 13: Cryptographic functionality in JSSE
2, and using the secret key that the client sent to the server
in Message 8.
3.2.1 Core Classes
The JSSE may also integrate with JCE in order to use The core classes for JSSE are:
each others functionalities. However, the cryptographic
capabilities of JSSE are not available for use by other
applications. Here below there are two code examples (server o SocketFactory and ServerSocketFactory: These abstract
and client) using SSL to connect to each other using JSSE. classes are used to create sockets. They must be subclassed
by other factories, which create particular subclasses of
import java.io.*;
import javax.net.ssl.*;
sockets and thus provide a general framework for the
addition of public socket-level functionality.
. . .

int port = availablePortNumber; o SSLSocket and SSLServerSocket: These classes are


SSLServerSocket s;
subclasses of the standard Java java.net.Socket class. It
supports all of the standard socket methods and adds
try {
SSLServerSocketFactory sslSrvFact = additional methods specific to secure sockets. Instances of
(SSLServerSocketFactory)
SSLServerSocketFactory.getDefault();
this class encapsulate the SSLContext under which they
s =(SSLServerSocket)sslSrvFact.createServerSocket(port); were created. There are APIs to control the creation of
SSLSocket c = (SSLSocket)s.accept(); secure socket sessions for a socket instance but trust and
OutputStream out = c.getOutputStream();
key management are not directly exposed.
InputStream in = c.getInputStream();
o SSLSocketFactory and SSLServerSocketFactory: They
// Send messages to the client through
// the OutputStream act as factories for creating secure sockets. They are
//
//
Receive messages from the client
through the InputStream
abstract subclasses of javax.net.SocketFactory. They
} encapsulate the details of creating and initially configuring
catch (IOException e) { secure sockets. This includes authentication keys, peer
}
certificate validation, enabled cipher suites, etc.
The Server Code o SSLSession Interface: this represents a security context
import java.io.*;
negotiated between the two peers of an SSLSocket
import javax.net.ssl.*; connection. Once a session has been arranged, it can be
. . . shared by future SSLSockets connected between the same
int port = availablePortNumber;
two peers. The session contains the cipher suite which will
String host = "hostname"; be used for communications over a secure socket as well as
try { a non-authoritative hint as to the network address of the
SSLSocketFactory sslFact =
(SSLSocketFactory)SSLSocketFactory.getDefault();
remote peer, and management information such as the time
SSLSocket s = of creation and last use. A session also contains a shared
(SSLSocket)sslFact.createSocket(host, port);
master secret negotiated between the peers that is used to
OutputStream out = s.getOutputStream();
InputStream in = s.getInputStream();
create cryptographic keys for encrypting and guaranteeing
the integrity of the communications over an SSLSocket. The
// Send messages to the server through
// the OutputStream value of this master secret is known only to the underlying
//
//
Receive messages from the server
through the InputStream
secure socket implementation and is not exposed through
} the SSLSession API.
catch (IOException e) {
} o HttpsURLConnection: this class is similar to http, except
that it first establishes a secure channel via SSL/TLS
The Client Code sockets before requesting/receiving data.
javax.net.ssl.HttpsURLConnection extends the
java.net.HttpsURLConnection class, and adds support for
https-specific features.
o Support Classes and Interfaces: provided to support the o HandShakeCompletedEvent: the event
creation and initialization of SSLContext objects, which are communicated to a HandShakeCompletedListener
used to create SSLSocketFactory and upon completion of an SSL protocol handshake on
SSLServerSocketFactory objects. The support classes and a given SSLSocket connection.
interfaces are part of the javax.net.ssl package.
o X509Certificate: provides a standard way to
o SSLContext: an engine class for an implementation of a access the attributes of X.509 certificates.
secure socket protocol. An instance of this class acts as a
factory for SSL socket factories. An SSLContext holds all of The main packages of JSSE are:
the state information shared across all sockets created under
that context. For example, session state is associated with o javax.net
the SSLContext when it is negotiated through the handshake o Factories for creating sockets, server sockets, SSL
protocol by sockets created by socket factories provided by sockets, and SSL server sockets. Using socket
the context. These cached sessions can be reused and shared factories you can encapsulate socket creation and
by other sockets created under the same context. configuration behavior.
o javax.net.ssl
o TrustManager: it determines whether the presented
o SSL session management
authentication credentials should be trusted. If the
o Secure (SSL) sockets and server sockets.
credentials are not trusted, the connection will be
o Key and trust manager interfaces (including
terminated.
X.509-specific key and trust managers), and
o TrustManagerFactory: an engine class for a provider- factories for creating them.
based service that acts as a factory for one or more types of o javax.security.cert
TrustManager objects. o A public key certificate API compatible with JDK
1.1-based platforms.
o X509TrustManager Interface: it extends the general
TrustManager interface. This interface must be
implemented by a trust manager when using X.509-based 3.3 Java Authentication and
authentication. For more information on X.509, see Authorization Service
glossary.
o KeyManager: responsible for selecting the authentication This extension is used for two purposes: authentication and
credentials that will eventually be sent to the remote host. authorization of users. It provides the capability to determine
The relationship between TrustManagers and KeyManagers who is currently executing java code regardless of the code type
is that the first one determines whether the remote (applet, application, bean, etc). It also ensures that the Java code
authentication credentials (and thus the connection) should being executed in a JVM to have the access control rights or
be trusted. The latter one determines which authentication permissions required to do the actions performed. It provides
credentials to send to the remote host. flexible and scalable mechanisms for securing client- and
server-side Java applications.
o KeyManagerFactory: an engine class for a provider-based
service that acts as a factory for one or more types of Earlier Java security frameworks focused on protecting
KeyManager objects. the user from mobile code, based on the code' s origins and
o X509KeyManager Interface: it extends the general owner. JAAS however protects the system from users, based on
KeyManager interface. It must be implemented by a key who runs the code and their permissions. This pluggable,
manager for X.509-based authentication. stackable API lets you incorporate standard security
mechanisms like Solaris NIS (Network Information Services),
o Secondary Support Classes and Interfaces: support the Windows NT, LDAP (lightweight access directory protocol),
creation, use, and management of secure sockets. They are Kerberos, and others into your application in a consistent,
as follows: configurable way.
o SSLSessionContext Interface: a grouping of
SSLSessions associated with a single entity.
o SSLSessionBindingListener: an interface
implemented by objects which want to be notified
when they are being bound or unbound from an
SSLSession.
o SSLSessionBindingEvent: the event
communicated to an SSLSessionBindingListener
when it is bound or unbound from an SSLSession. Figure 14: JAAS Pluggable Authentication
o HandShakeCompletedListener Interface: an
interface implemented by any class which wants to JAAS authentication is performed in a pluggable
receive notification of the completion of an SSL fashion. This allows applications to remain separated from
protocol handshake on a given SSLSocket underlying authorization technologies. Updated authentication
connection. technologies can be plugged under the application without
requiring modifications to the application itself. Applications
enable the authentication process by instantiating a and credentials with a Subject object that represents the
LoginContext object, which in turn references a Configuration to subject being authenticated.
determine the authentication technology, or LoginModule(s), to 5 The LoginContext returns the authentication status to the
be used in performing the authentication. Typical LoginModules application.
may prompt for and verify a username and password. Others 6 If authentication succeeded, the application retrieves the
may read and verify a voice or fingerprint sample. This can be Subject from the LoginContext.
seen in the figure below:
Here below this sample code demonstrates what is
necessary to authenticate and logout a subject:

// let the LoginContext instantiate a new Subject


LoginContext lc = new LoginContext("entryFoo");
try {
// authenticate the Subject
lc.login();
System.out.println("authentication successful");

// get the authenticated Subject


Subject subject = lc.getSubject();

...

// all finished -- logout


lc.logout();
} catch (LoginException le) {
System.err.println("authentication unsuccessful: " +
le.getMessage());
}

The core classes and interfaces for authentication are:

o LoginContext: authentication class that provides the basic


methods used to authenticate subjects, and provides a way
Figure 15: JAAS authentication sequence diagram to develop an application independent of the underlying
authentication technology. It consults a Configuration to
determine the authentication services, or LoginModule(s),
3.3.1 Core Classes and Interfaces configured for a particular application. Therefore, different
LoginModules can be plugged in under an application
The core classes and interfaces for JAAS are (for authentication without requiring any modifications to the application itself.
and authorization): The methods in this class are:
o login(): performs login, a relatively complex step
o Subject: source of a request, which needs to be identified that invokes all LoginModules specified for this
and authenticated before authorizing it to access resources. configuration. If it succeeds, it creates an
It can be an entity or a service authenticated Subject. If it fails, it throws a
o Principals: can be associated with a subject if LoginException.
authentication n is successful. They represent the subject’s o getSubject(): returns the authenticated Subject.
identities.
o logout(): logs out the authenticated Subject and
o Credentials: An object that is verified when presented to removes its Principals and credentials.
the verifier in an authentication transaction. It can be any
class. Two interfaces are optional for credentials, the o LoginModule: interface that allows developers to
Refreshable and Destroyable. Credentials can be public, implement different kinds of authentication technologies
such as the name of the subject or a public key, or private that can be plugged in under an application. Some of these
like passwords or private keys. modules (implementations available in J2SE 1.4) can be:
o JndiLoginModule: verifies against a directory
service configured under JNDI (Java Naming and
3.3.1.1 Authentication Classes and interfaces: Directory Interface)
o Krb5LoginModule: authenticates using Kerberos
To authenticate a subject (user or service), the following steps protocols. See glossary for more information on
are performed: Kerberos.

1 An application instantiates a LoginContext. o NTLoginModule: uses the current user's NT


2 The LoginContext consults a Configuration to load all of the security information to authenticate
LoginModules configured for that application. o UnixLoginModule: uses the current user'
s Unix
3 The application invokes the LoginContext's login method. security information to authenticate
4 The login method invokes all of the loaded LoginModules.
Each LoginModule attempts to authenticate the subject. o CallbackHandler: used to obtain authentication
Upon success, LoginModules associate relevant Principals information from the user to the LoginModule. It either
gathers input from users (such as a password or smart card The GGS API is a standard defined by the IETF that
pin number) or supplies information to users (such as status proposes a generic interface for secure messages and
information). authentication. It was designed for the client/server architecture
and used for securely exchanging messages between
o Callback: defines the interface for callbacks.
communicating applications. The Java GSS-API contains the
o Authorization Classes: grants access control permissions Java bindings for the Generic Security Services Application
Program Interface (GSS-API) defined in RFC 2853. GSS-API
To make JAAS authorization take place, granting access control offers application programmers uniform access to security
permissions based not just on what code is running but also on services atop a variety of underlying security mechanisms,
who is running it, the following is required: including Kerberos.

1 The user must be authenticated, as described in the This standard provides confidentiality for the
LoginContext section. associated parties, message integrity and authentication. It is
2 The Subject that is the result of authentication must be supported by JAAS.
associated with an access control context, as described in
the Subject section.
3 Principal-based entries must be configured in the security
policy, as described below in the core classes section.

The core classes and interfaces for authorization are:

o Policy: an abstract class for representing the system-wide


access control policy.
o AuthPermission: encapsulates the basic permissions
required for JAAS. An AuthPermission contains a name
(also referred to as a "target name"). Figure 16: GSS Interfaces and Classes

o PrivateCredentialPermission: protects access to a


Subject's private credentials and provides one public 3.4.1 Core Classes
constructor:
The core classes for the GSS API are:
By providing an extensible model for authentication,
authorization of users and controlling permissions, this o GSSManagerFactory: factory responsible for instantiating
extension can provide the tools with the flexibility of creating GSSManagers.
customized login mechanisms, while at the same time using pre-
built modules that can be plugged into the application without o GSSManager: serves as a factory for other important GSS-
any side effect. API classes and also provides information about the
mechanisms that are supported. It can create instances of
classes implementing the following three GSS-API
3.4 GSS API – Generic Security interfaces: GSSName, GSSCredential, and GSSContext. It
Services API also has methods to query for the list of available
mechanisms and the nametypes that each mechanism
The GSS API is a generic API for doing client-server supports.
authentication. The motivation behind it is that every security
o GSSCredential: this interface encapsulates the GSS-API
system may have its own API and the effort involved with
credentials for an entity. A credential contains all the
adding different security systems to applications is extremely
necessary cryptographic information to enable the creation
difficult with the variance between security APIs. However,
of a context on behalf of the entity that it represents. It may
with a common API, application vendors could write to the
contain multiple, distinct, mechanism specific credential
generic API and it could work with any number of security
elements, each containing information for a specific
systems.
security mechanism, but all referring to the same entity. A
credential may be used to perform context initiation,
The relevant standards for GSS API include:
acceptance, or both.
o GSSContext: this interface encapsulates the GSS-API
o RFC 2743 - Generic Security Services Application Program
security context and provides the security services that are
Interface Version 2, Update 1.
available over the context. Security contexts are established
http://www.ietf.org/rfc/rfc2743.txt
between peers using locally acquired credentials. Multiple
o RFC 1509 - Generic Security Service API: C-bindings contexts may exist simultaneously between a pair of peers,
http://www.ietf.org/rfc/rfc1509.txt using the same or different set of credentials. GSS-API
functions in a manner independent of the underlying
o RFC 1964 - The Kerberos Version 5 GSS-API Mechanism. transport protocol and depends on its calling application to
http://www.ietf.org/rfc/rfc1964.txt transport the tokens that are generated by the security
context between the peers.
3.5 JSR 28 - SASL – Simple o JSR 219 – Foundation Profile 1.1
Authentication and Secure Layer
4.1 J2ME/ MIDP 2.0/ CLDC 1.1
It is defined as an authentication service for network protocols.
Security has always been a primary focus of MIDP. In
It allows LDAP clients to authenticate with an LDAP server and
MIDP 1.0, however, security is mostly addressed by removing
provides security for the data transmitted with this protocol. It
the ability to perform sensitive operations. MIDP 2.0 comes
follows the pluggable security provider approach and it is
with enhanced security features that open up more capabilities
defined by RFC 2222.
of devices to developers without compromising security. It
includes enhanced mobile code and application security by the
The JSR 28 proposes a standard API and framework
means of a defined security manager, security domains, MIDlet
for the Java programming language to implement the SASL
signature capability and provisioning process.
standard. As stated in the JSR definition, it specifies a
challenge-response protocol in which data is exchanged between
the client and the server for the purposes of authentication and 4.1.1 MIDlet Permissions
(optional) establishment of a security layer on which to carry on
subsequent communications. See glossary for more information The figure below demonstrates an attempt to connect
regarding the challenge-response protocol. through HTTP. If the client application, in this case the MIDlet,
is allowed to access this channel, it will connect and receive an
answer in HTML. Otherwise it will throw a security exception.
4 Security in the J2ME The source code after the figure demonstrates this figure.
Platform
This section provides security features inside the J2ME
platform. Due to the different markets and architecture, these
have been provided differently throughout the platforms based
on their characteristics, limitations, application domain, etc. At
the J2ME platform, we may have three security domains
defined: the one set by MIDP 2.0/CLDC 1.1 standards, another
set by SATSA (Security and Trust Services API) for JavaCards
and a last one set by JSR 219. Figure 18: MIDP/CLDC Concept of Permissions: HTTP
access allowed or restricted.
The figure below demonstrates the differences between
the two patforms: J2ME and JavaCard. They are different in
import java.io.*;
both the VM implementation and their core APIs or
frameworks. The security extensions therefore will not be import javax.microedition.io.*;
import javax.microedition.lcdui.*;
identical, but some similarities can be found, for example, in import javax.microedition.midlet.*;

cases where one is a subset of the other. public class HTTPMIDlet


extends MIDlet
implements CommandListener, Runnable {
private Display mDisplay;
private Form mMainScreen;

public HTTPMIDlet() {
mMainScreen = new Form("HTTPMIDlet");
mMainScreen.append(
"Press OK to create an HTTP connection.");

Command exitCommand =
new Command("Exit", Command.EXIT, 0);
Command okCommand =
new Command("OK", Command.OK, 0);
mMainScreen.addCommand(exitCommand);
mMainScreen.addCommand(okCommand);
mMainScreen.setCommandListener(this);
}

public void startApp() {


if (mDisplay == null)
mDisplay = Display.getDisplay(this);

mDisplay.setCurrent(mMainScreen);
}

public void pauseApp() {


}

public void destroyApp(boolean unconditional) {}


Figure 17: J2ME and JavaCard Platforms
// CommandListener method

public void commandAction(Command c, Displayable s) {


The security services that will be discussed in this if (c.getCommandType() == Command.EXIT)
notifyDestroyed();
section are: else if (c.getCommandType() == Command.BACK)
mDisplay.setCurrent(mMainScreen);
else if (c.getCommandType() == Command.OK) {
o J2ME/ MIDP 2.0/CLDC 1.1 // Put up a wait screen.
Form waitForm = new Form("Connecting...");
o SATSA – Security and Trust Services API for J2ME mDisplay.setCurrent(waitForm);
// Make the connection
Thread t = new Thread(this);
the Wireless Toolkit 2.0, the developer may choose the security
t.start(); domain designed for the application, as shown below.
}
}

// Runnable method

public void run() {


String url = "http://wireless.java.sun.com/";

Form resultsForm = new Form("Results");


Command backCommand =
new Command("Back", Command.BACK, 0);
resultsForm.addCommand(backCommand);
resultsForm.setCommandListener(this);

HttpConnection hc = null; Figure 19: Selecting a protection domain in WTK 2.0


InputStream in = null;

try {
// Now make a connection to the server.
hc = (HttpConnection)Connector.open(url);
All Java security mechanisms, and particularly the
sandbox concept, implicitly require a MIDlet verifier as a
// Retrieve the response.
in = hc.openInputStream(); foundation very similar to the concept seen in J2SE (presented
int length = 256;
in section 2 of this article), however simplified. Without this
byte[] raw = new byte[length]; verification no security policy can be enforced. The code below
int readLength = in.read(raw);
demonstrates how MIDlet permissions can be defined in the
String message = new String(raw, 0, readLength);
resultsForm.append(message);
application descriptor (JAD file).
}
catch (Exception e) {
resultsForm.append( MIDlet-Permissions: javax.microedition.io.Connector.http
new StringItem("Exception: ", e.toString())); MIDlet-Permissions-opt: javax.microedition.io.Connector.socket
}
finally {
if (in != null) {
try { in.close(); }
catch (IOException ioe) {} 4.1.2 Security Domains
}
if (hc != null) {
try { hc.close(); }
catch (IOException ioe) {}
Downloaded code can be pretty dangerous, especially
} when you don' t know the origin and the owner. Even though
}
mDisplay.setCurrent(resultsForm); MIDlets, running on a virtual machine, are intrinsically a lot
}
}
safer than binary code, there are still some risks, for example:

• A downloaded MIDlet could make undesired network


MIDP 2.0/CLDC 1.1 security is based on the concept connections, connections that cost the user money;
of permissions. To make any type of network connection, a • This MIDlet could also try to collect information and send it
MIDlet must have an appropriate permission. It introduces the to a server for unauthorized use for example.
notion of trusted/untrusted applets which allows the developer to
define restrictions to resources for each MIDlet. To obtain A MIDP device gives its owner a lot of flexibility in
privileged access, a MIDlet must be assigned to specific pre- choosing games and applications, but with that flexibility the
defined domains, and properly signed. In order to be risk of running code whose origins and motivations may not
downloaded, installed and granted associated permissions, the well be know still exist.
device must successfully verify the signature. A MIDlet may
request permissions by declaring them in the application Protection domains can be configured to make it safer
descriptor using for example MIDlet-Permissions. This however for users to run downloaded MIDlets. The MIDP specification is
doesn’t mean that all permissions will be granted to the MIDlet. deliberately open about how protection domains should be
defined. It leaves a lot to the implementor' s discretion: the
Some security permissions may be: number of protection domains that will be present and how they
will be defined. The specification does, however, suggest a
• javax.microedition.io.Connector.http protection domain based on cryptographic signatures and
• javax.microedition.io.Connector.socket certificates for the application. The idea is that the carrier, or the
• javax.microedition.io.Connector.https software developer, creates a signing-key pair and obtains a
• javax.microedition.io.Connector.ssl certificate from a recognized certificate authority. The carrier or
developer computes a signature of the MIDlet suite JAR, then
• javax.microedition.io.Connector.datagram
places that signature and the corresponding certificate in the
• javax.microedition.io.Connector.serversocket
application descriptor (JAD file).
• javax.microedition.io.Connector.datagramreceiver
• javax.microedition.io.Connector.comm A signed MIDlet suite assures the user that the contents
• javax.microedition.io.PushRegistry of the MIDlet suite have not been tampered (see glossary) with
and that the MIDlet suite comes from an identifiable (and thus
By default MIDP applications are not trusted, and are legally accountable) source. The MIDP implementation on the
assigned to untrusted domains that prevent access to any device can verify the identity of the developer by verifying the
privileged functionality. These untrusted Java MIDlets are developer' s signature. It can use the developer's public key to
executed inside a small “sandbox”. Trusted midlets are also verify the integrity of the MIDlet suite itself.
limited by permissions and cannot access ungranted APIs. For
The J2ME Wireless Toolkit easily allows the developer limitations. Most modern cryptographic packages today
to specify the permissions that a MIDlet suite requires. MIDlets consume several MBs of storage space. There must be a
are sorted into buckets called protection domains based on their balance between features and footprint.
credentials. A protection domain is a collection of permissions
o Support to various algorithms: the idea would to offer
and a set of criteria for entry into the domain. The MIDP 2.0
flexible security schemes, with the ability to select from a
specification includes suggestions for signing MIDlet suites
range of algorithms. They must include the following:
cryptographically; this scheme is implemented in the J2ME
Wireless Toolkit, which includes simple tools for creating a key o Symmetric key encryption
pair and signing a MIDlet suite.
o Public key encryption
MIDP 2.0 security model therefore provides a pre- o Digital signatures
verifier and a simplified Sandbox model. It constitutes a very
simplified class verifier, with no access to native code (inside o Password-based encryption
KVM), impossibility to overload the class loader, restricted o Easy Key Management: matching and identifying keys
access to MIDP and CLDC APIs only and a few features in with different algorithms on both communication ends is
J2SE that were eliminated: quite complex and tool slow on mobile devices, specifically
mentioning the public key cryptography. Keys may have to
o JNI (KNI as subset only) be generated at the server and transported to the device
o Class loaders that can be defined by the user safely. APIs to provide such features must exist.
o Reflection
o Weak referencing o Quick correction of bugs found in the security
architecture: bugs must be fixed rather fast in order to
guarantee the integrity of the security services in the API
o Etc.
4.1.4 Third Party Security APIs
This necessity has caused some interest for third party
development of security framework APIs for this platform.
Some of them are:

o Bouncy Castle Lightweight API: it begun as a community


attempt to implement a free, clean-room, open source JCE
provider. They have developed their own lightweight API
to be wrapped into JCE provider classes. It supports a great
Figure 20: Signing a MIDlet Suite using WTK 2.0
deal of algorithms, but unfortunately is has a large footprint.
It is for free.
4.1.3 HTTPS o Phaos Technology Micro Foundation Toolkit:
implemented by a Java and XML security solution provider,
HTTPS support has been made mandatory for data this company provides toolkits for secure XML Java APIs,
communications. It is the most widely used data security J2ME lightweight crypto APIs and one of the first
protocol in J2ME applications. implementations of the SSL protocol on J2ME/CLDC.
However, future mobile applications require more o NTRU Neo for Java Toolkit: developed by four math
flexible, customizable and better optimized security solutions. professors at Brown University, this toolkit includes an
HTTPS, SSL and TLS are connection based security protocols. encryption algorithm (NTRUEncrypt) and a signature
The main focus is to provide security through communication algorithm (NTRUSign). Their algorithms are published and
channels and by this secure everything that passes through these are soon to become IEEE and IETF standards.
channels. o B3 Security: developed by a company that specializes in
developing new lightweight security infrastructures that
The inflexibility for special security requirements minimize the overhead associated with public key
makes the HTTPS a troublesome feature. There may be cryptography. Its products are B3 Tamper Detection and
requirements which require the platform to be customized, such Digital Signature (B3Sig) SDK and B3 End-to-End
as: (B3E2E) Security SDK, both being available for J2ME.

o Processing Speed: mobile devices must be responsive to There are also APIs developed by MIDP device
the user. However they have slow CPUs and Java itself is vendors, such as Motorola, that provide device-specific
not as fast as desired. When there is a demand for cryptographic extensions. They take the advantage of using
cryptographic tasks, specifically public key algorithms, for native cryptography libraries and special features in hardware.
J2ME devices is a great challenge. For this reason, they tend to have good device performance. The
o Small footprint: there is a great demand for cryptographic only problem is the portability of applications to other devices,
packages that are compatible to the J2ME memory causing J2ME fragmentation and the loss of one of Java’s
greatest advantages. One way to avoid such fragmentation and
still take advantage of native performance is to develop standard
J2ME cryptography API specifications and allow device
vendors to plug in their own implementations. The JSR 177
provides J2ME applications with APIs for security and trust
services. This will be discussed in better detail in the next
section.

4.2 SATSA – Security and Trust


Services API for J2ME

The JavaCard technology depends fully on the SATSA


specification (JSR 177) for its security infrastructure. This JSR
defines the Security and Trust Services APIs to permit secure Figure 21: MIDP device communicating with a JavaCard
access to smartcards by giving cryptographic capacities for via APDUs.
applications in small devices, including J2ME MIDP 2.0/CLDC
1.1 devices. It is composed of four distinct APIs:

o APDU – Application Protocol Data Unit 4.2.2 JCRMI – JavaCard Remote Method
o JCRMI – JavaCard Remote Method Invocation Protocol Invocation Protocol
o Crypto – Cryptography Package
o PKI – Public Key Infrastructure This package enables the communication between MIDP
devices and a smart card using the JCRMI protocol. It is an
4.2.1 APDU – Application Protocol Data Unit alternative method for the communication with smartcard
applications with support to distributed objects framework. It
This standard enables MIDP applications to communicate with a contains a subset of J2SE RMI. It comprises three
smart card using a protocol based on Application Protocol Data classes/Interfaces as shown in the figure below.
Units (APDUs). This protocol is defined by ISO 7816-4. An
APDU is a short message represented by bytes. SATSA-APDU
enables your application to exchange APDU messages with a
card application. SATSA APDU has been implemented as an
extension of the Generic Connection Framework.

An example of opening a APDU Connection between a MIDlet


and a JavaCard: Figure 22: JCRMI objects and interface
Their responsibilities are:
String purseURL = "apdu:0;target=a0.00.00.00.62.03.01.0c.02.01";
APDUConnection purseConnection;
purseConnection = (APDUConnection)Connector.open(purseURL);
o Remote interface: includes the methods to be called on the
remote object.
The locator string begins with “apdu” and specifies the o Stub class: implements the remote interface.
slot number and the card application identifier. By retrieving the o Client code: opens a connection and calls methods on the
value of the microedition.smartcardslots system property, the remote object.
list of available slots in the card can be obtained. For the
exchange of messages or APDUs, an array of bytes can be sent The connection is similar when using the APDU API,
and also be received for response. This response is synchronous, except that it uses the JavaCardRMIConnection interface for
meaning that the application will only continue after it receives RMI to communicate. It receives an object which allows
the data back from the other end. communication between the two ends.

The source code below shows the exchange of APDU messages 4.2.3 Crypto – Cryptography Package
between a MIDlet and a JavaCard:
This is a generic cryptography API that provides features such
byte[] apdu = {
as message digests, digital signatures, and ciphers for smart
(byte)0x00, (byte)0x20, (byte)0x00, (byte)0x82, (byte)0x04, cards. It is a subset of the J2SE JCE (see section 3.1). It
(byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x00
}; encapsulates cryptographic ciphers in the javax.crypto.Cipher
byte[] response = purseConnection.exchangeAPDU(apdu);
class. The example below demonstrates the usage of the class
Cypher.

At the example below, this code can be used for


ciphering data with DES algorithm. The interface is pretty
similar to what has been defined in JCE. In fact this is a subset
of it.
uses this and its own secret key as input to its cryptographic
algorithm. The output of the calculation is transmitted to the
byte[] keyBits = {
system. The system compares the value received with the
(byte) 0x2b, (byte) 0x7e, (byte) 0x15, (byte) 0x16, one calculated itself. If the two match, the card is
(byte) 0x28, (byte) 0xae, (byte) 0xd2, (byte) 0xa6
}; considered to be genuine. Similar procedure is used for
byte[] plaintext = {
(byte)0x01, (byte)0x23, (byte)0x45, authentication of the external world to the card.
(byte)0x67, (byte)0x89, (byte)0xab, (byte)0xcd, (byte)0xef
}; o Data Integrity: many situations demand data integrity, for
byte[] ciphertext = new byte[8];
example, in electronic monetary transaction or email
SecretKeySpec key = new SecretKeySpec(keyBits, 0, keyBits.length,
"DES");
communications, it is important to ensure the message
Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding"); content remains unaltered during and after each
cipher.init(Cipher.ENCRYPT_MODE, key);
int count = cipher.doFinal(plaintext, 0, plaintext.length, transmission. One method of achieving data integrity during
ciphertext, 0);
transmission is by using the message authentication code
(MAC). MAC is the cryptographic checksum, calculated
At the algorithm above, the secret key is created along based on the secret key, the data and a random number
with the cipher object. The initialization of the cipher is done by using Data Encryption Standard (DES). It is appended to
passing the secret key as parameter, returning by reference the the end of the original data and is transmitted to the
ciphered data in the doFinal() method. In the example below the recipient, together with the random number. The recipient
cipher object is used for encrypting data using the public key of verifies the received message by generating the MAC using
an RSA key pair. It demonstrates the use of the KeyFactory the same secret key, the received random number and the
class to extract a public key from an encoded representation. received data by the same computation. If the MAC
matches with the one received, it is proven that the data was
not modified during the transmission.
byte[] publicKeyBits;
// Assign publicKeyBits here.
byte[] plaintext = "This is just an example".getBytes(); o Data Confidentiality: when data is transmitted through an
byte[] ciphertext = new byte[128];
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBits);
insecure network, it is important that confidential data like
KeyFactory kf = KeyFactory.getInstance("RSA"); secret cryptographic key is not disclosed to unauthorized
PublicKey publicKey = keyFactory.generatePublic(keySpec);
Cipher cipher = Cipher.getInstance("RSA"); individuals. To ensure data confidentiality, the card’s
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int count = cipher.doFinal(plaintext, 0, plaintext.length,
microprocessor is capable of encrypting the data internally
ciphertext, 0); before it is transmitted. In general, the two types of
cryptographic algorithms are supported (secret key and
public key cryptography). A Java smart card provides a
4.2.4 PKI – Public Key Infrastructure secure place to create and store these cryptographic keys.
Secret key cryptography is simple and fast but the main
This API allows applications to use a smartcard for digital data drawback of the system is that the two parties must ensure
signatures and certificate management for end users. PKI the secret key is exchanged securely. Public key
associates cryptographic keys with people, businesses, or other cryptography, although more complicated, can avoid this
objects. It is based on standard cryptographic signatures and problem.
certificates. It provides:
o Digital Signature: digital signatures address the integrity,
o Key and certificate management authentication and non-repudiation requirements. A digital
o Digital Signature of data signature is the encrypted information generated using the
o Authentication private key of the sender. The receiver can perform the
reverse process using the associated public key and confirm
the identity of the sender. It is analogous to a hand written
4.2.5 JavaCard Security Features signature. Today, a Java smart card used for security
purposes has a crypto-coprocessor capable of public key
Some of JavaCard security features are:
cryptography calculation using up to 1024 bit keys. When
this is used with the on-board random generator, the card
o Card owner verification: this is done via CHV PIN can perform full public-key generation, digital signatures,
(Personal Identification Number) encrypted. Before access and authentication internally. This capability guarantees
to the data and functions are allowed, the cardholder has to that the secret key will never be known outside the smart
prove him to be genuine. Cardholder verification is card and contributes to the overall security of the system.
performed using a CHV PIN (Personal Identification There are, unfortunately, several ways of breaking the
Number) which is known only to the owner of the card. security in smart card. For example, if the device is
Access is granted only if the comparison is positive. This tampered.
PIN stored is encrypted in some cards to provide greater
security.
o Authentication: at the beginning of any session there is
authentication. This is achieved using a challenge and
response procedure employing cryptographic algorithms
such as Data Encryption Standard (DES) or public key
cryptography. To authenticate the card, the system
challenges the card by sending a random number. The card
developers. There are off course security breaches in any
platform. The importance is for it to have an effective support
team ready to fix any breaches that anyone may find.

Besides all extensions and features presented in this


document, there are also other security packages specific to their
application domains. For example for Web Services, the Web
Service Message Security APIs (JSR 183) proposes to enable
applications to construct and exchange secure SOAP messages.
Also for RMI, the RMI Security API for J2SE defines a high
level API for network security in RMI, covering basic security
mechanisms such as authentication, confidentiality and integrity.
Figure 23 : SATSA Standards on the move. The XML Digital signature APIs (JSR 105) also define and
incorporate a standard set of high-level implementation-
In summary, APDU and JCRMI standards are used for independent APIs for XML digital signatures services. Digital
general message exchanges between the mobile device (a cell encryption is also included in JSR 106 which aims to define a
phone) and a JavaCard. The difference is how these messages standard set of APIs for XML digital encryption services.
are being transferred, whether working with arrays of bits or
invoking remote objects. The PKI package offers authentication Focusing at the J2ME platform, there is a great demand
by applying a “challenge-response” protocol to guarantee the for this platform to deliver security solutions that are fast and
identity of, in this case, a JavaCard owner. It is up to the mobile efficient, taking into account all limitations that J2ME devices
device to compute message digests, verify digital signatures impose. The evolution of these devices may be a solution
from entities and encrypt/decrypt data. This last responsibility is however, as they gain more processing power, more memory
quite resource demanding for the mobile, therefore and better energy consumption. There are already J2ME devices
demonstrating the importance of the development of efficient that are crossing the border from CLDC to CDC, thus enabling
security APIs for J2ME MIDP2/CLDC 1.1 devices. applications to have access to security features already available
to the J2SE Platform, for example in JSR 219 [8]. It is also
important to note the need to define and follow standard security
APIs in the mobile world in order for Java applications
4.3 JSR 219 – Foundation Profile 1.1 demanding security to be fully runnable across any device on
that same platform, thus maintaining on of Java’s greatest
J2ME devices in the CDC range will soon receive a new profile advantages.
that is being defined by the JCP. It provides updates based on
J2SE 1.4 to the existing CDC (JSR 36) core. From all the
updates being planned, some security packages from Java 1.4
will be added into the CDC APIs. J2ME Foundation Profile 1.0
(JSR 46) does not currently include certain J2SE, v1.4 features
that are required by device manufacturers and application
developers. It proposes the addition of several security
packages, including partial support to JCE, JAAS and JSSE, as
it can be shown in the figure below.

Figure 25: The overall picture (J2SE, J2EE)


All security extensions are cooperating mutually in
providing a safe environment for each platform. Some of these
Figure 24: Comparison between J2SE and J2ME features apply only to specific platforms, while others are
configurations in API coverage. generic and can be used by any of the Java Platforms. Even in
the J2ME, subsets of the extensions shown above have been
made available for developers and their applications.
5 Conclusion
It can be said that the Java Platform contains a quite robust
security model. It is customizable, extendable, well maintenance
supported and it supports a great deal of algorithms. From the
starting point of preparing the Java code to compile up to the
usage of core security APIs, Java provides many features that
guarantee a secure environment for programs, users and
a cryptographic hash of the data and then encrypting the
hash with the sender'
s private key.
• Encryption and Decryption: the process of taking data
(called cleartext) and a short string (a key), and producing
data (ciphertext) meaningless to a third-party who does not
know the key. Decryption is the inverse process: that of
taking ciphertext and a short key string, and producing
cleartext.
• Password-Based Encryption: Password-Based Encryption
(PBE) derives an encryption key from a password. In order
to make the task of getting from password to key very time-
consuming for an attacker, most PBE implementations will
Figure 26: Security Extensions for J2EE mix in a random number, known as a salt, to create the key.

As it can be seen in the above picture, many of the • Cipher: Encryption and decryption are done using a cipher.
security APIs and extensions are important to the J2EE Platform A cipher is an object capable of carrying out encryption and
services. It can be said that J2EE takes full advantage of these decryption according to an encryption scheme (algorithm).
APIs to guarantee security in its operations. It takes regular data, the plaintext, and converts it into an
unreadable form, called ciphertext. This process is
encryption. The cipher can also decrypt ciphertext to restore
the original plaintext, regarded as decryption.
• Key Agreement: Key agreement is a protocol by which 2
or more parties can establish the same cryptographic keys,
without having to exchange any secret information.
• Message Authentication Code: A Message Authentication
Code (MAC) provides a way to check the integrity of
information transmitted over or stored in an unreliable
medium, based on a secret key. Typically, message
authentication codes are used between two parties that share
a secret key in order to validate information transmitted
between these parties. A MAC mechanism that is based on
cryptographic hash functions is referred to as HMAC.
Figure 27: Security in the JRE HMAC can be used with any cryptographic hash function,
e.g., MD5 or SHA-1, in combination with a secret shared
For the Java Runtime Environment, some services
key. HMAC is specified in RFC 2104.
utilize the security APIs available in the platform to enforce its
security model and guarantee a safe environment for the Java • Message Digest: The representation of text in the form of a
code. single string of digits, created using a formula called a one-
way hash function. Encrypting a message digest with a
As new application domains come to surface in the private key creates a digital signature, which is an electronic
Java Platform, new security requirements will eventually be means of authentication.
added into the APIs in order to fulfill their demands. Existing
domains may also request more security features, as trustability • One-Way Hash Function: An algorithm that turns
becomes crucial for certain types of applications. messages or text into a fixed string of digits, usually for
security or data management purposes. The "one way"
means that it's nearly impossible to derive the original text
Glossary from the string. A one-way hash function is used to create
digital signatures, which in turn identify and authenticate
• Authentication: the process of confirming the identity of a
the sender and message of a digitally distributed message.
party with whom one is communicating.
• Public Key Encryption: A cryptographic system that uses
• Certificate: a digitally signed statement vouching for the
two keys -- a public key known to everyone and a private or
identity and public key of an entity (person, company, etc.).
secret key known only to the recipient of the message.
Certificates can either be self-signed or issued by a
When John wants to send a secure message to Jane, he uses
Certification Authority (CA). Certification Authorities are
Jane's public key to encrypt the message. Jane then uses her
entities that are trusted to issue valid certificates for other
private key to decrypt it. An important element to the
entities.
public key system is that the public and private keys are
• Digital Signature: the digital equivalent of a handwritten related in such a way that only the public key can be used to
signature. It is used to ensure that data transmitted over a encrypt messages and only the corresponding private key
network was sent by whoever claims to have sent it and that can be used to decrypt them. Moreover, it is virtually
the data has not been modified in transit. For example, an impossible to deduce the private key if you know the public
RSA-based digital signature is calculated by first computing key. Public-key systems, such as Pretty Good Privacy
(PGP), are becoming popular for transmitting information
via the Internet. They are extremely secure and relatively into the smart card. The smart card then displays a new
simple to use. The only difficulty with public-key systems code (the response) that the user can present to log in.
is that you need to know the recipient' s public key to
encrypt a message for him or her. What' s needed, therefore, • Public Key Certificate: A public key certificate can be
is a global registry of public keys, which is one of the thought of as the digital equivalent of a passport. It is issued
promises of the new LDAP technology. Public key by a trusted organization and provides identification for the
cryptography was invented in 1976 by Whitfield Diffie and bearer. A trusted organization that issues public key
Martin Hellman. For this reason, it is sometime called certificates is known as a certificate authority (CA). The CA
Diffie-Hellman encryption. It is also called asymmetric can be likened to a notary public. To obtain a certificate
encryption because it uses two keys instead of one key from a CA, one must provide proof of identity. Once the
(symmetric encryption). CA is confident that the applicant represents the
organization it says it represents, the CA signs the
• Private Key Encryption: A type of encryption where the certificate attesting to the validity of the information
same key is used to encrypt and decrypt the message. This contained within the certificate.
differs from asymmetric (or public-key) encryption, which
uses one key to encrypt a message and another to decrypt • Tampering: a breach of communication security in which
the message. information in transit is changed or replaced and then sent
on to the recipient.
• LDAP: Short for Lightweight Directory Access Protocol, a
set of protocols for accessing information directories.
LDAP is based on the standards contained within the X.500
References
standard, but is significantly simpler. And unlike X.500,
LDAP supports TCP/IP, which is necessary for any type of [1] Java Security, Second Edition, Scott Oaks, May 2001
Internet access. Because it' s a simpler version of X.500, [2] Java Cryptography Extension Reference Guide, Sun Microsystems
LDAP is sometimes called X.500-lite. Although not yet http://java.sun.com/j2se/1.4.2/docs/guide/security/jce/JCERefGuide.h
widely implemented, LDAP should eventually make it tml
possible for almost any application running on virtually any
[3] Java Secure Sockets Extension Reference Guide, Sun Microsystems
computer platform to obtain directory information, such as http://java.sun.com/j2se/1.4.2/docs/guide/security/jsse/JSSERefGuide
email addresses and public keys. Because LDAP is an open .html
protocol, applications need not worry about the type of
server hosting the directory. [4] Java Authentication and Authorization Service Reference Guide, Sun
Microsystems
• X.509: A widely used standard for defining digital http://java.sun.com/j2se/1.4.2/docs/guide/security/jaas/JAASRefGuid
e.html
certificates. X.509 is actually an ITU Recommendation,
which means that it has not yet been officially defined or [5] SATSA Developer’s Guide and Reference Implementation 1.0, Sun
approved for standardized usage. As a result, companies Microsystems
have implemented the standard in different ways. For http://java.sun.com/j2me/docs/satsa-dg/
example, both Netscape and Microsoft use X.509 [6] Secure Your Sockets with JSSE, Jamie Jaworski, March 2001,
certificates to implement SSL in their Web servers and OnJava
browsers. But an X.509 Certificate generated by Netscape http://www.onjava.com/lpt/a/811
may not be readable by Microsoft products, and vice versa.
[7] MIDP Application Security 1: Design Concerns and Cryptography,
• Kerberos: An authentication system developed at the Jonathan Knudsen
September 2002,
Massachusetts Institute of Technology (MIT). Kerberos is http://developers.sun.com/techtopics/mobility/midp/articles/security1
designed to enable two parties to exchange private
information across an otherwise open network. It works by [8] JSR 219 – Foundation Profile 1.1
assigning a unique key, called a ticket, to each user that logs http://www.jcp.org/en/jsr/detail?id=219
on to the network. The ticket is then embedded in messages [9] JSR 177 – Security and Trust Services API for J2ME
to identify the sender of the message. http://www.jcp.org/en/jsr/detail?id=177
• RFC: The name of the result and the process for creating a [10] JSR 28 – Java SASL Specification
standard on the Internet. New standards are proposed and http://www.jcp.org/en/jsr/detail?id=28
published on line, as a Request For Comments. The Internet
[11] JSR 72 – Generic Security Services API
Engineering Task Force is a consensus-building body that http://www.jcp.org/en/jsr/detail?id=72
facilitates discussion, and eventually a new standard is
established, but the reference number/name for the standard [12] The Java Virtual Machine Specification, Second Edition
retains the acronym RFC, e.g. the official standard for e- http://java.sun.com/docs/books/vmspec/2nd-
edition/html/VMSpecTOC.doc.html
mail is RFC 822.
• Challenge-response Protocol: A challenge-response
protocol is a common authentication technique whereby an
individual is prompted (the challenge) to provide some
private information (the response). Most security systems
that rely on smart cards are based on challenge-response. A
user is given a code (the challenge) which he or she enters

Das könnte Ihnen auch gefallen