java ultimate security [מצב תאימות] - john...

50
Java Ultimate Security Rony Keren [email protected] Topics Security Threats OWASP Java Secured Code Java Security Manager JCE & Java keytool Bean Validation API JAAS Java Web Security Authentication Declarative Security Application Server Security Authentication Declarative Security JACC Server Hardening - Administration 1

Upload: phungnhu

Post on 05-Apr-2018

221 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

Java Ultimate Security

Rony [email protected]

Topics

• Security Threats

• OWASP

• Java Secured Code

• Java Security Manager

• JCE & Java keytool

• Bean Validation API

• JAAS

• Java Web Security– Authentication

– Declarative Security

• Application Server Security– Authentication

– Declarative Security

– JACC

– Server Hardening - Administration

1

Page 2: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

Security Threats

• In general, any aspect of our service / application / domain is threatened

• Hardware– Hardware corruption

– Hardware intrusion

– Driver manipulations

• OS– Memory abuse

– File system corruption

– Viruses and Trojan horses

• Server– Configuration manipulation

– Services abuse

– Network over-flow and starvations

Security Threats

• Databases– Intrusion

– Data injection & corruption

– Effect availability & performance

• Applications– Plug-in corruption

– Log over-flow

– Thread & resource abuse

– Code injection

– Exceptions

• Web– Code injections

– HTTP manipulation

– Exploiting client browsers

2

Page 3: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

Security Threats

• All a hacker needs is us forgetting one tiny thing…

• Example:– You put lot of efforts on protecting your domain & hardware, paid for the best

system administrators to configure your OS and purchased cutting edge security tools for your DB and your applications environment.

– But your developer failed to check some user input…

– Hacker may inject malicious code – executed in your domain and enjoy all your application permissions…

– All the efforts are now practically worthless…

OWASP

• Open Web Application Security Project (OWASP)

“ Our mission is to make software security visible, so that individuals and organizations worldwide can make informed decisions about true

software security risks”

• Provides: information, activities, news, APIs, list of threats and known attacks

3

Page 4: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

OWASP

• OWASP top threads

– A list of web attacks • your web modules will probably suffer from

• any web developer must be at least aware of

OWASP

1 – Cross Site Scripting – XSS

4

Page 5: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

OWASP

• 1 – Cross site scripting – XSS

– When user input is shared with others without proper validation and encoding

– Malicious code can be easily executed on innocent client machines

– See how simple it is…

<% String user=request.getParameter(“user”); %>…<%= user %>

index.jsp?user=guest<script>alert('attacked')</script>

OWASP

• 1 – Cross site scripting – XSS

– So ? What’s the big deal ? It’s just JavaScript running in our browser…

– Well, JavaScript, when allowed (as shown), might…• Steal your cookies

• Simulate user activity

• Install malicious ActiveX plugin

5

Page 6: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

OWASP

• 1 – Cross site scripting – XSS

• How to protect ?– Sanitize user input

– Use escaping libraries

– Each client-side tech. has it own escaping rules (HTML, CSS, JavaScript…)

– OWASP provides libraries in several languages including Java

OWASP

2 – Injection Flaws

6

Page 7: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

OWASP

• 2 – Injection flaws

– When non trusted data is delegated to an interpreter

– Malicious data can be easily injected to your domain

– Might be LDAP, JNDI, XPATH, JPQL, SQL

– See how simple it is…

stmt.executeQuery(“SELECT * FROM users WHERE user=‘”+user+”’”);return rs.next();

“surprise!!’ or ‘1’=‘1”

OWASP

• 2 – Injection flaws

• How to protect ?– Awareness is the name of the game.

– Sanitize and escape application input

– Consider sanitize 3rd parties data (like DB) as well, if shared with other applications

7

Page 8: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

OWASP

3 – Malicious File Execution

OWASP

3 – Malicious file execution

– When non trusted files or paths are executed on web server

– Might lead to file corruption, threads locked on FS

– Configuration files might be hacked

– Authentication storage can be manipulated

– See how simple it is…and you should know what to do by now

