Super simple application security with Apache Shiro

60
Simple Application Security Les Hazlewood Apache Shiro Project Chair

TAGS:

description

Les Hazlewood, founder of the Apache Shiro project, covers the benefits of using Shiro as an application security framework. Check out the video for this presentation, as well as more training resources for Java here: http://marakana.com/forums/java/general/183.html

Transcript of Super simple application security with Apache Shiro

Page 1: Super simple application security with Apache Shiro

Simple Application Security

Les HazlewoodApache Shiro Project Chair

Page 2: Super simple application security with Apache Shiro

About Me

Les Hazlewood

Apache Shiro Project Chair

JSecurity Founder

Katasoft Founder & CTO

Page 3: Super simple application security with Apache Shiro

What is Apache Shiro?

• Application security library

• Quick and easy

• Simplifies security concepts

Page 4: Super simple application security with Apache Shiro

About Shiro

• Started in 2003, JSecurity in 2004

• Simplify or replace JAAS

• Dynamic changes at runtime

• Sessions - Heterogeneous Clients

• Reduce Design Flaws

• ‘One stop shop’

• Apache Top Level, September

Page 5: Super simple application security with Apache Shiro

Reduce Design Flaws

Page 6: Super simple application security with Apache Shiro

No Silver Bullets

Page 7: Super simple application security with Apache Shiro

Agenda

Web Support

Threading & Concurrency

Authentication

Session Management

Authorization

Cryptography

Page 8: Super simple application security with Apache Shiro

Quick Terminology

• Subject – Security-specific user ‘view’

• Principals – Subject’s identifying attributes

• Credentials – Secret values that verify identity

• Realm – Security-specific DAO

Page 9: Super simple application security with Apache Shiro

Authentication

Web Support

Threading & Concurrency

Session Management

AuthorizationAuthentication

Cryptography

Page 10: Super simple application security with Apache Shiro

Authentication Defined

Identity verification:

Proving a user is who he says he is

Page 11: Super simple application security with Apache Shiro

Shiro Authentication Features

• Subject-based (current user)

• Single method call

• Rich Exception Hierarchy

• ‘Remember Me’ built in

Page 12: Super simple application security with Apache Shiro

How to Authenticate with Shiro

Steps

1. Collect principals & credentials

2. Submit to Authentication System

3. Allow, retry, or block access

Page 13: Super simple application security with Apache Shiro

Step 1: Collecting Principals & Credentials

//Example using most common scenario:

//String username and password. Acquire in

//system-specific manner (HTTP request, GUI, etc)

UsernamePasswordToken token =

new UsernamePasswordToken( username, password );

//”Remember Me” built-in, just do this:

token.setRememberMe(true);

Page 14: Super simple application security with Apache Shiro

Step 2: Submission

Subject currentUser =

SecurityUtils.getSubject();

currentUser.login(token);

Page 15: Super simple application security with Apache Shiro

Step 3: Grant Access or Handle Failure

try {

currentUser.login(token);

} catch ( UnknownAccountException uae ) { ...

} catch ( IncorrectCredentialsException ice ) { ..

} catch ( LockedAccountException lae ) { ...

} catch ( ExcessiveAttemptsException eae ) { ...

} ... catch your own ...

} catch ( AuthenticationException ae ) {

//unexpected error?

}

//No problems, show authenticated view…

Page 16: Super simple application security with Apache Shiro

“Remember Me” support

• subject.isRemembered()

• subject.isAuthenticated()

• remembered != authenticated

Page 17: Super simple application security with Apache Shiro

Authorization

Web Support

Threading & Concurrency

Session Management

Authentication Authorization

Cryptography

Page 18: Super simple application security with Apache Shiro

Authorization Defined

Process of determining Access Control

“who can do what”

Elements of Authorization

• Permissions

• Roles

• Users

Page 19: Super simple application security with Apache Shiro

Permissions Defined

• The “what” of an application

• Most atomic security element

• Describes resource types and their behavior

• Does not define “who”

Page 20: Super simple application security with Apache Shiro

Roles Defined

• Implicit or Explicit construct

• Implicit: Name only

• Explicit: A named collection of Permissions

Allows behavior aggregation

Enables dynamic (runtime) alteration of user abilities.

Page 21: Super simple application security with Apache Shiro

Users Defined

• The “who” of the application

• What each user can do is defined by their association with Roles or Permissions

Example: User’s roles imply PrinterPermission

Page 22: Super simple application security with Apache Shiro

Authorization Features

• Subject-centric (current user)

• Checks based on roles or permissions

• Powerful out-of-the-box WildcardPermission

• Any data model – Realms decide

Page 23: Super simple application security with Apache Shiro

How to Authorize with Shiro

Multiple means of checking access control:

• Programmatically

• JDK 1.5 annotations

• JSP/GSP TagLibs (web support)

Page 24: Super simple application security with Apache Shiro

Programmatic Authorization

