Professional Documents
Culture Documents
CNS05P07A
Web Secure
TRAINING FOR
INFORMATION PROCESSING
NOTES
All products, names and services used in this book may be trademarks or registered
trademarks of their respective owners.
No part of this text book may be copied or reproduced in any way and by any means
without the permission of the copyright holder .
Contents
Objectives ........................................................................................................... 2
Contents ............................................................................................................... 3
ii
1-1
1-2
Tapping
User Application
Server
Alteration
Malicious
Attacker user
Transactions taking place via open networks such as the Internet are always at risk. There are
cases of network tapping where a attacker eavesdrops on the data exchanged on the network
and where a attacker alters data on a server in order to sneak hazardous programs into the
server.
With the explosive increase of Internet usage, the risk is growing rapidly. It is thus
particularly necessary to take security into account when designing systems involving Web
applications.
1-3
Encrypted Encrypted
data communication
Detection of
alteration
Tapping
User Application
Server
Sophisticated Alteration
authentication
processing Malicious
Malicious user
user
1-4
JAVA
Java comes with various security functions as standard. Many of these functions used to be
provided as optional packages at first, but they have been incorporated in the standard class
libraries as standard functions since Java 1.4.
Security Manager, which uses a security model called sandbox, controls access to computer
resources such as hard disks etc.
JCE (Java Cryptography Extension) and JSSE (Java Secure Socket Extension) are libraries
that perform encryption processing. JCE can implement message encryption and unique
encryption algorithms. JSSE can encrypt socket-based communication such as HTTPS.
JAAS provides a function to perform authentication using user-specific information such as
ID and password and allows central management of the authentication processing, including
when multiple applications are involved.
Keytool, jarsigner and other tools allow appending signatures to JAR files created using
X.509 certification processing. Under normal circumstances, certificates are issued by third
party organizations that conduct fair verification; it is possible to heighten the reliability and
safety of programs by appending signatures to data transferred via networks.
1-5
Access
Applet etc. Various resources
restriction
Java Download Sandbox
program
Java
program
Remote code
File system
Java
program
Local code JVM
(Java Virtual Machine)
Network
The Java runtime environment JVM implements a security model called sandbox. The
Sandbox model restricts all access to various resources on the computers on which they run,
such as the local file system and network resources when executing remote code such as
Applets and Java programs downloaded from the Internet.
That is, it permits local code located on the computer itself to access resources as reliable
code, but only permits remote code to access a strictly limited set of resources on the system,
as the remote code cannot be considered reliable.
1-6
Java Domain A
Class
program
Loader
Domain B File system
Java Security
program Manager
Domain C
Security
Policy Network
In Java2, the security model has been improved; security processing is now performed at
execution of all programs, not only for remote code, but also for local code.
When JVM is launched, the data of the Security Policy file is read and stored in the Security
Manager object first. The Security Policy file specifies information concerning access rights,
including access permission to various resources in units called protection domains. Protection
domains refer to specifications of certain access rights, and all classes are executed under one
of these protection domains. The Security Policy file is located at
JRE_HOME/lib/security/java.policy.
ClassLoader is a class included in the java.lang package; it is used when reading class
definition data from the file system or other sources. When a class is read, Security Manager
determines the protection domain, whereby its access rights to various resources are
determined.
Local code is now subjected to the security control, but access to various resources are
granted as standard for the domain of local code.
1-7
Web
server Web
Response application
User Program
impersonation, substitution,
spoofing etc. rewriting
Various security measures must be taken for Web applications that are made available to the
public via the Internet and other open networks used by an unspecified number of users.
・When exchanging personal information and other important information, the communicated
data may be tapped on open networks.
・In the majority of cases, Web applications perform authentication processing to identify
users, but attackers may impersonate or spoof users.
・There is a risk that attackers may substitute or alter programs of Web applications.
1-8
1-9
Web container
Web browser Encryption
HTTPS Web
Server Web
application
Request
Public key response Private key
By using SSL (Secure Socket Layer), it is possible to encrypt communication between a Web
browser and a Web server. The protocol that encrypts HTTP using SSL technologies is called
HTTPS.
In the HTTP protocol, the POST/GET parameters exchanged as part of requests to a Web
server and responses from the Web server are streamed via the network as is; thus, if the
network is tapped, the data may be stolen. HTTPS, on the other hand, encrypts all transactions
with the Web server; thus, even if the network is tapped by a attacker, it is difficult to restore
the data.
In HTTPS, the client uses the public key of the server implemented in the Web browser to
securely transfer a secret key used for the actual encrypted communication.
1-10
Web
Web application
application
Authentication Web
Web browser processing Web browser application
Web Authentication
Authentication application processing
processing
User database
User database
1-11
Download Digital
Java application certificate
When using applets in Web applications or when using Java Web Start to execute Java
applications on users’ computers, it is possible to append digital signatures to JAR files in
order to guarantee that the programs have not been tampered with.
Users can confirm the information about the provider of a program by checking the signature
before executing the program. If the program was tampered with by a attacker, the fact can be
detected by checking the signature. Java generates errors for applets and applications of Java
Web Start without signatures and prevent them from being executed. Moreover, even when a
signature is present, Java notifies a warning if the signature is not a signature of a certificate
issued by a third party organization,.
1-12
In addition to taking security measures in the Web applications themselves, a continuous broad
spectrum of security measures including network security measures and countermeasures
against viruses will be required to maintain the security of Web applications.
If users can be identified as in the case of Intranets, it is also important that users understand
the importance of security, and educational campaigns are thus important.
1-13
2.2 JCE
2-1
2-2
Class Interface
java.security.Provider java.security.Key
java.security.Security
java.security.Signature
Java includes a framework related to encryption in the standard class library. The framework is
called JCA (Java Cryptography Architecture).
JCA is included in the java.security package; the most important classes and interfaces of
this framework include Provider, Security, Signature and Key.
JCA is designed taking independence of implementation and algorithm into consideration; it
is possible to incorporate unique encryption services and algorithms.
2-3
Signature
Signature Cipher
Cipher
KeyGenerator
KeyGenerator Provider implementations
JCE (Java Cryptography Extension) is one of the frameworks included in JCA. By using JCE,
it becomes possible to implement unique encryption methods and related processing in JCA.
JCA puts together various encryption services in the Provider class. JCE allows the user to
implements these services in his/her own ways.
2-4
Provider
addProvider
removeProvider
The Provider class provides a package or set of packages that executes one or more encryption
processing. The classes dealing with the execution of the encryption algorithms are called
Engine classes; they include the MessageDigest class that deals with encrypting character
strings, the Signature class that generates and verifies digital signatures and the KeyGenerator
class that generates keys for encryption. Objects of the Provider class contain various
combinations of these Engine classes and is managed centrally by a Security object. System
developers can acquire and use Providers to fit their purposes.
The Provider class is implemented in order to secure independence of implementation.
When there are several implementations that execute the same processing, it is possible to
choose the one that is the fastest or the one that is the most secure, for instance.
In order to add or delete Providers to/from the Security object, use the addProvider method
and removeProvider method. Each Provider has a priority order; if no particular Provider is
provided, the Provider with the highest priority order is used.
2-5
Engine classes represent encryption service associated with specific algorithms. Engine classes
that perform various types of processing necessary for encryption have been defined in
advance.
An Engine class is associated with one or more algorithms and it is possible to specify an
algorithm at execution. A class for each algorithm is defined separately from the Engine
classes and it is possible to define unique algorithm classes as well. JCA ensures independence
of algorithms with this structure.
2-6
initSign
Signed
Signature
data
object sign
static getInstance
Provider
2-7
Signature Verification
object verify
static getInstance
In order to validate the digital signature, first use the getInstance method of the Signature class
to acquire an instance of the Signature class.
After acquiring/setting an algorithm to be used from the public key used for verification, call
the initVerify method to initialize the verification processing.
Next, use the update method to set the data to be verified in the Signature class. The data to
be set should be specified as a byte array.
Lastly, call the verify method to judge the validity of the digital signature.
2-8
KeyPair
Private key
KeyPairGenerator
object Public key
static getInstance
Generate
Provider
The KeyPairGenerator class allows generating a key pair consisting of a public key and a
private key.
To generate a key pair, first call the getInstance method of the KeyPairGenerator class to
generate an instance of the KeyPairGenerator class. It is possible to specify the specific
algorithm and Provider to be used when calling the method. If the specification of a Provider is
omitted, the Provider with the highest priority order is used.
After generating the instance, call the initialize method to initialize the generator. At this
point, it is possible to set parameters for the encryption algorithm and random numbers to be
used.
After initializing the generator, the generate method can be called in order to generate a
private key and a public key and acquire an instance of KeyPair, which includes the two keys.
2-9
getKeyEntry
Private key
KeyStore
object Public key
static getInstance setKeyEntry
Provider
2-10
java.crypto.Cipher
java.crypto.CipherInputStream
java.crypto.CipherOutputStream
java.crypto.KeyGenerator
JCE stands for Java Cryptography Extension and is a framework that extends the functions of
JCA.
The java.crypto.Cipher class is used to implement encryption and decryption functions. In
order to implement unique encryption services, a subclass of this class is created and the
algorithms are implement there.
The CipherInputStream and CipherOutputStream classes implement encrypted input/output
streams. Specify an appropriate Cipher class for encrypting a given stream when generating an
instance.
2-11
2.3.3 Initialization
2-12
KeyGenerator class
Provider
2-13
Example
KeyGenerator kg = KeyGenerator.getInstance(“DES”);
2-14
Example
SecureRandom r = SecureRandom.getInstance("SHA1PRNG");
KeyGenerator kg = KeyGenerator.getInstance(“DSA”);
kg.init(r);
It is necessary to initialize the KeyGenerator class by executing the init method before
generating keys.
The SecureRandom class is a random number generator included in the java.security
package and enhanced for encryption processing. It uses the SHA1PRNG algorithm as
standard. In syntaxes (1), (3) and (5), random numbers are generated from a given
SecureRandom object to perform encryption processing. If a SecureRandom object is not
specified as in the cases of syntaxes (2) and (4), the SecureRandom object is acquired from the
specified Provider. If the specified Provider does not include a SecureRandom object, the
standard random generator provided by the system is used.
2-15
Example
SecureRandom r = SecureRandom.getInstance("SHA1PRNG");
KeyGenerator kg = KeyGenerator.getInstance(“DSA”);
kg.init(r);
Key k = kg.generateKey();
It is possible to generate keys by initializing an instance of KeyGenerator with the init method
and executing the generateKey method.
2-16
2.4.2 Transformation
2.4.5 Padding
2.4.6 Encryption/Decryption
2-17
Cipher class
update Data to be
doFinal encrypted/
decrypted
Cipher
object
Encrypted/
decrypted data
static getInstance
Provider ENCRYPT_MODE
init DECRYPT_MODE
The Cipher class provides functions for encrypting and decrypting data and is a core class of
JCE.
An instance of the Cipher class can be acquired by calling the getInstance method. When
doing so, it is not only possible to specify a Provider, but also a Transformation as a character
string argument for the getInstance method. A Transformation is a character string specifying
the encryption algorithm, conversion mode and/or padding, and various combinations can be
specified.
Next, specify an operation mode and execute the init method. Either ENCRYPT_MODE or
DECRYPT_MODE can be specified. The operation mode specified here determines the
processing carried out in doFinal, which can be either encryption or decryption. With the init
method, it is possible to set not only the operation mode, but also key and algorithm
parameters and random number generator.
After the data is passed to the Cipher object with the update method, encrypted/decrypted
data is returned. When the last data is returned, call the doFinal method and reset the
encryption processing. The reset Cipher object can encrypt/decrypt new data.
2-18
Example
The Cipher class allows specifying a Transformation character string for the getInstance
method. A Transformation character string is composed of an encryption algorithm, a
conversion mode and a padding scheme.
2-19
RC2, RC4, RC5 A variable key-size encryption algorithm developed by Ron Rivest of
RSA Data Security, Inc
The table shows encryption algorithms that can be specified in a Transformation character
string.
2-20
The table shows conversion modes that can be specified in a Transformation character string.
2-21
NoPadding No padding
PKCS5Padding A padding scheme prescribed in “PKCS #5:
Password-Based Encryption Standard” version 1.5
(RSA Laboratories, November 1993)
The table shows padding schemes that can be specified in a Transformation character string.
2-22
Call the update method to perform encryption/decryption with the Cipher class; once data has
been specified as a byte array, it is possible to acquire encrypted/decrypted data. The update
method may have different parameters depending on how the data to be encrypted/decrypted is
specified and how the resulting encrypted/decrypted data is acquired.
Once all the necessary data has been processed with the update method, call the doFinal
method when passing the last data. The doFinal method executes data encryption/decryption in
the same way as the update method, but it also resets the object after processing all data in the
buffer. The reset Cipher object can then encrypt or decrypt new data using different settings.
2-23
Cipher cp = Cipher.getInstance(algorithm);
cp.init(Cipher.ENCRYPT_MODE, key); Encryption
byte[] result = cp.doFinal(args[1].getBytes()); processing
System.out.println("DATA:" + toHexString(result));
2-24
cp.init(Cipher.DECRYPT_MODE, key);
byte[] decrypt = cp.doFinal(result);
System.out.println("DECRYPT:" + new String(decrypt));
} catch (Exception e) {
e.printStackTrace();
} Decryption
} processing
}
2-25
Lines 19 to 20
Initialize the KeyGenerator tool to create a secret key used for
encryption/decryption. Use the algorithm specified in the first
argument.
Lines 21 to 22
Initialize the Cipher instance associating it with the generated key.
Lines 26 to 28
Encrypt the string passed via the second argument and print the
data as hexadecimal numbers
Lines 30 to 32
Decrypt the encrypted data and print it as a string
Execution result
C:\java Sample0201 DESede “Web Secure Programming”
KEY:1cabc5fa6684fc45b111e7e820c3ec511cabc5fa6684fc45
9ba5d11fe1f2d8f3
DATA:6592d6f73f8238d3566eec43ce2cf72121a9dad8dd7f1f
DECRYPT:Web Secure Programming
2-26
3.2 MD5/SHA
3-1
Fixed length
Any length
Update Digest
Data to be
MessageDigest Hash value
hashed
Cannot be restored
Message digest refers to a form of processing that outputs data of a fixed length from data of
arbitrary length using a specific algorithm. The output data is called a hash value or digest
value.
It is not possible for the same hash value to be output unless the data is exactly identical
because the order of the data also influences hash values. Moreover, computing a hash value is
an irreversible operation; it is very difficult to restore the original data from the hash value.
3-2
Compare
Hash value
Hash values can be used as unique reliable identifiers of any data and it is thus can be used to
check that data of programs, documents etc. download via a network have not been tampered
with. For example, when publishing a program, the developer might disclose the JAR file that
contains all the software along with the hash value. A user downloading the software and hash
value can then verify that the software has not been tampered with by executing the same
message digest processing and checking that the same hash value is created.
For this reason, hash values are sometimes called digital fingerprints.
3-3
There are various algorithms for generating hash values, with MD5 and SHA being the
representative ones. These digest algorithms are implemented in the standard Java class
library.
3-4
3-5
Provider
The MessageDigest class allows processing data of any length and generate a hash value based
on it.
Call the getInstance method to generate an instance of the MessageDigest class. At this
point, it is possible to specify the algorithm and/or Provider used for MessageDigest. Either
MD5 or SHA can be specified for the algorithm.
Call the update method to load the data to be hashed into the MessageDigest object. The
data should be specified as a byte array. When all the data is loaded, call the digest method to
acquire the hash value of the data.
3-6
Example
MessageDigest md = MessageDigest.getInstance(“SHA”);
3-7
digest syntax
(1) public byte[] digest()
(2) public byte[] digest(byte[] input)
(3) public int digest(byte[] output, int offset, int length)
The update method of the MessageDigest class is used when loading data of an arbitrary
length, from which a hash value is derived. The arguments of the update method are specified
differently depending on how the data is passed. It is possible to load data of large size by
calling the update method repeatedly.
After loading all the data, it is possible to acquire the hash value by calling the digest
method. The arguments of the digest method are specified differently depending on the method
of acquiring the hash value. After calling the digest method, the data loaded so far by the
update method is reset and the MessageDigest object can load new data again.
3-8
Sample program
import java.security.MessageDigest;
3-9
Lines 5 to 16
Define the toHexString() method, which returns a generated
hash value as a string of hexadecimal numbers. The byte array
given by the argument is converted into hexadecimal numbers
and the character string is returned.
Line 20
Acquire an instance of the MessageDigest class. MD5 is
specified for the hash algorithm.
Line 21
Specify the first argument of the command line in
MessageDigest as a message.
Line 23
Call the digest method to acquire the hash value.
Execution result
3-10
4-1
Sign with
Private key Public key
Verification
Private key Public key
Signed Signed
data data
Delivery
Digital signature refers to signing data such as messages, documents and files electronically,
just like with a manual signature.
In digital signature, a key pair consisting of a private key and a public key is used. The
signatory uses the private key to sign the data. A user receiving the data can then use the
public key of the signatory, which is publicly available, to verify the validity of the signature.
4-2
One of the important advantages of using digital signatures is that it is possible to prove that
signed data has not been illegally rewritten. This is effective when exchanging data via the
Internet and other open networks, as well as when exchanging highly important data. If data
has been changed illegally, the fact can be detected by examining the signature.
Moreover, it is possible to verify the validity of a signature using the public key provided by
the signatory. A signature cannot be forged unless the private key is known to others.
4-3
4-4
Java manages keys and certificates using databases called keystores. The data is managed in
units called entries; each entry has a unique alias name. A entry can be either a key entry, a
certificate entry or a combined entry containing private a key and the corresponding public key
certificate.
4-5
Signature
keystore
Signed data
4-6
Sample program
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Signature;
PrivateKey privateKey =
(PrivateKey)store.getKey(entryName, Acquire private
entryPassword.toCharArray()); key
To be continued
4-7
Continued Initialize
signature object
String keyAlgorithm =
HASH_ALGORITHM + "with" + privateKey.getAlgorithm();
Signature signature = Signature.getInstance(keyAlgorithm);
signature.initSign(privateKey);
Execution result
C:\java Sample0401 C:\temp\keystore.ks password testentry
password C:\temp\input.txt C:\temp\signature.dat
Signature has been created: C:\temp\signature.dat
4-8
Signature
keystore
(2) Read
(3) Verify and update Data
Signed data
4-9
Sample program
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.Certificate;
Continued
4-10
Initialize signature
Sample program object
String keyAlgorithm = HASH_ALGORITHM + "with"
+ publicKey.getAlgorithm();
Signature signature = Signature.getInstance(keyAlgorithm);
signature.initVerify(publicKey);
} catch (Exception e) {
e.printStackTrace();
}
}
}
4-11
Execution result(success)
C:\java Sample0401 C:\temp\keystore.ks password testentry
password C:\temp\input.txt C:\temp\signature.dat
Valid Signature
Invalid Signature
4-12
4-13
Generation
Key pair
Key generator
Private key
Public key Prove validity of Certificate
public key
Public keys are used to prove the validity of data that has been digitally signed, whereas
certificates are data proving that the public keys are generated by the key generator without
doubt. Normally, a certificate is created based on a public key and information about the key
generator.
A user using a public key to verify a digital signature can confirm the validity of the public
key and information of the generator with the corresponding certificate.
4-14
Confirmation Confirmation of
of generator certificate
Signed with
Signed document Private key Verification with public key
4.3.2 CA (Certificate Authority) 4-15
4-15
Java SDK includes various tools for appending digital signatures as standard.
keytool is a utility for managing keystores. It can generate a new key for a keystore or
confirm keystore data. It is also possible to import a certificate issued by a third party
certificate authority and associate this with a corresponding private key.
jarsigner uses private keys and certificates included in a specified keystore to append digital
signatures on JAR files. It is also possible to verify signatures by using the -verify option.
4-16
The X.509 standard is a standard that prescribes what data to include in certificates and how it
should be formatted. Certificates conforming to the X.509 standard is called X.509 certificates.
The data included in a X.509 certificate consists of version, serial number, signature
algorithm identifier, issuer information, valid duration, information of person to be
authenticated and information of the public key corresponding to the certificate. Information
about issuers normally include information about CAs.
4-17
Example
CN=Mark Smith, OU=JavaSoft, O=Sun, L=Cupertino, S=California, C=US
The information about issuer and person to be authenticated included in a X.509 certificate
must be written in a format conforming to the X.500 standard. Information defined by the
X.500 standard include commonName, organizationName, stateName and countryName. This
information is specified using comma-separated format, where each value is specified using
the format “identifier = value.”
4-18
4-19
The keytool utility is a tool included in JavaSDK as standard; it allows managing keystores.
The keytool commands can largely be divided into four categories: data addition to a
keystore, data export, data display and keystore management. The operations are specified via
options.
4-20
Parameters
alias Alias name to be generated storetype Keystore type
keyalg Algorithm to be used for key keystore Keystore file path
generation
storepass Keystore password
keysize Size of the key to be generated
provider_cl Name of provider class to be used for
sigalg Algorithm to be used for signature ass_name processing
dname Information about a person to be
authenticated, written in a format
conforming to the X.500 standard
(generator of the key)
keypass Password of a key to be generated
valDays Number of days in which the
certificate remains valid
The -genkey option generates a new KeyPair (private key and public key) and stores it in a
keystore with the specified alias name.
By default, DSA and 1024 are specified for the key generation algorithm and key size,
respectively. A generated private key is stored together with a self-authentication certificate
created based on the information about the person to be authenticated specified via the dname
parameter. sigalg is used for the signature algorithm.
If any information necessary for generating a key is omitted, the keytool utility acquires the
information from the user via interactive questions.
4-21
Parameters
alias Alias name used when importing a storetype Keystore type
certificate
keystore Keystore file path
cert_file Certificate file to be imported
storepass Keystore password
keypass key password
provider_cl Name of provider class to be used for
ass_name processing
4-22
Parameters
alias Alias name to be generated storetype Keystore type
sigalg Algorithm used for signature keystore Keystore file path
dname Information about a person to be storepass Keystore password
authenticated, written in a format
provider_cl Name of provider class to be used for
conforming to the X.500 standard
ass_name processing
(generator of the key)
The -selfcert option generates self-signed certificates conforming to the X.509 standard.
4-23
Parameters
alias Alias name to be generated storetype Keystore type
sigalg Algorithm used for signature keystore Keystore file path
certreq_file Destination path of the CSR file to be storepass Keystore password
generated
provider_cl Name of provider class to be used for
keypass Password for the key to be generated ass_name processing
The -certreq option generates a certificate signature request (CSR), which is used to request a
third party certificate authority etc. to issue a certificate.
It is possible to specify a specific entry’s alias name and password and the destination path
of the corresponding CSR file to create the CSR file.
4-24
Parameters
alias Alias name to be exported storetype Keystore type
cert_file Destination path of the CSR file to be keystore Keystore file path
generated
storepass Keystore password
provider_cl Name of provider class to be used for
ass_name processing
The -export option reads a certificate included in a specified entry and exports it to a specified
file.
4-25
Parameters
alias Alias name to be displayed storetype Keystore type
keystore Keystore file path
storepass Keystore password
provider_cl Name of provider class to be used for
ass_name processing
The -list option writes information of a key entry identified by a specified alias name to the
standard output. If no alias name is specified, the information of all the key entries in the
keystore is written.
4-26
Parameters
cert_file Path of the certificate file to be displayed
The -printcert option reads a specified certificate file and writes the content to the standard
output.
4-27
Parameters
alias Copy origin of alias name storetype Keystore type
dest_alias Copy destination of alias name keystore Keystore file path
keypass Copy origin of key password storepass Keystore password
new_keypass Copy destination of key password provider_cl Name of provider class to be used for
ass_name processing
By using the -keyclone option, it is possible to copy a specific entry to another entry. Specify
the alias names and key passwords of the copy origin and copy destination, respectively.
4-28
Parameters
new_storepass New password storetype Keystore type
keystore Keystore file path
storepass Keystore password
provider_cl Name of provider class to be used for
ass_name processing
With the -storepasswd option, it is possible to change the password of a specified keystore.
4-29
Parameters
alias Alias name storetype Keystore type
old_keypass Old key password keystore Keystore file path
new_keypass New key password storepass Keystore password
provider_cl Name of provider class to be used for
ass_name processing
By using the -keypasswd option, it is possible to change the key password of a specific entry.
In this case, it is necessary to specify both the old and the new key passwords.
4-30
Parameter
alias Alias name of an entry to be storetype keystore type
deleted
keystore keystore file path
storepass keystore password
provider_cl Name of provider class to be used for
ass_name processing
By using the -delete option, it is possible to delete an entry with a specified alias name.
4-31
jarsigner
keystore
Sign
Java allows placing programs, images, sound files and other files together in a JAR (Java
ARchive) file for efficient delivery of software. The jarsigner utility can use the private key of
a specified keystore to append a digital signature on a JAR file. The jarsigner utility can sign
any files except for files in the META-INF directory. The generated signature information is
stored in the META-INF directory.
It is possible to prove that the contents of the JAR file have not been modified illegally by
verifying the signature of a signed JAR file. If the contents were modified, the illegal changes
can be detected by verification as an error is generated.
Applets, Java Web Start applications etc. are always treated as unreliable programs unless
the program to be executed is signed. If a program is delivered to an unspecified number of
people, it is desirable to append a digital signature using the jarsigner utility.
4-32
Parameters
jarfile Name of the JAR file to be signed storetype Keystore type
keystore Keystore file path
alias Alias name of the entry to be
storepass Keystore password
signed
provider_cl Name of provider class to be used for
keypass Key password ass_name processing
signedjar Destination path for the signed
JAR file
The jarsigner utility appends a signature using a JAR file name and an alias name of the key
entry to be used for the signature.
Keystore information, key password, file name to which a signed JAR file is output etc. are
specified with the options. If the output destination of a signed JAR file is not specified, the
JAR file to be signed is overwritten as a signed JAR file.
4-33
Parameters
jarfile JAR file to be verified
keystore path of keystore file
Example
By using the -verify option, it is possible to verify signatures of signed JAR files.
If no keystore is specified, the system keystore, which includes certificates of the certificate
authorities set in Java in advance, is used. If a keystore is specified, the certificates included in
the keystore are verified.
4-34
5.1 JAAS
5.2 JAAS Core Class/Interface
5.3 Login Module Configuration File
5.4 LoginContext
5.5 LoginModule
5.6 Callback
5.7 JAAS Security Policy File
5.8 Policy Tool Utility
5-1
Authentication
server
Application
Authentication
Authentication Authorization Application
server
JAAS (Java Authentication and Authorization Service) consists of two main functions: an
“authentication” function to identify users in a highly reliable manner and an “authorization”
function for confirming user access rights. JAAS is positioned as a Java standard PAM
(Pluggable Authentication Module) and has been incorporated in SDK from Java1.4 as a
standard package.
Since JAAS authentication is executed as a plug-in, it operates independently of the
individual applications requiring authentication. For this reason, it is not necessary to change
any programs on the application side even if a new authentication method is employed or an
authentication method is changed.
JAAS can be linked to one or more authentication servers, allowing transparent
authentication processing using various methods, including Kerberos, NTUser, UNIXUser and
other forms of authentication.
5-2
Principal Principal
JAAS handles a single entity such as authenticated users and services using the concept of a
“subject.” A subject includes one or more principals. A principal refers to identification
information, such as user ID, that distinguishes the subject from other subjects.
In addition to this, a subject maintains a credential, which is a collection of various objects,
as attribute information. A credential either belongs to the set of public credentials, which can
be accessed from external classes, or the set of private credentials, which can only be used
from within the scope of the subject. The format of credentials and various other objects
included within credentials do not have to follow any specific format.
5-3
5-4
Main method
5-5
Login Login
LoginModule
LoginContext
implementation
Subject
NTUser
Login Determination
Kerberos
JAAS uses the LoginContext class to execute the authentication processing of subjects. The
LoginContext object passes the authentication processing to an object implementing the
LoginModule interface, as determined by a setting file called a login module configuration file.
All the operations an application needs to perform is related to these LoginContext and
LoginModule objects; the actual authentication method and settings related to the
authentication processing are specified in the login module configuration file. For this reason,
the application can operate entirely independently of the authentication processing.
5-6
<entry name> {
Example
SampleEntry{
com.sun.security.auth.module.Krb5LoginModule required;
};
A login module configuration file contains one or more entries. Any name can be specified for
<entry name>.
Each entry is comprised of one or more login modules. Each login module is comprised of a
<LoginModule> value, which specifies the class name of the login module, a <flag> value,
which specifies whether login is necessary, along with any <LoginModuleOptions> values
required in the implementation of the login module. If multiple login modules are specified, all
login modules are executed in the order of description.
5-7
5-8
It is possible to specify the necessity of login authentication and behavior after authentication
by setting flags accordingly in a login module configuration file.
If Required or Requisite is specified, the authentication processing must succeed. If the
authentication fails, an exception is thrown. If Sufficient or Optional is set, an exception is not
thrown even if authentication processing does not succeed.
If multiple login modules are specified for one entry, the value of the flag also determines
whether or not to continue the authentication processing. If Required or Optional is set, the
authentication processing is continued according to the list of enumerated login modules
regardless of whether the authentication succeeds or fails.
If Requisite is set, the authentication processing is continued if the processing succeeds and
the control is switched to the application side if it fails. If Sufficient is set, the control is
switched to the application side if the authentication processing succeeds and the processing is
continued according to the list if it fails.
5-9
LoginContext
class
Entry search
Constructor
LoginContext
instance
Subject
Login module
configuration file Entity
Entity name
name
5-10
Main methods
5-11
JNDI
Keystore Login
LoginModule LoginContext
NTUser
Kerberos
UNIXUser
LoginModule is the basic interface that all classes implementing authentication processing
must implement. A login module includes multiple implementations as standard, and it is
possible to create various LoginModule classes that execute unique authentication processing
by implementing this interface.
5-12
LoginModule1 LoginModule1
Login Commit
Login Login
LoginModule2 context LoginModule2 context
Login Abort
LoginModule3 LoginModule3
LoginModule1 LoginModule1
LoginModule2 Login module LoginModule2 Login module
LoginModule3 configuration file LoginModule3 configuration file
Seen from the LoginContext side, the login processing represents a single operation, but in fact
the login processing on the LoginModule side is executed in two phases.
In the first phase, the login method of each of the LoginModule objects that are targets of
the login processing is executed. The login method returns success or failure, or throws an
exception.
In the second phase, the commit method or abort method of each LoginModule object is
called based on the overall login success and failure. Principals and credentials are set for
authenticated subjects during this phase.
5-13
5-14
Request
Callback Handler
LoginModule Login LoginContext Login
UNIXUser Application
Callback Callback
When executing authentication processing, LoginModule objects may prompt a user to enter
information or display various error messages. The Callback and CallbackHandler interfaces
constitute a framework for handling various requests from LoginModule objects and are
implemented on the application side.
Callback objects represent requests passed from a LoginModule object to the user
application. Normally, several Callback objects are sent at the same time. A CallbackHandler
object executes the Callback processing; specify an appropriate object on the application side
as an argument when generating an instance of LoginContext. Then, when a request to a user
or similar is generated by the actual LoginModule object, an array of Callback instances is
passed to the specified CallbackHandler object.
With this Callback mechanism, it is possible for the application side to implement the
processing using the optimal method for the system in question. For example, in case of GUI-
based (Graphical User Interface) applications, it is possible to implement the prompt for user
ID and password as dialog boxes and display error messages as error dialog boxes.
It is possible to process the Callback and CallbackHandler mechanisms even when unique
LoginModule objects are implemented.
5-15
5-16
The ChoiceCallback class is a class implementing the Callback interface included in the
javax.security.auth.callback package. It provides functionality for prompting a user to select
from various options, which can be obtained using getChoices. Multiple options may be
selected in some cases; whether or not multiple selection is allowed or not can be checked by
calling the allowMultipleSelections method.
5-17
5-18
LanguageCallback()
Main methods
Locale getLocale() Obtains the specified locale information
void setLocale(Locale l) Specifies locale information
The LanguageCallback class is a class implementing the Callback interface included in the
javax.security.auth.callback package. It is used when it is necessary to obtain information
about the system locale.
It implements the getLocale and setLocale methods, which return and specify the locale
information, respectively. The CallbackHandler object either returns locale information of a
system or sets locale information selected by a user via a dialog box etc.
5-19
Main methods
String getDefaultName() Obtains the default name
String getName() Obtains the previously specified name
void setName(String name) Specifies the name
String getPrompt() Obtains the prompt string
The NameCallback class is a class implementing the Callback interface included in the
javax.security.auth.callback package. It is a used when name information such as user name
and ID is required. The CallbackHandler object sets and returns information entered by a user
using the setName method.
5-20
Main methods
void clearPassword() Clears the specified password
String getPassword() Obtains the previously specified password
void setPassword(String pwd) Specifies the name
boolean isEchoOn() Returns True if passwords are echoed on the
screen when entered
String getPrompt() Obtains the prompt string
The PasswordCallback class is a subclass implementing the Callback interface included in the
javax.security.auth.callback package. It is a Callback class used when password information is
required. The CallbackHandler object sets and returns password information entered by a user
using the setPassword method.
The isEchoOn method indicates whether or not to echo the password input (to the screen).
5-21
Main methods
String getDefaultText() Obtains the default character string
String getText() Obtains the previously specified text
void setText(String txt) Specifies the text string
String getPrompt() Obtains the prompt string
The TextInputCallback class is a subclass implementing the Callback interface included in the
javax.security.auth.callback package. It is a Callback class used when a LoginModule object
requires text input. The CallbackHandler object specifies and returns text information entered
by a user or generated in processing etc. using the setText method.
5-22
Main methods
int getMessageType() Obtains the message type.
Constants for INFORMATION, WARNING and
ERROR have been set.
String getMessage() Obtains the message
5-23
LoginModule
LoginContext Application
Callback Register
NTUser Callback
handler
Kerberos instance
UNIXUser
5-24
This sample program shows how to use the LoginContext class and LoginModule interface
explained so far.
In the call to the LoginContext constructor, “Sample0501” is specified for the entry name,
which will be used as an identifier, and a TextCallbackHandler object, which is a text-based
handler included as standard, is specified as the CallbackHandler. It is possible to perform
authentication processing by writing and executing a login configuration file corresponding to
this program.
5-25
Execution result
C:\java -Djava.security.krb5.realm=Realm name
-Djava.security.krb5.kdc=Address authentication host This should actually
-Djava.security.auth.login.config=jaas.conf Sample0501 be on the same line
Authentication Succeeded
jaas.conf is a login configuration file that specifies that the Sample0501 entry performs
Kerberos authentication.
At the execution, it is necessary to use the -D option several times to set various system
properties. The login configuration file is also specified with the -D option.
5-26
Resources Access to
resources
Security
Java
manager
program
Permission Load
objects
Policy file
A policy file contains information related to various access rights such as access rights to
resources and code execution rights. JVM generates permission objects based on these policy
files. Created permission objects are managed via a security manager and applied to execution
of all programs.
The default policy files are located at $JRE_HOME/lib/security/java.policy. Under normal
circumstances, if an application requiring settings specified in a policy file is created, a new
policy file should be created for the particular application rather than using the default policy
file.
To use a created policy file, specify the name of the policy file for the system property
java.security.policy. The system property is specified with the -D option at execution of JVM.
Example: java –Djava.security.policy = policy-file-name class-name
5-27
grant
[signedBy <signer name>, codeBase “URL” ,]
[principal <principal class name> “principal name”]
{
permission <permission class name> “target_name” “action”,
permission <permission class name> “target_name” “action”,
...
}
Example
After “grant,” it is possible to specify JAR file signature information and information about
principals with authenticated logins in a policy file; this is called an entry. Various access
rights can be entered for each entry under “permission.”
If signedBy is specified in a grant entry, it is possible to control access targeted for programs
included in a JAR file signed with a specific certificate. If principal is specified in a grant
entry, it is possible to control access for subjects with particular principal information after
JAAS authentication.
In the example above, file reading rights are granted for the /home/system directory only,
insofar as the authenticated subject contains the myclass.MyPrincipal class and its name is
admin.
5-28
A policy file can easily be created using a text editor or similar, but Java SDK also supplies a
GUI tool for creating policy files as standard. By using Policy Tool, it is possible to prevent
syntax mistakes while improving the operability.
It is possible to edit a specific policy by executing “$JAVA_HOME/bin/policytool policy
file name” in the command prompt or similar. Policy Tool allows not only editing files but also
creating new policy files.
5-29
6.1 JSSE
6-1
Encrypted communication
JSSE (Java Secure Socket Extension) is a framework that provides encrypted communication
via SSL (Secure Socket Layer).
The Internet and other open networks are exposed to various risks.
・The person with whom you are communicating may not necessarily be the person you expect.
・The communication may be tapped by attackers.
・If the communication can be tapped, attackers can alter the content before the data is sent to
the receiver.
SSL allows encrypted and secure communication, thus avoiding these risks. SSL operates
below the application layer and can thus use various protocols such as HTTP and FTP.
SSL was developed by Netscape in 1994 and has become the standard encrypted
communication protocol on the Internet. The standard is currently managed by IETF (Internet
Engineering Task Force) and the name was changed to TLS (Transport Layer Socket).
6-2
In SSL, encrypted communication is not started until after a negotiation where the encryption
method to be used is decided and the server is authenticated.
First, a client sends information about the encryption methods it supports to a server. The
server determines the optimal encryption method based on the information it received and
returns this information to the client. At this point, the encryption algorithm, key size and other
information are determined.
The client then authenticates the server using a certificate and/or other sources and obtains
information about the server’s public key. In the most popular form of SSL communication,
HTTPS, several certificates issued by trusted CAs are registered in a Web browser and the
users can obtain the public key without performing any special operations. If self-authenticated
certificates are to be used, it is necessary to obtain the public key on the client side in advance.
In the encrypted communication, the client and server use the same secret key. The client
encrypts the secret key using the public key generated and obtained from the certificate and
sends it to the server. The encrypted key can only be decrypted by the server’s secret key,
which is paired with the public key attached to the certificate; it is thus not possible for the key
information to be decrypted by entities other than the server.
It is only after these procedures have been completed that the actual encrypted
communication is started using the determined encryption method and the secret key obtained
by both sides.
6-3
javax.net.ssl.SSLSocketFactory
javax.net.ssl.SSLSocket
javax.net.ssl.SSLServerSocketFactory
javax.net.ssl.SSLServerSocket
6-4
SSLSocketFactory SSLSocketFactory
class class
getDefault() getDefault()
SSLSocketFactory SSLSocketFactory
instance instance
6-5
Main methods
6-6
6-7
Main methods
6-8
Main method
void startHandshake() Initiates a new SSL connection (handshake)
void close() Closes the current SSL connection
InputStream getInputStream() Obtains a stream for reading from the current
connection
OutputStream getOutputStream() Obtains a stream for writing to the current
connection
void setSupportedProtocols(String[] p) Sets protocols supported by this connection
void setSupportedCipherSuites(String[] c) Sets encryption methods supported by this
connection
6-9
truststore keystore
A truststore is a keystore that stores certificate and public key information issued by a trusted
CA. Technically, it is not different from a keystore; only the stored data and purposes are
different.
Normally, public key information from trusted third parson certificate authorities such as
Verisign and Geo Trust is stored in a truststore. Web browsers and other applications search
for public key information necessary for SSL communication in truststores. In this way, many
applications can execute encrypted and more secure communication smoothly without the
need of a user installing CA certificates.
Java also incorporates a truststore provided by Sun as standard; it is placed in
$JRE_HOME/lib/security/cacerts.
6-10
Sample
SSL Web server
program
(3) Response
6-11
Sample program
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
if(args[2] != null){
port = Integer.parseInt(args[2]); Generation of the
} Socket class
SSLSocketFactory factory =
(SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket socket =
(SSLSocket) factory.createSocket(host, port);
To be continued
6-12
Sample program
PrintWriter out = new PrintWriter(
new BufferedWriter( Create output
new OutputStreamWriter( stream
socket.getOutputStream())));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close(); Write response
out.close(); to screen
socket.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
6-13
Execution result
>java Sample0601 www.verisign.com / 443
<html>
...
...
[snip]
...
...
</html>
6-14
7.4 Realms
7-1
Web Container
Servlet
Access
control JSP
static HTML
Web containers are entities implementing user authentication frameworks in advance and
allow specific Web applications to control access to Servlet, JSP, static HTML and similar
content through authentication processing. In this way, developers of Web applications do not
need to implement authentication functions from scratch.
7-2
Realm
static HTML
Tomcat authenticates users based on information stored in a user database called a realm. A
realm includes user ID, password and role information indicating privilege. There are various
realm implementations: the user information may be stored using a relational database or in
XML files, LDAP may be used for authentication etc. Realm settings should be described in
server.xml, which is one of the setting files of Tomcat; describe realm implementation classes
to be used and other attribute information in this file according to the realm to be used.
7-3
Tomcat is a genuine Web container and can thus operate in collaboration with various HTTP
servers including well-known Apache. However, Tomcat comes with HTTP servers
implemented 100% in pure Java as standard as well, so that it can operate as a stand-alone
package by itself.
SSL communication is normally handled by a HTTP server; specify Apache or another
HTTP server as the frontend for receiving requests from users. Tomcat’s own HTTP servers
also support SSL communication. They become available by specifying the settings in
server.xml, which is a setting file used by Tomcat.
7-4
7-5
7.5.1 Path-traversal
7.5.3 Overflow
7-6
URL
http://abc.com/cgi-bin/list.cgi?file=../../user_list.txt
Web server
Path-traversal refers to a phenomenon where information that normally must not be shown in a
system is streamed to a user by specifying an illegal URL such as “upper directory” for
parameters etc.
In the majority of the cases, it is possible to prevent path-traversal simply by setting the
security settings of the Web servers tightly. In addition, system developers should always take
precautions about information that must not be made public by locating it in a non-disclosed
directory and other secure area.
7-7
Web server
Web browser
Many Web browsers allow viewing the source of a downloaded HTML file.
HIDDEN type tags that are not rendered on the webpage display can be used for INPUT
tags that return variable values to the server, but since it is possible examine the HTML source,
the hidden data may be revealed and exploited.
Since it is possible to tamper with these parameters and send them back to the server, there
may be circumstances where it is possible to execute processing not expected by the system.
Data that must not be tampered with must not be embedded in HIDDEN type tags, or they
must be encrypted or protected other ways.
7-8
Web server
Web browser
If countermeasures against long character strings and others are not taken in programs on the
server side, there may be cases where the server can be forced to go down or illegal processing
is executed.
Programs receiving parameters must take measures against these issues through strict
checking, including parameter length and prohibited characters, as well as encoding.
7-9
Application Application
SELECT
SELECT ** FROM
FROM USERS
USERS SELECT
SELECT ** FROM
FROM USERS
USERS
WHERE TYPE=1
WHERE TYPE=1 WHERE TYPE=1;
WHERE TYPE=1;
DELETE
DELETE FROM
FROM USERS
USERS
DB DB
Command injection is a form of attack where SQL statements, commands and similar are
embedded in parameters, causing illegal processing to be executed. If the value obtained from
a parameter is used directly in an SQL statement as shown above, a attacker may cause an
illegal SQL statement to be executed on the target system.
Countermeasures against command injection can be taken by checking the contents of
parameters rigorously. In Java, it is possible to use JDBC’s PreparedStatement to check the
content of each parameter and ensure that the data is of a pre-specified type.
7-10
Contents
<script>
................................... Tags are executed.
</script>
Contents
................................................
In cross-site scripting, a attacker may embed <script> and <object> tags in parameters if
values input to parameters are sent out as HTML, making the user open particular pages and
execute illegal processing.
HTML data is encoded according to specific rules when sent out. It is necessary to take
robust countermeasures by encoding entities included in parameters entered by users including
< and > as well as < and > carefully.
7-11
Parameter acquisition
・When a parameter value is
used for SQL, check that
Business logic processing
illegal SQL is not included.
・When a parameter
value is used for HTML, Web application
check that the value is
encoded correctly.
7-12