String file=request.getParameter(“file”);File loc=new File (getContext().getRealPath(“/mySite”),file);try(FileOutputStream out=new FileOutputStream(loc)){out.write(…);

web.xml

8

Page 9: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

OWASP

4 – Insecure Direct Object Reference

OWASP

• 4 – Insecure direct object reference

– When real internal data is exposed to users

– Example: Accept account-ID from user and use it as PK…• SQL Injection checks will not help here…

String id=request.getParameter(“userID”);stmt.executeQuery(“SELECT * FROM users WHERE user_id=‘”+userID+”’”);

1122334455‐6

1122334455‐6

9

Page 10: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

OWASP

• 4 – Insecure direct object reference

– Protecting:• Avoid exposing internal sensitive data

• Prefer index values mapped to real data

• Store data in sessions

• Use authorization when submit / view sensitive data

OWASP

5 – Cross Site Request Forgery

10

Page 11: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

OWASP

• 5 – Cross site request forgery

– When your application authenticates users by session-cookies, IPs, SSL certificated and ‘Remember Me’ feature

– Example: a site uses physical user IP to support “Remember Me”• Now, innocent client logs in. Than client’s IP is stolen by another site infected with XSS.

• Hacker may use your IP address to log-in via “Remember Me”…

String ip=request.getRemoteHost();rememberMeMap.put(ip, userData);

143.4.34.99

143.4.34.99

OWASP

• 5 – Cross site request forgery

– Protecting• Use tokens

– Each response holds a unique token value stored also in client session

– Every-time a client submit a request – the token is checked against the one on server

– If a hacker steals client session cookie – he will try to make a request with it…

– In Java prefer SecureRandom rather than using Random or Math.random()

» Uses hardware noises for randomizing values

11

Page 12: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

OWASP

6 - Information Leakage

OWASP

• 6 – Information leakage

– When your application exposes internal mechanisms by throwing exceptions or showing log messages to the client

– Hackers can learn about hosting server, stack traces, connection opening…

– Hackers may flood your systems with Ex & logs

– Java – avoid checked exceptions

12

Page 13: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

OWASP

7 – Authentication Flaws

http://yourSite.com/admin/…user = adminpassword = 1234

OWASP

• 7 – Authentication Flaws

– When your domain has unprotected entries and badly managed sessions

• Unprotected entries are holes in your domain– Static admin server IP

– unprotected admin server channels ( “/admin/” , default user/pass…)

– Badly managed “forgot password” functionality (send email with temp link to reset pass)

• Session Fixation – Session that remains too long might be exploited by hackers

– They might create sessions and ‘hand’ it to an innocent client who is about to log in…

– They might change session cookie expiration on client

13

Page 14: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

OWASP

• 7 – Authentication Flaws

– Protecting:

• Unprotected entries– Your admin server should be down in production

– Change default admin passwords and users

– “forgot password” - send email back to the requestor with temp link to reset password

• Session Fixation – Creating a session can be done only after invalidating the previous one

– Don’t keep your session too long just to save logins…

– Never implement your own session mechanism

OWASP

8 – Insecure Cryptographic Storage

14

Page 15: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

OWASP

• 8 – Insecure Cryptographic Storage

– When your application fails to hide sensitive data

• Non-encrypted data

• Using custom encryption algorithms

• Use weak known algorithms

• Unprotected key stores

OWASP

• 8 – Insecure Cryptographic Storage

– Protecting

• Encrypt data

• Using strong encryption algorithms – RSA – asymmetric – (later)

– AES – strong encryption algorithm

• Encrypt your key store

• Use hashing for authentication data – Salt the data, than encrypt

– SHA-1, SHA-2, MD5…

Hashing

• One way encryption

• Collision free• Checking is a matter of time• Therefore good for authentication• If your storage hacked…

15

Page 16: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

OWASP

9 – Insecure Communication

OWASP

• 9 – Insecure communication

– When authorization and other sensitive data submit are done over non-encrypted protocol

– Use secured socket layer - SSL

– Use it also for intra domain communication• Clusters, remote management, DB & Messaging servers…

16

Page 17: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

OWASP

• 9 – Insecure communication

– SSL / TLS (Transport Layer Security)

– Secured HTTP is HTTPS

– How HTTPS works ? Few words on encryption:• Symmetric encryption

– Both sided uses the same key to encryption & decryption

• Asymmetric encryption –– Each side uses a different key

» One side publishes a public key and keeps a private key

» Client obtains a public key and use it to encrypt his message

» Once the client encrypted the message – only owner of private key can view it

» Server uses private key to decrypt it

– Public key is the result of two huge primer numbers multiplied

– Private key contains the two primer numbers

OWASP

• 9 – Insecure communication

• HTTPS– Handshake

• Client sends strongest supported encryption & hashing algorithms

• Server sends back his algorithms + a public key

– Client approves public key and uses it to encrypt a symmetric key• The symmetric key will be used for the rest of the secured communication

– Server uses his private key to obtain the symmetric key

– Deciding on a symmetric key is done with asymmetric encryption – slower..

– Messages are encrypted with symmetric encryption – faster..

17

Page 18: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

OWASP

• 9 – Insecure communication

– Wait,• When we exchange secrets and decide on a symmetric key – how do we know for sure server

identity ??

• What if the page looks like what we expect but actually sends our secrets somewhere else ??

– Certified Authorities (CA)• Server digital certificate can be issued by well known authorities

• CAs are trusted organizations

• Provides digital signature for public keys

• Public keys can be signed with CA certificates

Issuer Usage Market share

1 Comodo 5.3% 35.6%

2 Symantec 4.7% 31.9%

3 GoDaddy 2.1% 14.0%

4 GlobalSign 1.5% 10.0%

5 DigiCert 0.4% 2.7%

Wiki, May 2015

Trusted public key Un‐trusted public key

OWASP

10 – Unrestricted URLs

18

Page 19: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

OWASP

• 10 – Unrestricted URLs

– When internal referencing and forwarding URLs are unsecured

– We tend to forget that • Client controllers and AJAX calls can be investigated

• URLs which are never given and shown to clients can still be invoked…

– Some hackers are very talented in guessing… most are very patient…

OWASP

11– HTTP Splitting

HTTP/1.1 200 OKenter HTTP/1.1 200 OK

Set cookies:

HTTP/1.1 200 OKenter

19

Page 20: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

OWASP

• 11 – HTTP splitting

– When HTTP status header is planted in the application response

– Validate user cookies

for (Cookie c : request.getCookies()) {//validate c

}

OWASP

• General Tips

– Watchdogs• Independent background processes or threads

• May do the following:– Restart & Handle crashed servers

– Alert / discard stacked threads / resources

– Rollback recorded Tx.

– Non-Repudiation• Give the client several attempts to login and investigate your logs

• Honest mistakes can easily be filtered from those who are guessing…

– Honey pots• Return 200 OK

• Allow hackers to navigate in a void “/admin/” domain and learn about their actions

20

Page 21: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

Java Secured Code

• Code injection – Malicious jars

– Providing malicious implementations to be executed in a container

– Hacking to file system and placing jars in lib\ext

• Some coding rules might reduce the damage and harden your application

Java Secured Code

• Accessibility

– Use the narrowest scope required• Public

• Protected

• Package friendly

• Private

– Use private internal data-types for sensitive data which are not exposed in your façade

• Avoid exposing your data types to the client

– Avoid overriding methods to be more public

21

Page 22: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

Java Secured Code

• Design for inheritance

– Abstraction makes your system works according to contracts

– Contract contributes to code security:

• Sensitive methods can be defined as final

• Operations are done in a specified order

– Methods invoked from constructors should be final

Java Secured Code

• Immutable objects

– Make your sensitive data types immutable

– Are thread safe – no race condition

– Improves performance

– Once calculated cannot be manipulated

22

Page 23: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

Java Secured Code

• Design patterns

– Use Builder when constructing mutable objects• Encapsulate how objects are created and populated

– Use Factories instead of letting client action instantiate objects • Control the number of instances

• Mange cache for sharable objects

• Maintain role-based sharing policy

– Best Singleton is Enum• Anyway try to avoid using it

• Singletons are easy to track via reflection

• Usually, many objects depends on it

Java Secured Code

• JNI

– Native code is not running in the JVM sandbox

– Wrap each method with security checks

• Verify paths and references are allowed

• Make sure that user is allowed to use external resource

• Prevent buffer overflow by checking data size

23

Page 24: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

Java Secured Code

• IO

– Avoid storing sensitive data. Make it transient

– Serializable subclasses handed by clients should by checked before stored

• Provide a custom writeObject()

– When loading objects – verify before using

• In case someone managed to hack to your domain and play with your files…

• Same goes with DB...

Java Secured Code

• Broken constructors

– What happened when an exception is thrown from a constructor ?

– You will get an exception

– The partially constructed object will get finalize() callback and GCed

– Make sure you don’t throw exception in your constructors

– Make finalize() final

24

Page 25: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

Java Secured Code

• Application architecture

– Separate security and business logic

– In JEE

• Each App. Server provider has its own implementation for JAAS (later)

• JEE modules define portable roles

• Roles are mapped to actual users/group when deployed to App. Server

Java Security Manager

• Java Access Control Model

• Default security manager– Uses lib/security/java.policy

– Disallows port opening, file system updates

– Allows to stop threads, get OS & JRE version info, reflection, Ext. class loader

• Is activated when you run applets in your browser’s JRE

• It is disabled when you use a JRE installed as part of JDK

• You can provide your own implementation for Security Manager– Always make it more restrictive

– Once a security manager is registered it cannot be replaced or overridden

25

Page 26: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

Java Security Manager

• Extension Class Loader

– Loads classes from jars located in your jre/lib/ext

– Default security policy provides ‘All Permission’ to classes loaded from Ext CL

– Consider changing this

– Hackers may plant jars and inject code that has permissions to do harm

Java Security Manager

• Activating default SecurityManager example:

public static void main(String[] args) {

//use default security manager to disable file system read permissionSystem.setSecurityManager(new SecurityManager());

//if file read is permitted ‐ you'll get a file list printed. for(String file:new File("c:\\").list())

System.out.println(file);

}

26

Page 27: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

Java Security Manager

• Activating custom SecurityManager example:

public class CustomSecurityManager extends SecurityManager {

@Overridepublic void checkRead(String file) {

//do your business…

// consider super.checkRead(file);

//throw SecurityException when vetoing request  }

}System.setSecurityManager(new CustomSecurityManager());

Java Security Manager

• Security Policy File– Holds permissions bounded to code bases

– Permissions• Set of predefined permissions

• Custom permission can be added

– Codebases• Source location

• Mapped to specified permissions

java.security.AllPermissionjava.security.SecurityPermissionjava.security.UnresolvedPermissionjava.awt.AWTPermissionjava.io.FilePermissionjava.io.SerializablePermissionjava.lang.reflect.ReflectPermissionjava.lang.RuntimePermissionjava.net.NetPermissionjava.net.SocketPermissionjava.sql.SQLPermissionjava.util.PropertyPermissionjava.util.logging.LoggingPermissionjavax.net.ssl.SSLPermissionjavax.security.auth.AuthPermissionjavax.security.auth.PrivateCredentialPermissionjavax.security.auth.kerberos.DelegationPermissionjavax.security.auth.kerberos.ServicePermissionjavax.sound.sampled.AudioPermission

grant codebase “file$((java.ext.dirs))/*” {permissions: java.security.AllPermission;

};  

27

Page 28: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

Java Security Manager

• Default Security Policy File: //Standard extensions get all permissions by default grant codeBase "file:${{java.ext.dirs {{ "*/}} permission java.security.AllPermission;};