//get the current Subject

Subject currentUser =

SecurityUtils.getSubject();

if (currentUser.hasRole(“administrator”)) {

//do one thing (show a special button?)‏

} else {

//don‟t show the button?)‏

}

Role Check

Page 25: Super simple application security with Apache Shiro

Programmatic Authorization

Subject currentUser =

SecurityUtils.getSubject();

Permission printPermission =

new PrinterPermission(“laserjet3000n”,“print”);

If (currentUser.isPermitted(printPermission)) {

//do one thing (show the print button?)‏

} else {

//don‟t show the button?

}

Permission Check

Page 26: Super simple application security with Apache Shiro

Programmatic Authorization

String perm = “printer:print:laserjet4400n”;

if(currentUser.isPermitted(perm)){

//show the print button?

} else {

//don‟t show the button?

}

Permission Check (String-based)

Page 27: Super simple application security with Apache Shiro

Annotation Authorization

//Throws an AuthorizationException if the caller

//doesn‟t have the „teller‟ role:

@RequiresRoles( “teller” )

public void openAccount( Account acct ) {

//do something in here that only a teller

//should do

}

Role Check

Page 28: Super simple application security with Apache Shiro

Annotation Authorization

//Will throw an AuthorizationException if none

//of the caller‟s roles imply the Account

//'create' permission

@RequiresPermissions(“account:create”)‏

public void openAccount( Account acct ) {

//create the account

}

Permission Check

Page 29: Super simple application security with Apache Shiro

Enterprise Session Management

Web Support

Threading & Concurrency

AuthorizationAuthentication

CryptographySession

Management

Page 30: Super simple application security with Apache Shiro

Session Management Defined

Managing the lifecycle of Subject-specific temporal data context

Page 31: Super simple application security with Apache Shiro

Session Management Features

• Heterogeneous client access

• POJO/J2SE based (IoC friendly)

• Event listeners

• Host address retention

• Inactivity/expiration support (touch())

• Transparent web use - HttpSession

• Can be used for SSO

Page 32: Super simple application security with Apache Shiro

Acquiring and Creating Sessions

Subject currentUser =

SecurityUtils.getSubject()

//guarantee a session

Session session =

subject.getSession();

//get a session if it exists

subject.getSession(false);

Page 33: Super simple application security with Apache Shiro

Session API

getStartTimestamp()

getLastAccessTime()

getAttribute(key)

setAttribute(key, value)

get/setTimeout(long)

touch()

...

Page 34: Super simple application security with Apache Shiro

Cryptography

Web Support

Threading & Concurrency

AuthorizationAuthentication

Session Management

Cryptography

Page 35: Super simple application security with Apache Shiro

Cryptography Defined

Protecting information from undesired access by hiding it or converting it into nonsense.

Elements of Cryptography

• Ciphers

• Hashes

Page 36: Super simple application security with Apache Shiro

Ciphers Defined

Encryption and decryption data based on public/private keys.

• Symmetric Cipher - same key for encryption and decryption.

• Asymmetric Cipher - different keys for encryption and decryption

Page 37: Super simple application security with Apache Shiro

Hashes Defined

A one-way, irreversible conversion of an input source (a.k.a. Message Digest)

Used for:

• Credentials transformation

• Data with underlying byte array

Files, Streams, etc

Page 38: Super simple application security with Apache Shiro

Cryptography Features

Simplicity

• Simplified wrapper over JCE infrastructure.

• Easier to understand API

• “Object Orientifies” cryptography concepts

• Interface-driven, POJO based

Page 39: Super simple application security with Apache Shiro

Cipher Features

• OO Hierarchy

JcaCipherService, AbstractSymmetricCipherService, DefaultBlockCipherService, etc

• Just instantiate a class

No “Transformation String”/Factory methods

• More secure default settings

Initialization Vectors, et. al.

Page 40: Super simple application security with Apache Shiro

Shiro’s CipherService Interfacepublic interface CipherService {

ByteSource encrypt( byte[] raw, byte[] key);

void encrypt(InputStream in, OutputStream out, byte[] key);

ByteSource decrypt( byte[] cipherText, byte[] key);

void decrypt(InputStream in, OutputStream out, byte[] key);

}

Page 41: Super simple application security with Apache Shiro

Hash Features

• Default interface implementations

MD5, SHA1, SHA-256, et. al.

• Built in Hex & Base64 conversion

• Built-in support for Salts and repeated hashing

Page 42: Super simple application security with Apache Shiro

Shiro’s Hash Interface

public interface Hash {

byte[] getBytes();

String toHex();

String toBase64();

}

Page 43: Super simple application security with Apache Shiro

Intuitive OO Hash API

//some examples:

new Md5Hash(“foo”).toHex();

//File MD5 Hash value for checksum:

new MD5Hash( aFile ).toHex();

//store a password, but not raw:

new Sha256(aPassword, salt,

1024).toBase64();

