Java Programming Advanced Features Security Volume II - Chapter 9 Agenda About Security Application Security Java Security from the Ground Up Standalone Java Application Techniques 2 About Security Common Security Threats Three concepts of CIA security model Definition of security 3 Common Security Threats Identity interception Steal your identity and use it as their own Masquerading Grab your identity and use it elsewhere with the intention of perpetrating fraud Replay attack Capture your request and replay that request Data interception and manipulation 4 Read your data (such as credit card info) Common Security Threats Repudiation Deny your/his completed transaction Denial of Service Terminate the service 5 Three concepts of CIA security model Confidentiality information must not be disclosed to any unauthorized person Integrity authorized actions (unauthorized data changes) separation and protection for resources error detection and correction (data corruption) Availability presence of objects or service in a usable form capacity to meet service needs adequate timeliness of a service 6 Definition of security Detect Detect how, when and where intrusion has taken place Protect 7 Manage people and the Information System in an effective manner so as to protect against unauthorized usage Definition of security React react to an intrusion ensure that penetration does not happen again. vulnerability is eliminated Recover 8 recover all data and programs from a breach in security Application Security - Not just technology; it’s a process… - System-level Security Vs. Application-level Security Application System 9 Level { Level { Application code Java/J2EE APIs JVM Operating System System-level Security Vs. Application-level Security 10 Systemlevel security Applicationlevel Security Enterprise Data Defeating System-level security may not provide attackers with appropriate access to the applicationlevel data, logic, or methods that they seek Attacker System-level Security Vs. Application-level Security (cont.) Applicationlevel Security Systemlevel security Enterprise Data Work together to build a secure system/application combination 11 Attacker Attacker System-level Security Vs. Application-level Security (cont.) It is more efficient to push some security responsibilities up to the application level instead of handling them at the operating-system level Application code Java/J2EE Application code Java/J2EE Application code Java/J2EE JVM (Solaris) OS 12 APIs (Solaris) JVM APIs (IBM AIX) OS (IBM AIX) JVM APIs (MS Window) OS (MS Window) Java Security from the Ground Up Java Language Safety Features Java Security Model Java Security Architecture 13 Java Language Safety Features Objects have access levels: 14 private: Accessible by defining class package (default): Accessible by classes in the same package protected: Same as package, with addition of access by any subclass public: Accessible by any class Java Language Safety Features Access methods are strictly adhered to 15 No pointers (no access to arbitrary memory and automatic garbage collection) “final” methods or variables cannot be changed Variables MUST be initialized before use Array bounds are enforced Strict object casting rules Java Security Enforcement 16 Java Security Enforcement Enforcement happens at different times Compile time enforcement Class load time enforcement Runtime enforcement 17 Compile Time Enforcement Java Source Java Compiler Bytecode Class Loader Bytecode Verifier Java Virtual Machine Runtime 18 Compile Time Enforcement Validate language syntax Enforce method and variable access rules Enforce variable initialization Enforce some casting operations 19 Class Load Time Enforcement Java Source Bytecode Java Compiler Class Loader Bytecode Verifier Java Virtual Machine Runtime 20 Class Load Time Enforcement Bytecode verification Verifies class file format Accesses objects as correct type Final classes are not subclassed Final methods are not overridden Every class has a single superclass Verify that casting legality checks are in place 21 Class Load Time Enforcement No operand stack overflows All field and method accesses are legal Method calls use correct number & types of arguments 22 Runtime Enforcement Java Source JavaCompiler Compiler Java Bytecode Class Loader Bytecode Verifier Java Virtual Machine Runtime 23 Runtime Enforcement Array bounds checking Throws ArrayIndexOutOfBoundsException Object casting Throws ClassCastException Security Manager Throws SecurityException Depends on the Access Controller 24 Java Security Model 25 Java Security Model – a strictly defined arena where they cannot affect other system resources. It provides virtually no flexibility. Sandbox 26 Java Security Model (cont.) 27 What does this code do? 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 What happens when executing ? Use caution when executing Applets as Applications 1. 2. 3. public class BadApplet extends Applet{ public void init(){ try { Runtime.getRuntime().exec(“rmdir foo”); } catch (Exception e) { System.out.println(e); } } public static void main(String args[]) { BadApplet a = new BadApplet(); a.init(); } } Exception thrown if run in an Applet container Exception thrown if run as an application using Applet security Java –Djava.security.manager BadApplet OK if run as an application Java BadApplet 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 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 OS Code signing will be discussed later. 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. Security Policy Files Permission classes: java.io.FilePermission java.awt.AWTPermission java.net.SocketPermission java.net.NetPermission java.util.PropertyPermission java.lang.RuntimePermission java.security.AllPermission …. See page 712 for details Security Policy Files java.io.FilePermission Targets: File a file Directory a directory Directory/* all files in the directory * all files in current directory Directory/- 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 Security Policy Files java.net.SocketPermission Targets: (hostRange:portRange) HostName or IPAddreses a single host localhost or empty local host *.domainSuffix all hosts whose domain names end with the suffix . E.g. *.com * all hosts :n :n1-n2 single port all ports in the range Actions: accept, connect, listen Security Policy Files An example policy file grant 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"; }; Security Policy Files policytool: a utility for creating policy files Security Policy Files Location of policy file: On client machine Method 1: ${user.home}/.java.policy 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 On XP: 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. 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 the policy file grant codeBase "http://www.cs.ust.hk/~liao/comp201/codes/secu/awt/" { permission java.awt.AWTPermission "showWindowWithoutWarningBanner"; }; 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"; }; 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"; }; In your paper try to explain the contents following permission policy file Outline Using java security mechanisms Security policy files Code signing 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 give more permissions to applets signed by THE developer. 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! Code Signing /Developer Enter keystore password: 123456 What is your first and last name? [Unknown]: Renlan Liao What is the name of your organizational unit? [Unknown]: Computer Science What is the name of your organization? [Unknown]: Hong Kong University of Science and Technology What is the name of your City or Locality? [Unknown]: Hong Kong What is the name of your State or Province? [Unknown]: Hong Kong What is the two-letter country code for this unit? [Unknown]: CN Is <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 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.cert Owner: 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 Sign applets Create a jar file jar cvf MyApplet.jar *.class Run the jarsigner tool jarsigner –keystore Liao.store MyApplet.jar Liao Keystore containing private key Alias of private key Code Signing /Client Add public key received to his/her store of public keys keytool –import –keystore certs.store –alias liao –file liao.cert Include location of public key store to policy file Keystore “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 /User Add signedBy “alias” to grant clauses in policy file grant signedBy “liao" { permission java.awt.AWTPermission "showWindowWithoutWarningBanner"; }; 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/ Effective Java: Creating and Destroying Objects Agenda Material From Joshua Bloch Effective Java: Programming Language Guide Cover Items 1-7 Bottom Line: Understand Java Construction First C++ Creation/Destruction More Complex Item 1: Consider Static Factory Methods Instead of Constructors Constructor Calls vs Static Factory Method Alternate way to get an object Sometimes replaces constructors Sometimes augments constructors // Simple example from Boolean class public static Boolean valueOf (boolean b) { return b ? Boolean.TRUE : Boolean.FALSE; } Item 1: Advantages Unlike constructors, static factory methods Can have meaningful names Need not create new instances – Can return any subtype of return type – Reduces client dependency on specific class Can reduce verbosity of creating parameterized type instances Advantage 1: Meaningful Names Consider the constructor/factory pair: // Constructs a randomly generated positive BigInteger // that is probably prime, with the specified bitLength BigInteger (int bitLength, int certainty, Random rnd) vs. // Returns a positive BigInteger that is probably prime,// with the specified bitLength. BigInteger.probablePrime (int bitLength, Random rnd) – – Note: The extra constructor argument avoids a clash with another constructor Unique parameter lists on constructors are really restrictive Advantage 2: Not Required To Create New Object Instance-controlled classes can be useful Can avoid creating unnecessary duplicate objects –Boolean.valueOf(boolean) is an example Can guarantee a “singleton” or “noninstatiable” object Can allow for very fast “equals” test Advantage 3: Can Return Subtype of Return Type Consider the java.util.Collections class 32 Convenience implementations of Collection interfaces – All are static factory methods Interface return type vs. actual classes Static factory methods can hide multiple implementations Advantage 4: Reduce Verbosity of Parameterized Type Instances // Parameterized type instances Map<String, List<String>> m = new HashMap<String, List<String>>(); vs. // Static factory alternative public static <K, V> HashMap<K, V> newInstance() { return new HashMap<K, V>(); } // Now, client code looks like this // Compiler does type inference! Map<String, List<String>> m = HashMap.newInstance(); Item 1: Disadvantages of Static Factory Methods Subclassing impossible without constructors Naming conventions necessary – valueOf – effectively a type converter (also just of) – getInstance – return instance described by parameters – newInstance – like getInstance, but guarantees distinct object – getType – like getInstance, but converts type – newType – like newInstance, but converts type Item 2: Consider a Builder vs. Many Constructor Parameters Static factories and constructors don’t scale well to large numbers of optional parameters Bloch’s examples: NutritionFactsTelescoping.java NutritionFactsBeans.java NutritionFactsBuilder.java The last version enjoys significant advantages The problem ? Consider the case of a class representing the Nutrition Facts label that appears on packaged foods. These labels have a few required fields: serving size, servings per container, and calories per serving and over twenty optional fields—total fat, saturated fat, trans fat, cholesterol, sodium, and so on. Most products have nonzero values for only a few of these optional fields. What sort of constructors or static factories should you write for such a class? Telescoping Constructor Pattern. Traditionally, programmers have used the telescoping constructor pattern. Provide a constructor with only the required parameters, Another with a single optional parameter, A third with two optional parameters, and so on, culminating in a constructor with all the optional parameters. Here’s how it looks in practice What do you think of this code? Is it good or bad? Continue…. When you want to create an instance, you use the constructor with the shortest parameter list containing all the parameters you want to set: Disadvantages This constructor invocation will require many parameters that you don’t want to set, but you’re forced to pass a value for them anyway. It is hard to write client code when there are many parameters, and harder still to read it. If the client accidentally reverses two such parameters, the compiler won’t complain, but the program will misbehave at runtime. Think of another solution ?????? Second Solution A second alternative when you are faced with many constructor parameters is the JavaBeans pattern. How does it look like?????? JavaBeans Pattern Solution Problems It is easy, if a bit wordy, to create instances, and easy to read the resulting code. JavaBeans pattern has serious disadvantages of its own. Construction is split across multiple calls, a JavaBean may be in an inconsistent state partway through its construction. The class does not have the option of enforcing consistency merely by checking the validity of the constructor parameters. It can cause errors at runtime, as the compiler cannot ensure that the programmer calls the freeze method on an object before using it. Builder pattern Solution There is a third alternative that combines the safety of the telescoping constructor pattern with the readability of the JavaBeans pattern. It is a form of the Builder pattern Instead of making the desired object directly, the client calls a constructor (or static factory) with all of the required parameters and gets a builder object. Then the client calls setter-like methods on the builder object to set each optional parameter of interest. Finally, the client calls a parameterless build method to generate the object, which is immutable. The builder is a static member class of the class it builds Item 3: Enforce Singleton Property A Singleton is a class that’s instantiated exactly once Two approaches before Enums: Public static member (a constant, of course) Public static factory method Enum singleton is now preferred Lots of subtle advantages: security, serialization, etc. Item 3: Code Example // Option 1: public final field public class Elvis { public static final Elvis INSTANCE = new Elvis(); private Elvis() {...} } // Option 2: static factory method public class Elvis { private static final Elvis INSTANCE = new Elvis(); private Elvis() {...} public static Elvis getInstance() { return INSTANCE; } } // Option 3: Enum type – now the preferred approach public enum Elvis { INSTANCE; Item 4: Enforce Noninstantiability With a Private Constructor Some classes just group static methods and/or fields Trying to enforce noninstantiability by making class abstract doesn’t work Makes no sense to instantiate such a class Subclassing is possible Clients are led to believe subclassing makes sense However, a private constructor does the job Item 4: Code Example // Noninstantiable utility class public class UtilityClass { // Suppress default constructor for noninstantiability private UtilityClass() { throw new AssertionError(); } ... // Remainder of class omitted } // Note that no subclassing is possible (constructor chaining...) // Note that client can’t call constructor // Note that if constructor is mistakenly called inside class,there is an immediate assertion violation. Item 5: Avoid Creating Unnecessary Objects On the one hand, performance is a secondary concern behind correctness On the other, gratuitous object creation is just bad programming // String s = new String(“stringette”); // Don’t do this! vs. // String s = “stringette”; // Let JVM optimize for you // Also see earlier Boolean.valueOf() static factory example Item 5: Code Example public class Person { private final Date birthDate; // Other fields, methods, and constructor omitted // DON’T DO THIS public boolean isBabyBoomer() { // Unnecessary allocation of expensive object Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone(“GMT”)); gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0, 0); Date boomStart = gmtCal.getTime(); gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0, 0); Date boomEnd = gmtCal.getTime(); return birthDate.compareTo(boomStart) >= 0 && birthDate.compareTo(boomEnd) < 0; } Item 5: Code Example Fixed public class Person { private final Date birthDate; // Other fields, methods, and constructor omitted private static final Date BOOM_START; private static final Date BOOM_END; static { // Note static block Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone(“GMT”)); gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0, 0); BOOM_START = gmtCal.getTime(); gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0, 0); BOOM_END = gmtCal.getTime(); } public boolean isBabyBoomer() { return birthDate.compareTo(BOOM_START) >= 0 && birthDate.compareTo(BOOM_END) < 0; } } Item 5: Autoboxing Overhead // Hideously slow program! Can you spot the object creation? public static void main(String[] args) { Long sum = 0L; for (long i =0; i < Integer.MAX_VALUE; i++) { sum += i; } System.out.println(sum); } // Lessons: 1) prefer primitives to Boxed primitives // 2) watch for unintentional autoboxing The variable sum is declared as a Long instead of a long, which means that the program constructs about 231 unnecessary Long instances Item 7: Avoid Finalizers finalize() is a method in the Object class Finalizers: unpredictable, dangerous, unnecessary! What the garbage collector may call when cleaning up an unused object They are NOT the analog of C++ destructors There is no guarantee a finalizer will ever be called Finalizers have severe performance penalties Instead, provide explicit termination methods Sometimes requires “finalizer chaining” Item 7: Code Example // try-finally block guarantees execution of termination method // termination method ensures resources are released // Example resources: database connections, threads, windows Foo foo = new Foo(); try { // Do what must be done with foo } finally { foo.terminate(); // Explicit termination method in Foo Item 7: Finalizer chaining // Manual finalizer chaining // Only do this if you *have* to use the finalizer @Override protected void finalize() throws Throwable { try { .. . // Finalize subclass state } finally super.finalize(); // Note order of finalizer chaining } } // Also consider “Finalizer Guardian” idiom for public, nonfinal // classes. The goal is to ensure that finalization takes place // even if subclass finalizer fails to invoke super.finalize()