//default permissions granted to all domains grant  {

// Allows any thread to stop itself using the java.lang.Thread.stop() // method that takes no argument. // Note that this permission is granted by default only to remain // backwards compatible. // It is strongly recommended that you either remove this permission // from this policy file or further restrict it to code sources // that you specify, because Thread.stop() is potentially unsafe. // See the API specification of java.lang.Thread.stop() for more // information. permission java.lang.RuntimePermission "stopThread ";

// allows anyone to listen on dynamic ports

permission java.net.SocketPermission "localhost:1022", "listen ";

Java Security Manager

• Default Security Policy File cont. //"standard" properties that can be read by anyone permission java.util.PropertyPermission "java.version", "read "; permission java.util.PropertyPermission "java.vendor", "read "; permission java.util.PropertyPermission "java.vendor.url", "read "; permission java.util.PropertyPermission "java.class.version", "read "; permission java.util.PropertyPermission "os.name", "read "; permission java.util.PropertyPermission "os.version", "read "; permission java.util.PropertyPermission "os.arch", "read "; permission java.util.PropertyPermission "file.separator", "read "; permission java.util.PropertyPermission "path.separator", "read "; permission java.util.PropertyPermission "line.separator", "read "; permission java.util.PropertyPermission "java.specification.version", "read "; permission java.util.PropertyPermission "java.specification.vendor", "read "; permission java.util.PropertyPermission "java.specification.name", "read "; permission java.util.PropertyPermission "java.vm.specification.version", "read "; permission java.util.PropertyPermission "java.vm.specification.vendor", "read "; permission java.util.PropertyPermission "java.vm.specification.name", "read "; permission java.util.PropertyPermission "java.vm.version", "read "; permission java.util.PropertyPermission "java.vm.vendor", "read "; permission java.util.PropertyPermission "java.vm.name", "read ";};

