COMP201 Java Programming
Part III: Advanced Features
Topic 17: Security
Volume II,Chapter 9http://www.securingjava.com/chapter-three/chapter-three-7.html
COMP201 Topic 17 / Slide 2
Objective and Outline Objective:
Introduction to java security mechanisms (in relation to applets)– How to use and how do they work
Outline Using java security mechanisms
– Security policy files– Code signing
How do java security mechanisms work– Security enforcement
SecureClassLoader and SecurityManager– Supporting technologies
Message digest, digital signatures, authentication
COMP201 Topic 17 / Slide 3
Using java security mechanisms
Applets are restricted to the sandbox by default: Can only phone home and create pop-up window with warning Cannot read/write/delete local files, run another program,
connecting to a server other than its home server, …
More permissions can be granted with Security policy file Code signing
Try examples from Topic 11 and Topic 17
COMP201 Topic 17 / Slide 4
Security Policy Files Consist of a sequence of grant entries.
Each gives some specific permissions to applets from a specific location and/or signed by a specific person
A grant entry has the following general form:grant signedBy “name”, codeBase “file source”{ permission1; permission2; …}
signedBy part omitted if signatures not required for this entry. codeBase part omitted if the entry applies to code from all sources
COMP201 Topic 17 / Slide 5
Security Policy Files codeBase examples:
grant codeBase “http://www.cs.ust.hk/~liao/comp201/”{ } //premission entry for all classes under the directory grant codeBase “http://www.cs.ust.hk/~liao/comp201/tmp.jar”{ }
// permission entry for tmp.jar
grant codeBase “file:C:/dir/tmp” { }grant codeBase “file:/C:/dir/tmp” { }grant codeBase “file://C:/dir/tmp” { }/* permission entry for tmp on local machine */
Note: Forward slash even for the Windows OSCode signing will be discussed later.
COMP201 Topic 17 / Slide 6
Security Policy Files General form for permissions:
permission className tagetName, actionList;className must be fully qualified.
Examples: permission java.io.FilePermission "D:\\-","read, write"; // permission to read and write all files in D drive
permission java.awt.AWTPermission "showWindowWithoutWarningBanner";
// permission to create pop-up window without warning
permission java.net.SocketPermission “*:8000-8999", “connect";
//permission to connect to any host via port 8000 - 8999.
COMP201 Topic 17 / Slide 7
Security Policy Files Permission classes:
java.io.FilePermission java.awt.AWTPermission java.net.SocketPermissionjava.net.NetPermissionjava.util.PropertyPermissionjava.lang.RuntimePermissionjava.security.AllPermission….
See page 712 for details
COMP201 Topic 17 / Slide 8
Security Policy Files java.io.FilePermission
Targets:File a fileDirectory a directoryDirectory/* all files in the directory* all files in current directoryDirectory/- all files in this and all its subdirectories- all files in current directory and all its
subs<<ALL FILES>> all files in the file system
In Windows OS, use \\ as file separator Actions
read, write, delete, execute
COMP201 Topic 17 / Slide 9
Security Policy Files java.net.SocketPermission
Targets: (hostRange:portRange)HostName or IPAddreses a single hostlocalhost or empty local host*.domainSuffix all hosts whose domain names end
with the suffix . E.g. *.com* all hosts
:n single port:n1-n2 all ports in the range
Actions:accept, connect, listen, resolve
COMP201 Topic 17 / Slide 10
Security Policy Files
An example policy filegrant codeBase "http://www.cs.ust.hk/~liao/comp201/codes/secu/awt/" {
permission java.awt.AWTPermission "showWindowWithoutWarningBanner";
};
grant codeBase "http://www.cs.ust.hk/~liao/comp201/codes/secu/file/" {
permission java.awt.AWTPermission "showWindowWithoutWarningBanner";
permission java.io.FilePermission "<<ALL FILES>>", "read, write";
};
grant codeBase "http://www.cs.ust.hk/~liao/comp201/codes/secu/socket/" {
permission java.net.SocketPermission "*", "connect";
};
COMP201 Topic 17 / Slide 11
Security Policy Files policytool: a utility for creating policy files
COMP201 Topic 17 / Slide 12
Security Policy FilesLocation of policy file: On client machine Method 1:
${user.home}/.java.policy
On XP: C:\Documents and Settings\liao\.java.policy${java.home}/lib/security/java.policy on my machine: C:\Program Files\j2sdk1.4.0\jre\lib\security
Method 2: place a policy file on the internet or on local machine, add to the master security properties file: ${java.home}/jre/lib/security/java.security
the a link to the policy file. E.g.: policy.url.3=http://www.cs.ust.hk/~liao/comp201/codes/secu/applet.policy
Manage the policy file at a single location. Good for intranet.
COMP201 Topic 17 / Slide 13
Permission Granting Examples AWT Permission example: (check code page)
Normally, pop-up windows created by applets come with warning banners.
However, the pop-up window created by the applet from
http://www.cs.ust.hk/~liao/comp201/codes/secu/awt/
has no warning banner if one includes the following entry into thepolicy filegrant codeBase "http://www.cs.ust.hk/~liao/comp201/codes/secu/awt/" { permission java.awt.AWTPermission
"showWindowWithoutWarningBanner"; };
COMP201 Topic 17 / Slide 14
Permission Granting Examples File Permission example:
Normally, applets cannot read and write local files. However, FileIOApplet from
http://www.cs.ust.hk/~liao/comp201/codes/secu/file/ can read and write local files if one includes the following grant entry
in the policy file: grant codeBase "http://www.cs.ust.hk/~liao/comp201/codes/secu/file/" { permission java.io.FilePermission “<<ALL FILES>> ",
"read,write"; permission java.awt.AWTPermission
"showWindowWithoutWarningBanner"; };
COMP201 Topic 17 / Slide 15
Permission Granting Examples Socket Permission example:
Normally, applets cannot connect to a server other than its home server.
However, SocketApplet from
http://www.cs.ust.hk/~liao/comp201/codes/secu/socket/
can connect to other http servers if one includes the following grant entry in the policy file:
grant codeBase “http://www.cs.ust.hk/~liao/comp201/codes/secu/socket/” { permission java.net.SocketPermission "*", "connect"; };
COMP201 Topic 17 / Slide 16
Outline Using java security mechanisms
Security policy files Code signing
How do java security mechanisms work Security enforcement
– SecureClassLoader and SecurityManager Supporting technologies
– Message digest, digital signatures, authentication
COMP201 Topic 17 / Slide 17
Code Signing Developer
Generates a certificate, which contains a pair of keys, a public key and a private key.
Send the public key to its users. Sign applets with the private key.
Client Gets public key from the developer Adds the public key to his/her own public key collection Modify its own security policy file to given more permissions to
applets signed by THE developer.
COMP201 Topic 17 / Slide 18
Code Signing /Developer
Java comes with the keytool program for managing keystore – database of certificates.
To generate a keystore liao.store and generate a pair of keys with alias liao use the command:keytool –genkey –keystore liao.store –alias liao
A dialog follows and liao.store created.
Keep liao.store at a safe location!
COMP201 Topic 17 / Slide 19
Enter keystore password: 123456 What is your first and last name? [Unknown]: Renlan LiaoWhat is the name of your organizational unit? [Unknown]: Computer ScienceWhat is the name of your organization? [Unknown]: Hong Kong University of Science and TechnologyWhat is the name of your City or Locality? [Unknown]: Hong KongWhat is the name of your State or Province? [Unknown]: Hong KongWhat is the two-letter country code for this unit? [Unknown]: CNIs <CN=Renlan Liao, OU=Computer Science, O=Hong Kong University of
Science and Technology, L=Hong Kong, ST=Hong Kong, C=CN> correct? [no]: yes
Enter key password for <Renlan>
(RETURN if same as keystore password):
Code Signing /Developer
COMP201 Topic 17 / Slide 20
Export the public key to a certificate file and sent it to user.keytool –export –keystore liao.store –alias liao –file liao.cert
What is inside?D:\Users\public_html\COMP201\codes\secu>keytool -printcert -
file liao.certOwner: CN=Renlan Liao, OU=Computer Science, O=Hong Kong University of
Science and Technology, L=Hong Kong, ST=Hong Kong, C=cn
Issuer: CN=Renlan Liao, OU=Computer Science, O=Hong Kong University of Science and Technology, L=Hong Kong, ST=Hong Kong, C=cn
Serial number: 40a08a25
Valid from: Tue May 11 16:09:09 GMT+08:00 2004 until: Mon Aug 09 16:09:09 GMT+08:00 2004
Certificate fingerprints:
MD5: A0:60:35:22:28:42:3B:18:77:12:EB:43:13:B1:D7:C6
SHA1: 9:34:84:4C:F0:32:B5:B1:17:55:3B:0C:03:FC:87:FE:EC:69:A0:6F
Code Signing /Developer
COMP201 Topic 17 / Slide 21
Sign applets
Create a jar filejar cvf MyApplet.jar *.class
Run the jarsigner tooljarsigner –keystore Liao.store MyApplet.jar Liao
Keystore containing private key
Alias of private key
Code Signing /Developer
COMP201 Topic 17 / Slide 22
Add public key received to his/her store of public keyskeytool –import –keystore certs.store –alias liao –file liao.cert
Include location of public key store to policy fileKeystore “keystoreURL”, “keystoreType”;
Ex: keystore “file:C:\Windows\cert.store”, "JKS";
keystore "http://www.cs.ust.hk/~liao/comp201/codes/secu/certs.store", "JKS";
JKS: type of keystore generated by keytool
Code Signing /Client
COMP201 Topic 17 / Slide 23
Add signedBy “alias” to grant clauses in policy file
grant signedBy “liao" { permission java.awt.AWTPermission "showWindowWithoutWarningBanner"; };
Examples: see code page
What if client’s policy file does not grant permissions to signed applets Browser will ask for permissions when loading the applets Example: http://www.cs.ust.hk/~liao/comp201/codes/secu/sign2/
Code Signing /User
COMP201 Topic 17 / Slide 24
Outline
Using java security mechanisms Security policy files Code signing
How do java security mechanisms work Security enforcement
– SecureClassLoader and SecurityManager
Supporting technologies– Message digest, digital signatures, authentication
COMP201 Topic 17 / Slide 25
Security Enforcement
Policy files loaded into the VM at startup Represented using a java.Security.Policy object
SecureClassLoader tracks the code source and signatures of each class, and hence assigns classes to protection domains.
SecurityManager checks for permissions at run time.
COMP201 Topic 17 / Slide 26
SecureClassLoader Code identity: origin and signature
– A principal: an individual, a corporation, and a login id.
SecureClassLoader checks code identity against the entries of a policy object to determine what permission(s) a piece of code should be given
Security Enforcement
COMP201 Topic 17 / Slide 27
Security Enforcement Protection domains:
A bunch of classes that should be treated alike because they came from the same place and were signed by the same people
Permissions are granted to protection domains and not directly to classes and objects .
COMP201 Topic 17 / Slide 28
Security Enforcement The Security Manager
Performs runtime checks on dangerous methods. Code in the Java library consults the Security Manager whenever a
potentially dangerous operation is attempted. The Security Manager can veto the operation by generating a
SecurityException. Built-in classes are usually given more privilege than classes loaded across
the Net.
COMP201 Topic 17 / Slide 29
More details A Java program makes a call to a potentially dangerous operation in
the Java API.
The Java API code asks the Security Manager whether the operation should be allowed.
The Security Manager throws a SecurityException back to the Java API if the operation is denied. This exception propagates back to the Java program.
If the operation is permitted, the Security Manager call returns without throwing an exception, and the Java API performs the requested dangerous operation and returns normally.
Security Enforcement
COMP201 Topic 17 / Slide 30
Outline
Using java security mechanisms Security policy files Code signing
How do java security mechanisms work Security enforcement
– SecureClassLoader and SecurityManager
Supporting technologies– Message digest, digital signatures, authentication
COMP201 Topic 17 / Slide 31
Supporting Technologies
So far, we have discussed what programmer and user should do in order to give more permissions to trusted applets.
However, we haven’t not discussed
How does keytool generate keys? How does jarsigner sign codes? How does Java verify certificates?
Why is it secure?
COMP201 Topic 17 / Slide 32
Supporting Technologies /Message Digest
A message digest is a digital fingerprint of a block of data such that it is VERY VERY unlikely for two different blocks data to have the same digest.
If you send a message and its digest separately, recipient can verify whether the message has been modified during transmission.Compute the fingerprint of the message received and compare it with the fingerprint received.
Of course, you need to make sure that not both the message and its digest are intercepted.
MessageMessageMessageMessage MessageMessageMessageMessage
MessageMessageDigestDigest
MessageMessageDigestDigest MessageMessage
DigestDigest
MessageMessageDigestDigest MessageMessage
DigestDigest
MessageMessageDigestDigest=?
COMP201 Topic 17 / Slide 33
Supporting Technologies /Message Digest
Two best known algorithms for computing message digests: SHA1 (Secure hash algorithm #1), MD5. (Less reliable).
Java supports both algorithms.
COMP201 Topic 17 / Slide 34
Compute a fingerprint using SHA1: Get a MessageDigest objectMessageDigest alg = MessageDigest.getInstance(“SHA-1”);
Feed all bytes of message to the objectFileInputStream in = new FileInputStream( fileName );int ch;While ( (ch = in.read() != -1 ) alg.update( ((byte) ch );
Get fingerprint using the digest methodByte[] hash = alg.digest();
MessageDigest.java
Supporting Technologies /Message Digest
COMP201 Topic 17 / Slide 35
Supporting Technologies /Digital Signatures
Public key cryptography A pair of keys: one public (given to every one) and one private.
It is VERY VERY hard to compute the private key from the public key and vice versa.
But it is easy to tell whether a public key and a private key match
COMP201 Topic 17 / Slide 36
Supporting Technologies /Digital Signatures
When sending a message to a friend You sign it with your private key Recipient verifies the message with you public key If verification passes, receiver can be sure that
The message is from you and not altered during transmission
When a friend sending a message to your He/She signs it with his/her own private key You verify the message with his/her public key If verification passed, you can be sure that
The message is singed with your friend’s private key and not altered during transmission
COMP201 Topic 17 / Slide 37
HashHashFunctioFunctio
nn
MessageMessageMessageMessage
MessagMessagee
DigestDigest
MessagMessagee
DigestDigest
DigitalDigitalSig.Sig.
DigitalDigitalSig.Sig.
MessageMessageMessageMessage
DigitalDigitalSig.Sig.
DigitalDigitalSig.Sig.
Supporting Technologies /Digital Signatures
PrivatePrivateKeyKey
PrivatePrivateKeyKey
Sending message
COMP201 Topic 17 / Slide 38
Supporting Technologies /Digital Signatures
HashHashFunctiFuncti
onon
Matched?
Dig
ital S
ign
atu
re
PublicPublicKeyKey
MessageMessageMessageMessage
MessagMessagee
Digest’Digest’
MessagMessagee
Digest’Digest’DigitalDigital
Sig.Sig.
DigitalDigitalSig.Sig.
MessageMessageMessageMessage
DigitalDigitalSig.Sig.
DigitalDigitalSig.Sig.
MessagMessagee
DigestDigest
MessagMessagee
DigestDigest
Verify message
COMP201 Topic 17 / Slide 39
Algorithms for generating keys, signing messages, and verifying signatures: DSA (Digital signature algorithm), supported by Java RSA, commercial package.
Generating key pairs// get a KeyPairGenerator objectKeyPairGenerator keygen = KeyPairGenerator.getInstance(“DSA);// initialize it with a truly random numberSecureRandom secrand = new SecureRandom();keygen.initialize(512,secrand); //512 length of a block in key// generate key pair KeyPair keys = keygen.generateKeyPair();PublicKey pubkey = keys.getPublic();PrivatKey privkey = keys.getPrivate();
Supporting Technologies /Digital Signatures
COMP201 Topic 17 / Slide 40
Signing a message// get a Signature objectSignature signalg = Signature.getInstance(“DSA);
// initialize it with private key using initSignsignalg.initSign(privkey);
// feed all bytes of message to the object one by one While ( (ch = in.read() != -1) signalg.update( (byte) ch );
// get signature using the sing methodBye[] signature = signalg.sign();
Supporting Technologies /Digital Signatures
COMP201 Topic 17 / Slide 41
Verifying a message//get a Signature objectSignature verifyalg = Signature.getInstance(“DSA);
//initialize it with private key using initVerifysignalg.initVerify(pubkey);
//feed all bytes of message to the object one by one While ( (ch = in.read() != -1) verifyalg.update( (byte) ch );
//Finally, verify signatureBoolean check = verifyalg.verify(signature);
SingatureTest.java
Supporting Technologies /Digital Signatures
COMP201 Topic 17 / Slide 42
Any one can send you his/her public key and ask you to accept applets signed by him/her.
Authentication problem: How to determine the identity of the sender.
Sender can have his/her certificate authenticated by a trusted(?) body, such as Hong Kong Central Post Office (http://www.hongkongpost.gov.hk/product/ecert/usage/index.html ), Thawte, Versign, United States Postal Service,
If you trust the authentication authorities, you can trust the certificates they signed.
Software developer certificates are created this way.
Supporting Technologies /Authentication