460 likes | 715 Views
Java Security. James Atlas August 5, 2008. Review. Java 3D Java Media Framework (Sound). Schedule. Today Java Security JVM Security Java Cryptography Thursday Java Garbage Collection Java Bytecode Tuesday Review Thursday Final (5-7PM). Computer Security Overview. Threats
E N D
Java Security James Atlas August 5, 2008
Review • Java 3D • Java Media Framework (Sound) James Atlas - CISC370
Schedule • Today • Java Security • JVM Security • Java Cryptography • Thursday • Java Garbage Collection • Java Bytecode • Tuesday • Review • Thursday • Final (5-7PM) James Atlas - CISC370
Computer Security Overview • Threats • Secrecy attacks:Attempts to steal confidential information • Integrity attacks:Attempts to alter information with some selfish or malicious intent • Availability attacks:Attempts to disrupt a system's normal operations James Atlas - CISC370
Computer Security Overview • Attack examples • A brute force attack typically involves searching every key until the right one unlocks the door. While that may seem like an expensive operation, in reality it is possible to preen the search using specialized tools. • A Trojan horse attack involves planting an enemy as an insider in such a way that it's not apparently noticeable. A computer virus serves as a common Trojan horse example. • A person-in-the-middle attack intercepts communication between two parties without their knowledge. They assume that they're communicating normally. James Atlas - CISC370
Computer Security Overview • Defense examples • Firewalls • Cryptography • Confidentiality • Authentication • Integrity • Nonrepudiation (proof of origin) • Auditing • Policy - access control James Atlas - CISC370
Java Security History James Atlas - CISC370
JDK 1.0 Security Model Local Code Java Virtual Machine Remote Code Sandbox Local Host System Resources (File System, Sockets, Printers…) James Atlas - CISC370
JDK 1.1 Security Model Local Code Java Virtual Machine Remote Untrusted Code Sandbox Remote Trusted Code Full Access Limited Access Local Host System Resources (File System, Sockets, Printers…) James Atlas - CISC370
JDK 1.2 Security Model All Code Security Policy Class Loader Java Virtual Machine Sandbox Full Access Limited Access Local Host System Resources (File System, Sockets, Printers…) James Atlas - CISC370
New in Java 1.4 • Separate packages that are now included as part of JDK • JCE - Java Cryptography classes • JSSE - Java Secure Sockets Extension • JAAS - Java Authentication and Authorization Services • Java GSS API - Java Generic Security Services API • Java Certification Path API James Atlas - CISC370
The basic security architecture • Java security (APIs) • (access): The Security manager • (origin): Signed Codebases • (behalf): Principle-based access control (JAAS) • cryptography • JVM security • Class loaders • Class file verification process • JVMintrinsic security features James Atlas - CISC370
Java securitySecurity Manager and its API • Central instance for access control as far as code is concerned • Policies define access to outer-domain resources • SecurityManager objects instances enforce policies, throwing SecurityExceptions • By default java programs do not have a security manager, therefore it is a good precaution to instantiate one • System.setSecurityManager(new SecurityManager()) • java -Djava.security.manager -Djava.security.policy=pURL SomeApp James Atlas - CISC370
Java securitySecurity Manager and its API • Fine-grained control to Limit access on: • SocketConnections (create, accept, multicast) • Thread Groups • Dynamic Library Loading (JNI) • Files (read, write, delete) • Access to External shared ressources (printjob, clipboard) • Program control (exit, toplevelwindow) • Runtime components (member, package, classloader) James Atlas - CISC370
Policy File Example grant signedBy "signer_names", codeBase "URL", principal principal_class_name "principal_name", principal principal_class_name "principal_name", ... { permission permission_class_name "target_name", "action", signedBy "signer_names"; permission permission_class_name "target_name", "action", signedBy "signer_names"; ... }; grant codebase "http://www.games.com", signedBy "Duke", principal javax.security.auth.x500.X500Principal "cn=Alice" { permission java.io.FilePermission "/tmp/games", "read, write"; }; • See http://java.sun.com/j2se/1.4.2/docs/guide/security/PolicyFiles.html James Atlas - CISC370
JAR JAR Cat.class Dog.class Bird.class Cat.class Dog.class Bird.class Signed hash Java securityCode Base Authentication • Java-Archives (JARs) store codebases • Proof of Origin can be be achieved by signing the jars hash Private key sign James Atlas - CISC370
Java securityJAAS: Security based on principals • Enables login functionality • Username, password • Fingerprint • ... • Execution permitted/denied depending on the identity who runs the code • Policy based access to functionality • Fine-grained permission handling possible James Atlas - CISC370
JVM securityintrinsic features • Non-continuous memory model, distinct data areas • Java stack frames (execution state) • Method area (bytecode storage) • Garbage-collected heap (object storage) • Type-safe casting • Noself-modifying code • Automated garbage-collecting disallows explicit free operation • Automatic Array bounds-checking prevents off-by-one and buffer overflow scenarios James Atlas - CISC370
JVM security Class loaders • Classloaders load a classfile as byte array into the JVM • Can load from • file, • network or • dynamically generated byte array • Can even compile on the fly (so Java behaves like Perl) • Security features • Establishing name spaces • Enforcing separation of trusted system library code from user-supplied code via parent-delegation James Atlas - CISC370
JVM security Verifier • Task: check loaded classfile for integrity • 4-step process • 1st step: structural correctness • 2nd step: data type correctness • 3rd step: bytecode checks • 4th step: symbolical references management (runtime) • Not enabled by default for apps (it is for Applets): • java -verify SomeApp James Atlas - CISC370
Verifier P A S S 1 P A S S 2 P A S S 3 P A S S 4 JVM security Classfile verification public class Cat { void bite (int times) { ... } } J V M JAVAC Class loader CA FE BA BE 00 03 00 2D 00 13 07 00 17 12 30 11 .. .. .. CA FE BA BE 00 03 00 2D 00 13 07 00 17 12 30 11 .. .. .. bytecode assembler .class public Dog .method bite I .invokestatic seekVictim ... .end method .end class James Atlas - CISC370
The Verification Process Pass 1: Basic Structural checks • the classloader delivers byte array • Magic number = 0xCAFEBABE ? • Version id: 1.1=45.3, 1.2=46.0, 1.3=47.0, 1.4=48.0 • All recognized attributes need to be in proper length • The class file must not be truncated or have extra bytes at the end • The constant pool must not contain any „superficially unrecognizable information“ James Atlas - CISC370
The Verification ProcessPass 2: Check Context-Pool (CP) information • final classes are not subclassed, and final methods are not overridden. • All classes (except java.lang.Object) must have a superclass. • Check constraints for CP-entries: For example, class references in the CP can be resolved via a field to a string reference in the CP. • Checking that all field references and method references in the CP must have legal names, classes, and type signature. James Atlas - CISC370
The Verification ProcessPass 3 : Bytecode verification • Core part of verification • Static constraints • Checking maximal local variable count throughout control flow • Checking control-flow correctness (branch always to start of instruction, not beyond end of code) • all exception-handlers are valid (no partial overlap) • ... • Structural constraints • Reachability : subroutines (scope), exception handlers • data-flow : Instances initialization and new objects, stack size James Atlas - CISC370
The Verification ProcessPass 4: delayed checks during runtime • Verifies that currently executing class is allowed to reference the given class. • The first time an instruction calls a method, or accesses or modifies a field, the verifier checks the following: • method or field class • Method or field signature • that the currently executing method has access to the given method or field • insert „quick“ optimized instructions James Atlas - CISC370
Problems with Java securityWhat is still missing • Checks in terms of hard and soft limits on • memory allocation • Thread activation • Excessive memory usage and threading utilization often leads to Denial of Service problems James Atlas - CISC370
Java Cryptography • java.security: • message digests • certificates • Java Cryptography Extension (JCE) • Encryption • Key generation and agreement • Message authentication codes • Java Secure Sockets Extensions (JSSE) • Implements SSL programmatically James Atlas - CISC370
Security provider architecture • Java security consists of engines and algorithms • An engine is an operation that a programmer can perform; eg create a message digest • An algorithm is a particular implementation of that operation; eg MD5 or SHA for message digests • The security provider interface provides an easy mechanism for substituting algorithms while leaving the basic operations unchanged • Format: • engine.algorithm eg MessageDigest.SHA James Atlas - CISC370
Security provider architecture import java.security.Provider; import java.security.Security; import java.util.Enumeration; publicclass ExamineSecurity { publicstaticvoid main(String[] args) throws Exception { Provider[] p = Security.getProviders(); for (int i = 0; i < p.length; i++) { System.out.println(p[i]); for (Enumeration e = p[i].keys(); e.hasMoreElements();) { System.out.println("\t" + e.nextElement()); } } } } James Atlas - CISC370
Java support for cryptography • Keys • Certificates • Key management • Message digests • Secure message digests • Digital signatures • Encryption & decryption James Atlas - CISC370
Keys & certificates: recap • Two kinds of keys: • secret (symmetric) • public/private (asymmetric) • Certificates can be used to authenticate public keys: • Public keys usually transmitted as part of a certificate James Atlas - CISC370
Issues • Key management and storage • Self-certification? • Hierarchy of trust James Atlas - CISC370
java.security.KeyFactory javax.crypto.SecretKeyFactory Key factory key specification Eg P=3, Q=4, … encoded key data Generation and import/export of keys java.security.KeyPairGenerator javax.crypto.KeyGenerator generator Key KeyPair James Atlas - CISC370
The Key class hierarchies: a partial view java.security.interfaces.DSAKey java.security.Key PublicKey PrivateKey java.crypto.SecretKey DSAPublicKey DSAPrivateKey RSAPublicKey RSAPrivateKey java.security.KeyPair RSAPrivateKeyCrt James Atlas - CISC370
Why so many? • Certain algorithms require methods to access key generation parameters for export • DSAKey: methods getP(), getQ(), getG() • Certain algorithms have specific roles • DHKey: Diffie-Hellman key exchange James Atlas - CISC370
Example: generate/export key pair publicclass Export { publicstaticvoid main(String[] args) throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA"); kpg.initialize(512, newSecureRandom()); KeyPair kp = kpg.generateKeyPair(); Class spec = Class.forName("java.security.spec.DSAPrivateKeySpec"); KeyFactory kf = KeyFactory.getInstance("DSA"); DSAPrivateKeySpec ks = (DSAPrivateKeySpec)kf.getKeySpec(kp.getPrivate(), spec); FileOutputStream fos = new FileOutputStream("exportedKey"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(ks.getX()); oos.writeObject(ks.getP()); oos.writeObject(ks.getQ()); oos.writeObject(ks.getG()); } } Derived from: Oaks (2001) James Atlas - CISC370
Distributing public keys: certificates • Recall that a key doesn’t provide any authentication of the owner • A digitally-signed document + public key doesn’t guarantee that the document came from X • Certificates solve the problem. A Certificate Authority verifies the public key • However, anyone can obtain a basic level certificate • Bootstrapping problem? Who verifies the certificate containing the public key of the CA? • Workable solution: provide public keys of main CAs (eg in browser or in Java implementation) James Atlas - CISC370
Certificates in Java • java.security.cert.Certificate byte[] getEncoded() void verify(PublicKey pk) publicKey getPublicKey() • java.security.cert.CertificateFactory Certificate generateCertificate(InputStream is) • Imports a certificate (doesn’t generate from scratch) James Atlas - CISC370
Certificates in Java publicstaticvoid main(String[] args) throws Exception { FileInputStream fr = new FileInputStream("./resources/sample.cer"); CertificateFactory cf = CertificateFactory.getInstance("X509"); X509Certificate c = (X509Certificate)cf.generateCertificate(fr); System.out.println("Certificate for: " + c.getSubjectDN()); System.out.println("issued by: " + c.getIssuerDN()); System.out.println("valid from: " + c.getNotBefore() + " to " + c.getNotAfter()); System.out.println("generated with: " + c.getSigAlgName()); } Derived from: Oaks (2001) James Atlas - CISC370
Revoked certificates • Expiration date is sometimes not sufficient • For immediate invalidation, need a Certificate Revocation List (CRL) • Not clear yet how CA issues CRL yet • Support in Certificate class James Atlas - CISC370
Key & certificate management • keystore: file (or may be database) holding keys and certificates • Alias: keystore-specific name for entity • Distinguished name (DN): longer name for entity (but not guaranteed unique) • Usually includes common name; organisation; location; state; country • Manipulated using keytool or programmatically James Atlas - CISC370
keytool James Atlas - CISC370
Secret key management • Recall that in public key systems, the private key must be kept private, but that in secret key systems, the secret key must be shared • Management problem! • Use non-electronic means to distribute • Use public key encryption to send encrypted key (eg SSL) • Use key agreement algorithm • keytool doesn’t understand secret keys James Atlas - CISC370
Message digests import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.security.MessageDigest; publicclass Send { publicstaticvoid main(String[] args) throws Exception { FileOutputStream fos = new FileOutputStream("test"); MessageDigest md = MessageDigest.getInstance("SHA"); ObjectOutputStream oos = new ObjectOutputStream(fos); String data = "Martins message"; byte[] buf = data.getBytes(); md.update(buf); oos.writeObject(data); oos.writeObject(md.digest()); } } update() add data to digest digest() compute digest James Atlas - CISC370
publicclass Receive { publicstaticvoid main(String[] args) throws Exception { FileInputStream fis = new FileInputStream("test.md"); MessageDigest md = MessageDigest.getInstance("SHA"); ObjectInputStream ois = new ObjectInputStream(fis); String data = (String)ois.readObject(); System.out.println("Got message: " + data); byte[] buf = (byte[])ois.readObject(); md.update(data.getBytes()); if (MessageDigest.isEqual(md.digest(), buf)) { System.out.println("Message is valid"); } else { System.out.println("Message was corrupted"); } } } Source: Oaks (2001) • Recall that to verify a message digest, must read in message and its digest, compute the digest, and compare the two • isEqual() James Atlas - CISC370
Example: Encryption publicclass Encrypt { publicstaticvoid main(String[] args) throws Exception { KeyGenerator kg = KeyGenerator.getInstance("DES"); Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding"); Key key = kg.generateKey(); c.init(Cipher.ENCRYPT_MODE, key); byte[] input = "Secret message".getBytes(); byte[] encrypted = c.doFinal(input); byte[] iv = c.getIV(); IvParameterSpec ips = new IvParameterSpec(iv); c.init(Cipher.DECRYPT_MODE, key, ips); byte[] output = c.doFinal(encrypted); System.out.println("The string was: " + new String(output)); } } Derived from: Oaks (2001) James Atlas - CISC370