28

Page 29: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

Java Security Manager

• Example of using security check in java APIs:

public class File {….public String[]  list() {SecurityManager sm = System.getSecurityManager();if(sm != null) {

sm.checkRead(path);}rerturn fs.list(this);

}….

}

Java Security Manager

• Privileged executions

– Permissions are checked along the execution stack

– In some cases we provide our internal logic, which cannot be overridden / replaced

– In those cases we might want to get rid of the check

– If we are the only one to invoke it, and data is sanitized or no data involved – we would like to skip permission checks…

29

Page 30: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

Java Security Manager

• Privileged execution example:

public void doSomethingSafe() {PrivilegedAction<Result> p = new  PrivilegedAction () {

public Result run(){// perform sensitive operationsreturn result;

}}

Result r=AccessController.doPrivileged(p);

JCE

• Java Cryptography Extension

– Is part of JSE

– Supports• Symmetric ciphers

• Asymmetric ciphers

• Key generation

• Key storage

• Key retrieval

• Digital signatures

• Sealed objects

• Signed objects & jars

– Common operations are implemented and can be used via keytool

30

Page 31: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

JCE

• Java Cryptography Extension

– Cipher• Holds encryption and decryption algorithms

– Sealed Objects• Object serialization is decrypted with a Cipher

• Object can be decrypted back to its original state using the right Cipher

– Signed Objects• Object with a Signature appended to its byte[] serialization

• Signature are populated with digital certificate information loaded from a key store by alias

Java keytool

• keytool is a key and certificate management utility

• It allows users to administer their own public/private key pairs and associated certificates

• Certificates for use in – Self-authentication

– Data integrity and authentication services, using digital signatures

– Signed jars

• It also allows users to cache the public keys of their communicating peers

31

Page 32: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

Java keytool

• Creating server certificate example

– Creating server certificate and store it in key store• Alias is set to ‘business’

• Key store password – ‘pass’

• Key password – ‘kpass’

• Key store file – ‘keystore.jks’

• Requires IP & Org. info

– Export server certificate from keystore.jks to server.cer

– When using CA – server.cer must be signed and than stored in CA-cert. key store

java‐home/bin/keytool ‐genkey ‐alias business ‐keyalg RSA –keypass pass‐storepass kpass ‐keystore keystore.jks

java‐home/bin/keytool ‐export ‐alias business ‐storepass kpass‐file server.cer ‐keystore keystore.jks

Java keytool

• Creating server CA certificate example

– Generate CSR – Certification request file• Sent to CA

• Store request in myBisiness.csr

– Import CA trusted certification• Store in caserver.cer

– Store CA certification in your CA-cert. key store• cacert.jsk stores CA-certificates

• Import caserver.cer to cacert.jks

keytool ‐certreq ‐alias business ‐file myBusiness.csr

keytool ‐importcert ‐alias business ‐file caserver.cer

java‐home/bin/keytool ‐import ‐alias business  ‐file caserver.cer‐keystore cacerts.jks ‐keypass kpass ‐storepass pass

32

Page 33: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

Bean Validation

• Bean Validation JSR-303

– A framework that validates state of Java Beans (value objects)

– Uses annotations to set restrictions

– Supports custom annotations

– Restrictions can be grouped – for different policies / validation levels

Bean Validation

• Bean Validation

– Built in annotations• Boolean - @AssertFalse, @AssertTrue

• Numbers - @Max, @Min

• Big decimals - @DecimalMax, @DecimalMin (accepts string)

• Number length - @Digits

• Time - @Part, @Future

• References - @NotNull, @Null

• Strings - @Pattern, @Size

• Cascade validation to referenced member - @Valid

33

Page 34: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

Bean Validation

• Bean Validation - Example public class Person {

@NotNull@Size(min=2, max=15)private String name;

@Max(120)private int age;

public String getName() {return name;

}public void setName(String name) {this.name = name;

}public int getAge() {return age;

}public void setAge(int age) {this.age = age;

}}

public static void main(String[] args) {

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();Validator validator = factory.getValidator();

Person [] p = new Person[3];//fill array with person data….//validationSystem.out.println("Full Validation : ");for(Person curr:p){

System.out.println("Results:");boolean pass=true;for(ConstraintViolation<Person> r:validator.validate(curr)){

pass=false;System.out.println(r);

}if(pass)  System.out.println("OK");

}}