Page 44: Super simple application security with Apache Shiro

Web Support

Web Support

Threading & Concurrency

CryptographySession Management

AuthorizationAuthentication

Page 45: Super simple application security with Apache Shiro

Web Support Features

• Simple ShiroFilter web.xml definition

• Protects all URLs

• Innovative Filtering (URL-specific chains)

• JSP Tag support

• Transparent HttpSession support

Page 46: Super simple application security with Apache Shiro

web.xml<filter>

<filter-name>ShiroFilter</filter-name>

<filter-class>org.apache.shiro.web.servlet.IniShiroFilter</filter-class>

<init-param><param-name>config</param-name><param-value>

[main]

realm = com.my.custom.realm.Implementation

securityManager.realm = $realm

[urls]

/account/** = authc

/remoting/** = authc, roles[b2bClient], ...

</param-value></init-param>

</filter>

<filter-mapping>

<filter-name>ShiroFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

Page 47: Super simple application security with Apache Shiro

JSP TagLib Authorization<%@ taglib prefix=“shiro”

uri=http://shiro.apache.org/tags %>

<html>

<body>

<shiro:hasRole name=“administrator”>

<a href=“manageUsers.jsp”>

Click here to manage users

</a>

</shiro:hasRole>

<shiro:lacksRole name=“administrator”>

No user admin for you!

</shiro:hasRole>

</body>

</html>

Page 48: Super simple application security with Apache Shiro

JSP TagLibs<%@ taglib prefix=“shiro”

uri=http://shiro.apache.org/tags %>

<!-- Other tags: -->

<shiro:guest/>

<shiro:user/>

<shiro:principal/>

<shiro:hasRole/>

<shiro:lacksRole/>

<shiro:hasAnyRoles/>

<shiro:hasPermission/>

<shiro:lacksPermission/>

<shiro:authenticated/>

<shiro:notAuthenticated/>

Page 49: Super simple application security with Apache Shiro

Threading & Concurrency

Web Support

Threading & Concurrency

CryptographySession Management

AuthorizationAuthentication

Page 50: Super simple application security with Apache Shiro

Threading & Concurrency Features

• Subject retained on multiple threads

• Automatic thread cleanup

• Transparent Executor/ExecutorService support

Page 51: Super simple application security with Apache Shiro

ThreadLocal

• Currently-executing Subject is thread-bound via a ThreadContext

• Executing logic in the current thread is fine. What about other threads?

• Runnable & Callable support

• ExecutorService support

Page 52: Super simple application security with Apache Shiro

Subject Thread Association

Can associate a Subject with a Callable or Runnable intended to run on another thread:

Callable myCallable = //create or acquire

Subject currentUser = SecurityUtils.getSubject();

Callable associated =

currentUser.associateWith(myCallable);

associated.call(); //current thread

//or another thread:

anExecutorService.execute(associated);

Page 53: Super simple application security with Apache Shiro

Transparent Association

Subject ‘Aware’ Executor implementations transparently retain Subject:

SubjectAwareExecutor,

SubjectAwareExecutorService,

SubjectAwareScheduledExecutorService

//Look mom! No Shiro API imports!

Callable myCallable = //create or acquire

anExecutorService.execute(myCallable);

Page 54: Super simple application security with Apache Shiro

MISCELLANEOUS

Page 55: Super simple application security with Apache Shiro

“Run As” Support

• “Run As” allows a Subject to assume the identity of another

• Useful for administrative interfaces

• Identity retained until relinquished

Page 56: Super simple application security with Apache Shiro

//assume current user is the „admin‟ user:

Subject currentUser = SecurityUtils.getSubject();

PrincipalCollection newIdentity = new

SimplePrincipalCollection(“jsmith”, “jdbcRealm”);

currentUser.runAs(newIdentity);

//behave as the „jsmith‟ user here

currentuser.isRunAs(); //true = assumed identity

currentUser.getPreviousPrincipals();//prev. identity

//return back to the admin user:

currentUser.releaseRunAs();

“Run As” Support

Page 57: Super simple application security with Apache Shiro

Unit Testing• Subject.Builder creates ad-hoc Subjects

• Use with subject.execute for easy testing:

Subject testSubject =

Subject.Builder(securityManager)

.principals(“jsmith”).buildSubject()

testSubject.execute( new Runnable() {

public void run() {

callTestMethod();

}

});

Page 58: Super simple application security with Apache Shiro

Logging Out

One method:

App-specific log-out logic:

Before/After the call

Listen for Authentication or StoppedSession events.

//Logs the user out, relinquishes account

//data, and invalidates any Session

SecurityUtils.getSubject().logout();

Page 59: Super simple application security with Apache Shiro

APACHE SHIRO DEMO

Page 60: Super simple application security with Apache Shiro

Thank You!

[email protected]

• http://www.katasoft.com

• Seeking engineering talent

• Seeking product feedback