320 likes | 531 Views
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. Java Security Features. Java General Security Architecture Java Authentication and Authorization Service (JASS) Java Cryptographic Extension (JCE)
E N D
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
Java Security Features • Java General Security Architecture • Java Authentication and Authorization Service (JASS) • Java Cryptographic Extension (JCE) • Java Secure Socket Extension (JSSE) • Java Generic Security Services API (GSS-API)
Java General Security Architecture • Overall security is enforced by the following means: • The Java language is designed to be type-safe • Compliers and byte code verifier ensure that only legitimate Java byte-codes are executed • Access to crucial system resources is mediated by the JVM and is checked in advance by a SecurityManager class
The appletviewer and most browsers install a security manager • A security manager is not automatically installed when an application is running • How to run a security manager for an application? • Command-line argument • java -Djava.security.manager <SomeApp> • Inside the application itself • System.setSecurityManager(new SecurityManager());
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 effect • For example, a call to the method java.io.FileInputStream (String filename)calls a SecurityManager methodcheckRead (String filename)that checks for the permission java.io.FilePermission(“filename”, “read”)
The permission classes represents access to system resources • The java.security.Permission class is an abstract class and is sub-classed to represent specific accesses • A permission object is constructed by the current SecurityManager when making access decisions • There 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 successful • See document “Permissions in the Java 2 SDK”
Each permission instance is generated with one or two string parameters, a target and a comma-separated actions • Examples: fperm = new FilePermission(“filename”, “read, write”); sperm = new SocketPermission(“localhost:1024-”, “connect”); aperm = new AWTPermission(“accessClipboard”); secperm = new SecuityPermission(“getPolicy”); • You can define new permission public class com.abc.Permission extends java.securty.Permission public class com.abc.TVPermission extends com.abc.Permission tvperm = new TVPermission(“channel-5”, “watch”); AccessController.checkPermission(tvperm); • You can tailor AccessController, SecurityManager, ClassLoader, …
The policy specifies which permissions are available for code from various sources and executing as various principals • A policy file can be composed via a simple text editor, or via a graphical policytool utility • There 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>
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 • Thekeytool utility is used to create and administer keystores • The keystore in a policy file is used to look up the public keys of the signers specified in the grant entries • Syntax: keystore “some_keystore_url”, “keystore_type”; //where the url is relative to the policy file location • Example: keystore “keystores/.abckeystore”; • Default type is “JKS” by sun Microsystems • You can use keys and and certificates to digitally sign your java applications and applets with jarsigner utility
Grant examples • grant {permission java.io.FilePermission ".tmp", "read"; }; • grantsignedBy "Roland,Li" { permission java.io.FilePermission "/tmp/*", "read"; permission java.util.PropertyPermission "user.*"; }; • grantcodeBase "http://java.sun.com/*", signedBy "Li" { permission java.io.FilePermission "/tmp/*", "read"; permission java.io.SocketPermission "*", "connect"; }; • grantprincipal javax.security.auth.x500.X500Principal "cn=Alice" { permission java.io.FilePermission "/home/Alice", "read, write"; }; • grantcodebase "http://www.games.com", signedBy "Duke", principal javax.security.auth.x500.X500Principal "cn=Alice" { permission java.io.FilePermission "/tmp/games", "read, write"; };
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
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,..)
JASS Configuration file (jaas.config) • Sample { KeyStoreLoginModule required debug=true; }; • Other LoginModules: JndLoginModule, Krb5LoginModule, NTLoginModule, UnixLoginModule • LoginModule flag: required, requisite, sufficient, optional • How to run for JASS configuration • java -Djava.security.manager -Djava.security.policy= <policyFile> -Djava.security.auth.login.config= jaas.config <apllication> • ExampleAction • public class SampleAction implements PrivilegedAction { • public Object run() { • // privileged action will check on the permission
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);
Java Cryptography • A framework for accessing and developing cryptographic functionality such as digital signature & encryption • Java cryptography architecture design principals • Implementation independence: a provider based architecture • Algorithm 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
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 material • For each engine class there is a corresponding abstract Spi class which defines the service provider interface methods • A 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
A provider could supply one or more of the following algorithms (example “SUN” provider) • MessageDigest: MD2, SHA, MD5 • KeyPairGenerator, KeyFactory, AlgorithmParameterGenerator, AlgorithmParameters: DSA,RSA • Signature: SHA1withDSA, MD2withRSA, MD5withRSA, SHA1withRSA • CertificateFactory: X.509 • SecureRandom: SHA1PRNG • KeyStore: JKS, PKC12 • you can call java.security.Security methods getProviders, addProvider, insertProviderAt, removeProvider, …
Examples: #1 MessageDigest MessageDigest md = MessageDigest.getInstance (“SHA”); byte[] input = …; md.update(input); byte[] output = md.digest(); #2 Signature Signature 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();
#3 KeyPairGenerator • KeyPairGenerator kpg = KeyPairGenerator.getInstance (“DSA”); • kpg.initialize(1024); • KeyPair kp = kpg.generateKeyPair(); • PrivateKey privateKey = kp.getPrivate(); • PublicKey publicKey = kp.getPublic(); • #4 KeyStore • KeyStore 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
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
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);
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, PCBC • Padding: 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
Example Side A: Encryption Cipher cipher = Cipher.getInstance(“DES/ECB/PKCS5Padding”); // get key cipher.init(Cipher.ENCRYPT_MODE, key); byte[] clearText = … byte[] cipherText = cipher.doFinal (clearText); Side B: Decryprion Cipher cipher = Cipher.getInstance(“DES/ECB/PKCS5Padding”); // get key cipher.init(Cipher.DECRYPT_MODE, key); byte[] cipherText = … byte[] clearText =cipher.doFinal (cipherText);
Java Secure Socket Extension • JSSE enables secure Internet communications • Available in javax.net, javax.net.ssl, javax.security.cert • Provides factories for SSL sockets & SSL server sockets • Implementation 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
SSL provides enhancement to the standard TCP/IP • The application most commonly used with SSL is HTTP • The most obvious example of when to use SSL is in e-commerce transaction • SSL communication begins with a handshake to negotiate cipher suite (algorithms and key sizes), and optionally authenticate identity • JSSE includes an implementation that all users can utilize (SunJSSE) • KeyFactory: RSA • KeyPairGenerator: RSA • KeyStore: PKCS12 • Signature: MD2withRSA, MD5withRSA, SHA1withRSA • KeyManagerFactory & TrustManagerFactory: SunX509 • SSLContext: SSL, SSLv3, TLS, TLSv1
How to get an SSL Factory ? • The default • SSLServerSocketFactory 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)
Properties that affect SSL • System (javax.net.ssl): keyStore, keyStoreType, keyStorePassword, trustStore, trustStoreType, trustStorePassword • How to change a property ? • Command-line argument • java –Djavax.net.ssl.trustStore=myStore … • Inside the application • System.setProperty(“javax.net.ssl.trustStore”, “mystore”);
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”
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”
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