Bean Validation

• Bean Validation – Groups Example public class Person {

@NotNull@Size(min=2, max=15)private String name;

@Max(value=120, groups=CustomNumricChecks.class)private int age;

public String getName() {return name;

}public void setName(String name) {this.name = name;

} …..

}

public static void main(String[] args) {

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();Validator validator = factory.getValidator();

Person [] p = new Person[3];//fill array with person data….//validation

for(Person curr:p){…for(ConstraintViolation<PersonWithGroup> r:

validator.validate(curr,CustomNumricChecks.class)){…

}….}

}

public interface CustomNumricChecks {

}

34

Page 35: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

Bean Validation

• Bean Validation – Custom Validation Example

public class CharCheck implements ConstraintValidator <  CharV,  String>{

private char[] toCheck;public void initialize(CharV annot){

toCheck=annot.value();}public boolean isValid( String value, ConstraintValidatorContext ctx){

for(char curr:toCheck){if(value.contains(curr)){

return false;}

}return true;

}}

@Retention (RetentionPolicy.RUNTIME)@Constraint (validatedBy = CharCheck.class)public @interface CharV{String message() default “…”;Class<?> groups() default {};char[] value() default{‘.’ , ’,’};

}

public class Person {

@NotNull@Size(min=2, max=15)@CharV({‘.’, ‘,’, ‘@’, ‘%’, ’*’}) private String name;

@Max(value=120)private int age;

public String getName() {return name;

}public void setName(String name) {this.name = name;

} …..

}

JAAS

• Java Authentication and Authorization

• Provides pluggable authentication framework

• Easily authenticates with Java access control model

• Part of JSE

