Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

32
Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU

Transcript of Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

Page 1: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

Java Security

Sahar M. GhanemPh.D. Candidate

CS Department, ODU

Page 2: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

J2SDK v 1.4 URL

http://java.sun.com/j2se/1.4/docs/guide/security

Page 3: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

Java Security Features

Java General Security ArchitectureJava Authentication and Authorization Service (JASS)Java Cryptographic Extension (JCE)Java Secure Socket Extension (JSSE)Java Generic Security Services API (GSS-API)

Page 4: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

Java General Security Architecture

Overall security is enforced by the following means:

The Java language is designed to be type-safeCompliers and byte code verifier ensure that only legitimate Java byte-codes are executedAccess to crucial system resources is mediated by the JVM and is checked in advance by a SecurityManager class

Page 5: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

The appletviewer and most browsers install a security managerA security manager is not automatically installed when an application is runningHow to run a security manager for an application?

Command-line argumentjava -Djava.security.manager <SomeApp>

Inside the application itselfSystem.setSecurityManager(new

SecurityManager());

Page 6: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.
Page 7: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

SecuirtyManager class contains many methods with names that begin with the word check. Examples are checkRead, checkConnect

Various methods in the Java libraries call a check method before performing a potentially security sensitive operation. Examples are java.awt.ToolKit.getPrintJob, java.io.File.delete, java.lang.Class.forName, java.lang.System.getProperty, java.lang.Thread.interrupt, java.net.DatagramSocket.send, java.security.Policy.getPolicy, …

A SecurityManager method call checks on the permission on the policy currently in effectFor example, a call to the method java.io.FileInputStream (String filename) calls a SecurityManager method checkRead (String filename) that checks for the permission java.io.FilePermission(“filename”, “read”)

Page 8: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

The permission classes represents access to system resourcesThe java.security.Permission class is an abstract class and is sub-classed to represent specific accessesA permission object is constructed by the current SecurityManager when making access decisionsThere is risks of granting each J2SDK built-in permission. Examples are java.security.AllPermission, java.awt.AWTPermissions, java.io.FilePermission, java.net.NetPermission, java.util.PropertyPermission, java.lang.RuntimePermission, java.security.SecurityPermission, java.net.SocketPermission

The previously mentioned methods require certain permissions to be in effect in order to be successfulSee document “Permissions in the Java 2 SDK”

Page 9: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

Each permission instance is generated with one or two string parameters, a target and a comma-separated actionsExamples:fperm = new FilePermission(“filename”, “read, write”);sperm = new SocketPermission(“localhost:1024-”, “connect”);aperm = new AWTPermission(“accessClipboard”);secperm = new SecuityPermission(“getPolicy”);

You can define new permissionpublic class com.abc.Permission extends java.securty.Permissionpublic class com.abc.TVPermission extends com.abc.Permissiontvperm = new TVPermission(“channel-5”, “watch”);AccessController.checkPermission(tvperm);

You can tailor AccessController, SecurityManager, ClassLoader, …

Page 10: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

The policy specifies which permissions are available for code from various sources and executing as various principalsA policy file can be composed via a simple text editor, or via a graphical policytool utilityThere is by default a single system-wide policy file, and a single user policy file: {java.home}/lib/security/java.policy & {user.home}/.java.policy

The system policy is loaded in first, and then the user policy is added to it. If neither policy is present, a built-in policy is used (original sandbox policy)Policy file locations can be specified in: security properties file:

{java.home}/lib/security/java.security command-line argument: java -Djava.security.manager

–Djava.security.policy=purl <SomeApp>

Page 11: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

A policy file contains a list if entries, a “keystore” entry and a zero or more “grant” entries.A keystore is a database of private keys and their associated digital certificates The keytool utility is used to create and administer keystoresThe keystore in a policy file is used to look up the public keys of the signers specified in the grant entriesSyntax: keystore “some_keystore_url”, “keystore_type”; //where the url is relative to the policy file locationExample: keystore “keystores/.abckeystore”;

Default type is “JKS” by sun MicrosystemsYou can use keys and and certificates to digitally sign your java applications and applets with jarsigner utility

Page 12: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

Grant examplesgrant {permission java.io.FilePermission ".tmp", "read"; };grant signedBy "Roland,Li" { permission java.io.FilePermission "/tmp/*", "read"; permission java.util.PropertyPermission "user.*"; };grant codeBase "http://java.sun.com/*", signedBy "Li" { permission java.io.FilePermission "/tmp/*", "read"; permission java.io.SocketPermission "*", "connect"; }; grant principal javax.security.auth.x500.X500Principal "cn=Alice" { permission java.io.FilePermission "/home/Alice", "read, write"; }; grant codebase "http://www.games.com", signedBy "Duke", principal javax.security.auth.x500.X500Principal "cn=Alice" { permission java.io.FilePermission "/tmp/games", "read, write"; };

Page 13: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

Java Authentication & Authorization

• Authentication: determines who is currently executing java code. Application should be independent form the authentication technique.

• Authorization: ensures the users have the access permission required