• Used mainly for JEE authentication

• Pluggable authentication

– Allows flexible configuration of authentication mechanisms

– Application may use different ways to authenticate before executing sensitive tasks

– These pluggable modules works with Principals and Subjects

35

Page 36: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

JAAS

• Principal

– java.security.Principal

– Each authentication mechanism is bounded with a Principal

– Principal may reflect all kind of login methods

• User & password

• IPs

• 3rd party credentials

• Biometric input

• Certifications

• Tokens

– Java provides ready to use Principal implementations for common authentication needs

• Name, password, text, choice, X500, Kerberos

JAAS

• Principal

– X500 • World-wide id

• Personal digital certification

• Can be part of the handshake process in TLS

• Used for authentication

– Kereberos• In this case the user authenticates with a ticket / token

• In order to get a ticket the user

– issues a request with his username to an Authentication Server and gets a time stamped ticket

– Send the ticket to a Ticket Granting Server (usually the same server) and receives a ready-to-use ticket

– User comes with this ticket to you

36

Page 37: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

JAAS

• Subject

– javax.security.auth.Subject

– Holds all single user Principals

– Both Subjects and Principles are managed by the application

– In JEE container injects this data to servlets and remote objects

JAAS

• Authentication Components– LoginContext & Configuration

• File is specifies using “java.security.auth.login.config” System property

• File details Login Contexts and module dependencies

• Each Login Context has is registered Login Module(s)

– LoginModules• Each module performs what is needed to authenticate

• Generates Principal(s) and add it to the subject on successful authentication

• Removes Principal(s) from Subject when logout

• Uses CallbackHandler for generic user inputs

– CallbackHandler• Is loaded on module initialization

• On login() it is populated with Callback(s) to get user input(s) & handle() is called

• User input is checked and login should result in true/false or LoginException

37

Page 38: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

JAAS

• Authentication Components

SecurityContext

Subject

LoginModule

Principal

Principal

Principal

CallbackHandler

LoginModule

Principal

CallbackHandler

Configuration file

Callback

CallbackCallback

Callback Callback

JAAS

• Callback handler that accepts a list of Callbacks and uses System.in:

public class CustomCallbackHandler implements CallbackHandler {

private String userID;

@Overridepublic void handle(Callback[] cbs) throws IOException,UnsupportedCallbackException {

for(Callback cb:cbs){if(cb instanceof NameCallback){

System.out.println(((NameCallback) cb).getPrompt());Scanner in=new Scanner(System.in);userID=in.next();((NameCallback)cb).setName(userID);

}else{throw new UnsupportedCallbackException(cb);

}}

}}

38

Page 39: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

JAAS

• Simple Principal impl. that holds userID:

public class CustomIDPrincipal implements Principal {

private String userID;

public CustomIDPrincipal(String userID){this.userID=userID;

}

@Overridepublic String getName() {

return userID;}

}

JAAS

• Login Module:public class CustomLoginModule implements LoginModule {

private Subject subject;private CallbackHandler cbHandler;private Principal principal;

@Overridepublic boolean abort() throws LoginException { return true; }

@Overridepublic boolean commit() throws LoginException {

subject.getPrincipals().add(principal);return true;

}

@Overridepublic void initialize(Subject subject, CallbackHandler cb,Map<String, ?> sharedState, Map<String, ?> options) {

this.subject=subject;this.cbHandler=cb;

}…..

39

Page 40: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

JAAS

• Login Module cont.:

@Override//we login anyway.... with any given userID...public boolean login() throws LoginException {

try{NameCallback cb=new NameCallback("Please enter your ID");cbHandler.handle(new Callback[] {cb});principal=new CustomIDPrincipal(cb.getName());

}catch(Exception e){throw new LoginException(e.getMessage());

} return true;

}

@Overridepublic boolean logout() throws LoginException {

subject.getPrincipals().remove(principal);return true;

}

}

JAAS

• Configuring LoginModule, loading LoginContext and performing login()

//a. we load our login context//b. we login (here the CustomLogin with our CustomIDPrincipal & CustomCallback takes action)//c. then, we obtain the subject (with the single CustomIDPrincipal inside it ‐ holding the user input for userID)//d. we invoke a privileged action that digs the principal and print the userID it holds 

public static void main(String[] args) {System.setProperty("java.security.auth.login.config", "login.config");try{

LoginContext ctx=new LoginContext("exampleRealm", new CustomCallbackHandler());ctx.login();Subject subject=ctx.getSubject();//print userIDPrincipal p=subject.getPrincipals().iterator().next();Subject.doAsPrivileged(subject, new CustomPrivilegedAction(subject),null);

}catch(LoginException e){e.printStackTrace();

}}

exampleRealm {jaas.CustomLoginModule required;

};

login.config file

40

Page 41: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

Java Web Security - Authentication

– Java Web Modules allow you to configure web client authentication method• BASIC

• FORM

• DIGEST

• CLIENT-CERT

– Specified in web.xml

– Enforced by the server for every protected resource / URL (later)

Java Web Security - Authentication

– BASIC• Simplest way of returning HTTP 401 status

• This status instructs the browser to show its default login alert

• View can’t be customized

– FORM• Set with a specifies login page / URL to be presented to client

• View can be customized

• j_username & j_password must be sent as user input

Both are relevant for HTML clients

Both should be done over HTTPS

<login‐config> <auth‐method>BASIC</auth‐method>           <realm‐name> exampleRealm </realm‐name> 

</login‐config>

<login‐config><auth‐method>FORM</auth‐method><form‐login‐config>

<form‐login‐page>/LoginForm.html</form‐login‐page><form‐error‐page>/LoginError.html</form‐error‐page>

</form‐login‐config></login‐config>

41

Page 42: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

Java Web Security - Authentication

– DIGEST• HTTP standard that allows users to hash their username and passwords

• The client asks for a ‘nonce’ from the server and uses it to hash its personal data

• 2 iterations per call

• Not a strong encryption

• Vulnerable to man-in-the-middle attack (can you trust the given nonce ?)

– CLIENT-CERT• Clients must be certified and use SSL

• Usually, servers are to be trusted – but here client must be trusted as well

• Relevant when providing sensitive information to the client

• Relevant when one secured system calls another

• Known as ‘two way authentication’ and is the safest

Java Web Security – Declarative Security

• Java Web allows you to create application roles

• Security Roles – Are mapped to URL patterns and resources

– Are portable since you define it and you map it to your application

– Once a resource is mapped – it is available only for users from the specified roles

– This is declarative security – you declare – resource gets protected

– Resources with no role mapping are available to all

<security‐role><role‐name>employee</role‐name>

</security‐role> <security‐role> 

<role‐name>manager</role‐name> </security‐role>

42

Page 43: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

Java Web Security – Declarative Security

• Security Roles – Mapping security roles to resources by declaring

<security‐constraint> <web‐resource‐collection>