• Core classes: Subject, LoginContext, LoginModule

• Steps to authenticate a subject• The application instantiates a LoginContext• LoginContext consults a Configuration (which

LoginModule to use)• Application calls LoginContext.login()• Application retrieves the authenticated Subject

Page 14: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

• LoginContext • Provides a way to develp an application

independent of the authentication technology• Actual authentiction calls login() method

• Subject • represents source of request (might have many

principals)• AuthPermission is required to required to access/modify

Subject’s methods• Subject.doAs (Subject, PrivilegedAction) is the call to

perform work as subject • If the PrivilegedAction encounter a security check, the

permission has to on the Policy

• LoginModule• Interface for developers to implement different kinds of

authentication (username/password, hardware devices,..)

Page 15: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

• JASS Configuration file (jaas.config)Sample { KeyStoreLoginModule required

debug=true; }; Other LoginModules: JndLoginModule, Krb5LoginModule,

NTLoginModule, UnixLoginModuleLoginModule flag: required, requisite, sufficient, optional

• How to run for JASS configurationjava -Djava.security.manager -Djava.security.policy=

<policyFile> -Djava.security.auth.login.config= jaas.config <apllication>

• ExampleActionpublic class SampleAction implements PrivilegedAction { public Object run() { // privileged action will check on the permission

Page 16: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

Example

// Obtain a LoginContext, needed for authentication. Tell it // to use the LoginModule implementation specified by the // entry named "Sample" in the JAAS login configuration // file and to also use the specified CallbackHandler.

LoginContext lc = new LoginContext("Sample", new MyCallbackHandler());lc.login(); // attempt authentication

Subject mySubject = lc.getSubject(); // now try to execute the SampleAction as the authenticated Subject PrivilegedAction action = new SampleAction(); Subject.doAsPrivileged(mySubject, action, null);

Page 17: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

Java Cryptography

A framework for accessing and developing cryptographic functionality such as digital signature & encryptionJava cryptography architecture design principals

Implementation independence: a provider based architectureAlgorithm independence: achieved by defining “engine” classes and classes that provide the functionality

A programmer can request a particular type of object (Signature) implementing a particular service (DSA) and get the implementation from one of the installed providers

Page 18: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

9 Engine classes:• Does a cryptographic operation: MessageDigest, Signature• Generates or supplies the cryptographic keys and

parameters: KeyPairGenerator, AlgorithmParameters, AlgorithmParameterGenerator, SecureRandom

• Generates data objects that encapsulates cryptographic keys: KeyFactory, CertificateFactory, KeyStore

A “generator” creates objects with brand-new contents, whereas a “factory” creates objects from existing materialFor each engine class there is a corresponding abstract Spi class which defines the service provider interface methodsA user requests an object by calling the getInstance (algorithm, provider) method in the engine class (factory method)An object of an engine class encapsulates an object of the corresponding Spi class

Page 19: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

A provider could supply one or more of the following algorithms (example “SUN” provider)

MessageDigest: MD2, SHA, MD5KeyPairGenerator, KeyFactory, AlgorithmParameterGenerator, AlgorithmParameters: DSA, RSA Signature: SHA1withDSA, MD2withRSA, MD5withRSA, SHA1withRSACertificateFactory: X.509SecureRandom: SHA1PRNGKeyStore: JKS, PKC12

you can call java.security.Security methods getProviders, addProvider, insertProviderAt, removeProvider, …

Page 20: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

Examples:#1 MessageDigestMessageDigest md = MessageDigest.getInstance (“SHA”);byte[] input = …; md.update(input); byte[] output = md.digest();

#2 SignatureSignature s = Signature.getInstance (“SHA1withDSA”);// get privateKey | publicKey ??s.initSign(privateKey); | s.initVerify(publicKey); byte[] input = …;s.update(input);byte[] output = s.sign(); | boolean flag = s.verify();

Page 21: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

#3 KeyPairGeneratorKeyPairGenerator kpg = KeyPairGenerator.getInstance (“DSA”);kpg.initialize(1024); KeyPair kp = kpg.generateKeyPair();PrivateKey privateKey = kp.getPrivate(); PublicKey publicKey = kp.getPublic();

#4 KeyStoreKeyStore ks = KeyStore.getInstance (“JKS”);ks.load (instream, spw); //InputStream, String Enumeration aliases = ks.aliases(); ks.setKeyEntry(kalias,key,kpw, chain); // String, Key,String,

Certificate[]ks.setCertificateEntry(calias, c); // String, Certificate //other methods: isKeyEntry, isCertificateEntry, deleteEntry,

getKey, ..store (outstream, spw); //OutStream, String

Page 22: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

Java Cryptographic Extension JCE

Cipher engine class:• getInstance (String transformation, String provider)

transformation: ”algorithm/mode/padding”• init(int opmode, Key key)

opmode: ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE, UNWRAP_MODE

• public byte[] doFinal(byte[] input)• public byte[] update (byte[] input)• public byte[] wrap(Key key)• public Key unwrap(byte[] wrappedKey, String algorithm, int

type); type:SECRET_KEY, PRIVATE_KEY, PUBLIC_KEY

Page 23: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

KeyAgreement engine class:• getInstance (String algorithm, String provider);• init(Key key); // use private

key• public Key doPhase(Key key, boolean lastPhase); // use

public key• public byte[] generateSecret();• public SecretKey generateSecret(String algorithm);

Mac engine class:• getInstance (String algorithm, String provider);• init(Key key); • Public byte[] doFinal(byte[] input);• Public void update (byte[] input);

Page 24: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

A JCE provider could supply one or more of the following algorithms (example “SunJCE” provider)Cipher: DES, DESede, Blowfish, PBEWithMD5AndDES, RC2, RC4, RC5

Mode: ECB, CBC, CFB, OFB, PCBCPadding: NoPadding, PKCS5Padding, SSL3Padding

KeyAgreement: DiffieHellman Mac: HmacMD5, HmacSHA1 KeyGenerator: DES, DESede, Blowfish, HmacMD5, HmacSHA1 SecretKeyFactory: DES, DESede, PBEWithMD5AndDES KeyPairGenerator: DiffieHellman KeyFactory: DiffieHellman AlgorithmParameterGenerator: DiffieHellman AlgorithmParameters: DiffieHellman, DES, DESede, PBE, Blowfish KeyStore: JCEKS

Page 25: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

Example

Side A: EncryptionCipher cipher = Cipher.getInstance(“DES/ECB/PKCS5Padding”);// get keycipher.init(Cipher.ENCRYPT_MODE, key);byte[] clearText = …byte[] cipherText = cipher.doFinal (clearText);

Side B: DecryprionCipher cipher = Cipher.getInstance(“DES/ECB/PKCS5Padding”);// get keycipher.init(Cipher.DECRYPT_MODE, key);byte[] cipherText = …byte[] clearText =cipher.doFinal (cipherText);

Page 26: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

Java Secure Socket Extension

JSSE enables secure Internet communicationsAvailable in javax.net, javax.net.ssl, javax.security.cert Provides factories for SSL sockets & SSL server socketsImplementation of SSL 3.0 & TLS 1.0 that provides

Data encryption (secret key cryptography)Server authentication (public key cryptography)Message integrity (digital signature)Optional client authentication

Page 27: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

SSL provides enhancement to the standard TCP/IPThe application most commonly used with SSL is HTTPThe most obvious example of when to use SSL is in e-commerce transactionSSL communication begins with a handshake to negotiate cipher suite (algorithms and key sizes), and optionally authenticate identityJSSE includes an implementation that all users can utilize (SunJSSE)

KeyFactory: RSAKeyPairGenerator: RSAKeyStore: PKCS12Signature: MD2withRSA, MD5withRSA, SHA1withRSAKeyManagerFactory & TrustManagerFactory: SunX509SSLContext: SSL, SSLv3, TLS, TLSv1

Page 28: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

How to get an SSL Factory ?

• The defaultSSLServerSocketFactory ssf =

SSLServerSocketFactory.getDefault();

• Create an SSLContext SSLContext sc = SSLContext.getInstance (“SSL”); sc.init(KeyManager[], TrustManager[], SecureRandom);ServerSocketFactory ssf = sc.getServerSocketFactory();

To be able to authenticate the remote identity of a peer, you need TrustManager. A TrustManager implements an authentication technique such as X.509 certificates, shared secret keys, or other (initialized with KeyStore)

To be able to authenticate yourself t a remote peer, you need KeyManager (initilized with KeyStore and password)

Page 29: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

Properties that affect SSL

System (javax.net.ssl): keyStore, keyStoreType, keyStorePassword, trustStore, trustStoreType, trustStorePassword

How to change a property ?• Command-line argumentjava –Djavax.net.ssl.trustStore=myStore …• Inside the applicationSystem.setProperty(“javax.net.ssl.trustStore”,

“mystore”);

Page 30: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

Example Server

SSLServerSocketFactory sslSrvFact =(SSLServerSocketFactory) SSLServerSocketFactory.getDefault();

s = (SSLServerSocket) sslSrvFact.createServerSocket(port);

c = (SSLSocket) s.accept();OutputStream out = c.getOutputStream();InputStream in = c.getInputStream();

// send through “out”, and receive through “in”

Page 31: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

Example Client

SSLSocketFactory sslFact =(SSLSocketFactory) SSLSocketFactory.getDefault();

s = (SSLSocket) sslFact.createSocket(host, port);

OutputStream out = s.getOutputStream();InputStream in = s.getInputStream();

// send through “out”, and receive through “in”

Page 32: Java Security Sahar M. Ghanem Ph.D. Candidate CS Department, ODU.

Conclusion: Java secuirty features

• KeyStore management (keytool)• Fine-grained access control (Policy and policytool,

SecurityManager, …)• Authentication and authorization (LoginModule, …)• Cryptography (MessageDigest, Signature, Cipher,

Mac, …)• SSL protocol