<web‐resource‐name>ERP Protected</web‐resource‐name> <url‐pattern>/erp/pages/*</url‐pattern> <http‐method>PUT</http‐method> <http‐method>DELETE</http‐method> <http‐method>GET</http‐method> <http‐method>POST</http‐method> 

</web‐resource‐collection> <auth‐constraint> 

<role‐name>employee</role‐name> <role‐name>manager</role‐name> 

</auth‐constraint> </security‐constraint>

<security‐constraint> <web‐resource‐collection>

<web‐resource‐name>ERP Mng Area</web‐resource‐name> <url‐pattern>/erp/mng/pages/*</url‐pattern> <http‐method>PUT</http‐method> <http‐method>DELETE</http‐method> <http‐method>GET</http‐method> <http‐method>POST</http‐method> 

</web‐resource‐collection> <auth‐constraint> 

<role‐name>manager</role‐name> </auth‐constraint> 

</security‐constraint>

Java Web Security – Declarative Security

• Roles mapping to users and groups– Every time a module that uses declarative security is deployed we must map roles to

actual users

– Roles provides portable application roles

– Users & groups are authorized clients which can authenticate to a server (using JAAS)

– Mapping is the linkage between the two – and done in a vendor specific manner

<sun‐web‐app> <security‐role‐mapping> 

<role‐name>employee</role‐name> <group‐name>workers</group‐name> 

</security‐role‐mapping> <security‐role‐mapping>   

<role‐name>manager</role‐name> <principal‐name>director123</principal‐name>    

</security‐role‐mapping>... </sun‐web‐app>

43

Page 44: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

App. Server Security - Authentication

• Clients of App. Server might be:

• Web modules– In this case authenticated users got security subject from the web container

– Subject is delegated by default to the business tier

• Web services– Done mostly in a vendor specific manner

• JDNI lookups– User provides principal and credential for logging in through Java

– Done via properties file or Hash-table assigned to the InitialContextFactory constructor

Property Meaning

INITIAL_CONTEXT_FACTORY Provides an entry point into the App. Server environment. Specifies the fully qualified class name of theJNDI SPI for the specific server.

PROVIDER_URL Specifies the host and port of the Server that provides the name service.                                                           For example: t3://weblogic:7001.

SECURITY_PRINCIPAL Specifies the identity of the user when that user authenticates to the default (active) security realm.

SECURITY_CREDENTIALS Specifies the credentials of the user when that user authenticates to the default (active) security realm.

App. Server Security - Authentication

• JNDI authentication example

Hashtable env = new Hashtable();env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");env.put(Context.PROVIDER_URL, "t3://weblogic:7001");env.put(Context.SECURITY_PRINCIPAL, "javaclient");env.put(Context.SECURITY_CREDENTIALS, "javaclientpassword");Context ctx = new InitialContext(env);

ctx.lookup(“….”);….

44

Page 45: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

App. Server Security – Declarative Security

EJB/RO Roles

• EJB specifies internal roles in the DD (ejb-jar.xml)

• Each role is set on each permitted method

• Provider is responsible for role mapping to

existing principals

EJB  RolesRole1beanA – method1beanA – method2beanB – method1

Role2beanA – method3beanA – method2beanB – method2

Role3beanB – method2beanC – method1beanC – method2

groups

employees

managers

system

App. Server Security – Declarative Security

• Annotations for security settings

• Annotation list:

– @DeclareRoles – lists the roles used in the bean / RO

– @RolesAllowed – specifies the roles permitted for a method

– @PermitAll – makes a method available for any role

– @DenyAll – blocks method access for all roles

– @RunAs – specifies the role name to switch to when calling a method

45

Page 46: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

App. Server Security – Declarative Security

• Annotations for security settings

– @DeclareRoles• lists the roles used in the bean

• Takes a String array

• Mentioned at class level

@DeclareRoles({“employees”,”managers”,”admin”})public class ServiceLoader extends … {…..         

App. Server Security – Declarative Security

• Annotations for security settings

– @RolesAllowed• lists the roles that are permitted for a specific method

• Takes a String array

• Set at method level

@DeclareRoles({“user”,”manager”,”admin”})public class ServiceLoader extends … {…..         @RolesAllowed({“manager”,”admin”})public void loadDBServices(){

….

46

Page 47: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

App. Server Security – Declarative Security

Run-As

• A component will usually forward caller role to other components

• Run-As allows a component to switch to another role

• All roles used must be defined in the EJB application

– So its portable….

• Useful when we want to restrict client direct access to a protected resource – but still allowing the client to use the resource through some service

Bean Client Bean A Bean B

Client’s role is ‘managers’ Run as ‘admin’

App. Server Security – Declarative Security

Run-As

– @RunAs• Specifies the role the EJB will switch to when calling a specific method

• Set at method level

@DeclareRoles({“employees”,”managers”,”admin”})public class ServiceLoader extends … {…..         @RolesAllowed({“employees”,”managers”})@RunAs(“admin”)public void loadDBServices(){

….

47

Page 48: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

JACC

Java Authorization Contract for Containers

• Provides: – Contextual objects

• Convenient objects bound to thread local storage that can be obtained from "anywhere“

• “Anywhere” might be threads, modules, nodes

• Like current http request is bounded to a Subject

– Authorization queries• A way for application code to get from the container authorization related data

• Like caller’s role, is role allowed…

– A hook into the authorization process• receive all authorization constraints that have been put in web.xml, ejb-jar.xml

JACC

Java Authorization Contract for Containers

• Using JACC in EJB to obtain caller’s Subject

@DeclareRoles({“employees”,”managers”,”admin”})public class ServiceLoader extends … {

@Resource private SessionContext ctx;

@RolesAllowed({“manager”,”admin”})public void loadDBServices(){

if( ctx.isCallerInRole(“manager”) ){doThis();

}else{doThat();

}}

48

Page 49: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

JACC

Java Authorization Contract for Containers

• Using JACC in EJB to obtain caller’s Principal

@DeclareRoles({“employees”,”managers”,”admin”})public class ServiceLoader extends … {

@Resource private SessionContext ctx;

@RolesAllowed({“manager”,”admin”})public void loadDBServices(){

Principal p=ctx.getCallerPrincipal();String name=p.getName();  ….

}

Server Hardening - Administration

• General– Transaction recovery services

– Heath check

– Cluster for load-balancing and failover

– Setup log system

– Watchdogs

• Web – Max post size

– Set https channel

– Connection starvation

– Man-in-the-middle handling (server can use self tokens)

– Session replication

– Firewall

– Map roles to users / groups

Few points to keep in mind when deploying your applications

49

Page 50: Java Ultimate Security [מצב תאימות] - John Brycemarketing.johnbryce.co.il/ad/2015/jul/Java_Ultimate_Security.pdfJava Ultimate Security Rony Keren rkeren@johnbryce.co.il

Server Hardening - Administration

• Business– Stateless pool setup

– Stateful cache and passivation setup

– Map roles to users / groups

• JMS– Message flow restrictions

– Destination quotas (by no’ of messages or by size)

– Message paging

– Separated machine

– MDB pool min / max

– Protect destinations and message factories

• Database– Set connection pool min / max – Protect DataSources

– Separated machine

Few points to keep in mind when deploying your applications

50