Upload
rahmedsct
View
2.295
Download
2
Tags:
Embed Size (px)
DESCRIPTION
Citation preview
Copyright 2003 Rizwan Ahmed
Implementing Java Security with JAAS
Rizwan AhmedSun Certified Professional
Implementing Java Security with
JAAS
Rizwan Ahmed © 2003
Copyright 2003 Rizwan Ahmed
What is JAAS?
• Java Authentication and Authorization Service• Introduced as an optional package in J2SE 1.3• Integrated into J2SE 1.4• Provides a pluggable and flexible framework
that allows developers to incorporate different security mechanisms and sources
Copyright 2003 Rizwan Ahmed
Goals
• JAAS is an extensive and complicated library.• The goals for this presentation are:
– To give an overview of JAAS and its constituent parts and illustrate how they all work together
– Provide an introduction on how to use JAAS; code examples to help you get started
Copyright 2003 Rizwan Ahmed
Outline
• Introduction– What is JAAS– Authentication vs. Authorization– Subject– Principal
• Authentication• Authorization
Copyright 2003 Rizwan Ahmed
Authentication vs. Authorization
• Authentication is the process of verifying the users’ identity. Typically this entails obtaining a user name and a password or some other credential from the user.
• Authorization is the process of verifying whether a user has access to protected resources.
Authentication
Andy
AuthenticationService
Is the user who hesays he is?
User NamePassword
Authorization
Andy
Resource
AuthorizationService
Some Action
Can this userperform this
action on me?
Copyright 2003 Rizwan Ahmed
Overview of the Subject
• The Subject is a container for associated Principals, Public Credentials (public keys), and Private Credentials (passwords, private keys).
The Subject in Detail
Subject
PrincipalPrincipal
Principal
PublicCredential
PublicCredential
PublicCredential
PrivateCredential
PrivateCredential
PrivateCredential
Copyright 2003 Rizwan Ahmed
Subject
A Subject in JAAS represents an authenticated entity such as a person or device
1. package javax.security.auth;2. public class Subject {3. ...4.5. public Set getPrincipals() {}6. public Set getPrincipals(Class c) {}7.8. public Set getPrivateCredentials() {}9. public Set getPrivateCredentials(Class c) {}10.11. public Set getPublicCredentials() {}12. public Set getPublicCredentials(Class c) {}13.14. public boolean isReadOnly() {}15. public void setReadOnly() {}16.}
Copyright 2003 Rizwan Ahmed
Principal
• A Principal identifies a Subject. The Subject can be a person, a corporation, and application, etc.
• A Subject is comprised of a set of Principals, where each Principal represents an identity for that user. For example, a Subject could have a name Principal ("Susan Smith") and a Social Security Number Principal ("987-65-4321"), thereby distinguishing this Subject from other Subjects.
1. package java.security;2. public interface Principal {3. ...4. public String getName();5. }
Copyright 2003 Rizwan Ahmed
Obtaining a Specific Principal from a Subject
• Applications (and app. servers) typically adopt a convention stating that the Set of Principals on a Subject can only contain one instance of a particular Principal class.
1. // List the UserPrincipalExample principals2. Set userPrinSet = subject.getPrincipals(UserPrincipalExample.class);3. Iterator userPrinItr = userPrinSet.iterator();4. System.out.println("Found the following UserPrincipalsExample:");5. while (userPrinItr.hasNext()) {6. Principal p = (Principal) userPrinItr.next();7. System.out.println("\t" + p.toString());8. }
Copyright 2003 Rizwan Ahmed
Outline
• Introduction• Authentication• Authorization
Copyright 2003 Rizwan Ahmed
Authentication Overview1. The application
creates a LoginContext and calls login()
2. The LoginContext looks up the LoginConfiguration to load the predefined LoginModule
3. The LoginContext delegates the authentication to the LoginModules4. The LoginModules use the CallbackHandler to communicate with the
application5. Associate principals and credentials with the Subject if user is authenticated6. Or, throw a LoginException in case the login failed
Authentication Participants
Application
LoginContext
LoginConfiguration
LoginModule
LoginModule
LoginModuleCallback
Handler
Copyright 2003 Rizwan Ahmed
Pluggable Authentication Modules
The LoginModule provides authentication via a pluggable module, which implements the authentication algorithm and determines how the authentication is performed
Pluggable Authentication
Login Modules
Application
Login Context
JndiLoginModule
NTLoginModule
UnixLoginModule
Krb5LoginModule
MyLoginModule
LDAP Server
DbLoginModule
NTAuthentication
UnixAuthentication
KerberosAuthentication RDBMS
BiometricAuthentication
Copyright 2003 Rizwan Ahmed
LoginConfiguration File
• The default implementation parses a configuration file in the above format
• Configuration file specified via java.security.auth.login.config System parameter
Application1 { ModuleClass Flag ModuleOptions;};Application2 { ModuleClass Flag ModuleOptions; ModuleClass Flag ModuleOptions;};other { ModuleClass Flag ModuleOptions; ModuleClass Flag ModuleOptions;};
Copyright 2003 Rizwan Ahmed
Creating a LoginContext
• The name parameter is used to retrieve the appropriate login Configuration
• If a login Configuration with the specified name is not found, a default entry with the name “other” is used. If there is no Configuration with the name “other”, a LoginException is thrown
1. public class LoginContext {2. public LoginContext(String name) { ... }3. public LoginContext(String name, Subject subject) {...}4.5. public LoginContext(String name,6. CallbackHandler handler) { ... }7. public LoginContext(String name, Subject subject,8. CallbackHandler handler) { ... }9.10. ...11.}
Copyright 2003 Rizwan Ahmed
Creating a LoginContext (cont.)
• The constructors without a CallbackHandler either:– Rely on the default CallbackHandler specified
in the java.security file under property named auth.login.defaultCallbackHandler
– Do not use a CallbackHandler and rely on the LoginModules to have another means of obtaining the information
Copyright 2003 Rizwan Ahmed
Logging In
• Authentication occurs with a call to the login() method
• The login() method invokes the configured LoginModules to perform authentication
• When authentication succeeds, the Subject can be retrieved using the getSubject() method
• The logout() method logs out the Subject and removes its authenticated Principals
1. public class LoginContext {2. ...3. public void login() throws LoginException { }4. public void logout() throws LoginException { }5. public Subject getSubject() { }6. }
Copyright 2003 Rizwan Ahmed
LoginModule
• Two-phase authentication:– login() is 1st phase method– commit() and abort() are 2nd phase methods
1. package javax.security.auth.spi;
2. public interface LoginModule {3. public void initialize(Subject subject,4. CallbackHandler callbackHandler,5. Map sharedState,6. Map options);7. public boolean abort() throws LoginException;8. public boolean commit() throws LoginException;9. public boolean login() throws LoginException;10. public boolean logout() throws LoginException;11.}
Copyright 2003 Rizwan Ahmed
Login Example: Login Phase
1. // Use the "Example" entry in the login configuration file2. // to authenticate users.3. LoginContext loginContext = null;4. try {5. loginContext = new LoginContext("Example",6. new ExampleCallbackHandler());7. loginContext.login();8. } catch (AccountExpiredException e) {9. ...10.} catch (CredentialExpiredException e) {11. ...12.} catch (FailedLoginException e) {13. ...14.} catch (LoginException e) {15. ...16.} catch (Exception e) {17. ...18.}
Copyright 2003 Rizwan Ahmed
Login Example: Commit Phase
• Once the login succeeds we can get the Subject from the LoginContext and get the authenticated Principals from the Subject.
1. // List the Principals the authenticated user has2. Subject subject = loginContext.getSubject();3. Iterator principalItr = subject.getPrincipals().iterator();4. System.out.println("The authenticated user has the " +5. "following Principals:");6. while (principalItr.hasNext()) {7. Principal p = (Principal) principalItr.next();8. System.out.println("\t" + p.toString());9. }
Copyright 2003 Rizwan Ahmed
LoginModules in J2SE 1.4
These exist under sun.com.security.auth.module• JndiLoginModule – Authenticates against an
LDAP tree• Krb5LoginModule – Authenticates against a
Kerberos domain• UnixLoginModule – Authenticates against Unix
security• NTLoginModule – Authenticates against NT
security
Copyright 2003 Rizwan Ahmed
Callbacks
• javax.security.auth.callback.Callback Marker interface used to indicate a callback.
• Callbacks provide a means for the underlying authentication implementation to communicate with the application and obtains security data such as user name and password as well as provide information such as error and warning messages.
• Included callbacks:– NameCallback– PasswordCallback– TextOutputCallback– TextInputCallback– ChoiceCallback– ConfirmationCallback– LanguageCallback
Copyright 2003 Rizwan Ahmed
Custom LoginModule Example
1. public boolean login()2. throws LoginException {3. Callback[] callbacks = new Callback[2];4. callbacks[0] = new NameCallback("userName: ");5. callbacks[1] = new PasswordCallback("password: ",false);6. try {7. callbackHandler.handle(callbacks);8. userName = ((NameCallback) callbacks[0]).getName();9. char[] charPass = ((PasswordCallback) callbacks[1])10. .getPassword();11. if (charPass == null) charPass = new char[0];12. password = new String(charPassword);13. } catch (IOException ioe) {14. ...15. } catch (UnsupportedCallbackException uce) {16. ...17. }18. if (isUserAuthentic()) succeeded = true;19.20. return succeeded;21.}
Copyright 2003 Rizwan Ahmed
CallbackHandler
1. package javax.security.auth.callback;
2. public interface CallbackHandler {3. public void handle(Callback[] callbacks)4. throws IOException, UnsupportedCallbackException;5. }
Copyright 2003 Rizwan Ahmed
Custom CallbackHandler Example1. public void handle(Callback[] callbacks)2. throws IOException, UnsupportedCallbackException {3. for (int i = 0; i < callbacks.length; i++) {4. if (callbacks[i] instanceof TextOutputCallback) {5. ...6. } else if(callbacks[i] instanceof NameCallback) {7. NameCallback nc = (NameCallback) callbacks[i];8. System.out.print(nc.getPrompt());9. System.out.flush();10. nc.setName(readLine());11. } else if(callbacks[i] instanceof PasswordCallback){12. PasswordCallback pc = (PasswordCallback)13. callbacks[i];14. System.out.print(pc.getPrompt());15. System.out.flush();16. pc.setPassword(readLine().toCharArray());17. } else {18. throw new UnsupportedCallbackException19. (callbacks[i], "Invalid Callback");20. }21. }22.}
Copyright 2003 Rizwan Ahmed
Outline
• Introduction• Authentication• Authorization
Copyright 2003 Rizwan Ahmed
What is Authorization?
Authorization is the process of determining whether an authenticated user is permitted to perform some actions such as accessing a resource.
The process is Policy based since JAAS is built on the existing Java security model.
Copyright 2003 Rizwan Ahmed
CodeSource Based Authorization
• Before the integration of JAAS with Java security, authorization decisions were strictly based on the CodeSource
• A Trusted Library may be given access to sensitive resources while an Applet or another Library may have that access restricted.
Code Source Based Authorization
FileSystem
NetworkSockets
SystemProperties Applet
TrustedLibrary
Library X
Copyright 2003 Rizwan Ahmed
CodeSource and Principal Based Authorization
• With the integration of JAAS and J2SE Security, authorization decisions can be made based on the CodeSource and the Principal.
• A Library may not have access privileges to resources when running without a User context or when being executed by User Bart, but when User Andy executes the Library those permissions may be granted.
Code Source and Principal BasedAuthorization
FileSystem
NetworkSockets
SystemProperties
Library X
Andy
Bart
Copyright 2003 Rizwan Ahmed
CodeSource & ProtectionDomain
• The CodeSource of a piece of Java code is the URL location that the code was loaded from and the Certificates that we used to sign the code
• The ProtectionDomain is a holder for the CodeSource and a Principal
• Each class is assigned a ProtectionDomain upon being loaded. The Principal is null when the class is first loaded.
ProtectionDomain
CodeSource
CodeSource
URL
Certificate
ProtectionDomain
CodeSource
Principal
Class
Copyright 2003 Rizwan Ahmed
AccessControlContext – a Context for Authorization Decisions
• When making access decisions, the security system looks at every ProtectionDomain involved in the call. Access is granted only if every ProtectionDomain in the Context can have access.
Authorization Context
ContextStack Snapshot
AccessController.checkPermission()
java.io.FileInputStream()
java.io.FileReader()
ReadTestFileUseCase.apply()
AuthorizationTestHarness.run()
...
Class
Class
Class
Class
Class
Class
PD
PD
PD
PD
PD
PD
grant codebase "file:./SampleAzn.jar" { permission javax.security.auth.AuthPermission "createLoginContext.Sample";
permission javax.security.auth.AuthPermission "doAsPrivileged"; };
Copyright 2003 Rizwan Ahmed
How is JAAS Authorization performed?
To make JAAS authorization take place, the following is required:
• The user must be authenticated• Principal-based entries must be configured in the
security policy. • The Subject that is the result of authentication must
be associated with the current access control context.
Copyright 2003 Rizwan Ahmed
Permission
• Permissions represent access to resources.• All Permission object have a name. The
meaning of the name parameter is implementation dependent. Typically the name identifies the resource to be accessed.
1. package java.security;2. public abstract class Permission {3. public Permission (String name) {}4. public abstract boolean implies(Permission p) {}5. public abstract boolean equals(Object o) {}6. public String toString() {}7. public PermissionCollection newPermissionCollection() {}8. }
Copyright 2003 Rizwan Ahmed
Policy
• The mapping between PDs and associated Permissions is stored by the Policy
• The grant entry includes all the permissions granted for the principals to do the security sensitive operations, for example, accessing a particular web page or file
Policy Holds a Mapping of ProtectionDomain toPermissions
Policy
ProtectionDomain
ProtectionDomain
ProtectionDomain
PermissionCollection Permission
PermissionPermission
PermissionCollection Permission
PermissionPermission
PermissionCollection Permission
PermissionPermission
Copyright 2003 Rizwan Ahmed
Policy Implementation
• The default implementation of Policy accepts text based configuration in the above format
• Each grant entry is composed of an optional CodeSource, Signers, Principals, and a list of Permissions
• Default security policy is <JRE_HOME>/lib/security/java.policy• Can provide supplemental policy file location via
– -Djava.security.policy=<file> JVM parameter• Can override the default policy file with:
– -Djava.security.policy==<file> JVM parameter
1. grant [CodeBase <URL>,] [Signedby <signers>,]2. [Principal <Principal_Class> <Principal_Name>] {3. Permission <Permission_Class> [<Target_Name>]4. [, <Permission_Actions>]5. [, signedBy <Signer_Name>];6. };
Copyright 2003 Rizwan Ahmed
AccessController
• The AccessController embodies the access control algorithm.
• It obtains the current AccessControlContext, which has an array of PDs and then for each PD checks whether the Subject has the requested permission.
Authorization Participants
ProtectionDomain
CodeSource
Principal
PermissionCollection
PermissionPermission
PermissionPolicy
Class
AccessControlContext
AccessController
Copyright 2003 Rizwan Ahmed
Associating a Subject with an Access Control Context
• The doAs method associates the provided Subject with the current access control context and then invokes the run method from the action. The run method implementation contains all the code to be executed as the specified Subject. The action thus executes as the specified Subject.
1. package javax.security.auth;2. public class Subject {3. ...4.5. static public Object doAs(Subject s, PrivilegedAction pa) {}6. static public Object doAs(Subject s, PrivilegedExceptionAction pa){}7. static public Object doAsPrivileged(Subject s,8. PrivilegedAction pa) {}9. static public Object doAsPrivileged(Subject s,10. PrivilegedExceptionAction pa) {}11.}
Copyright 2003 Rizwan Ahmed
Execution flow
• Invoke Subject.doAs(..) or Subject.doAsPriviledged()• SecurityManager.checkPermission(..) is called to check
the permission• The SecurityManager delegates the check to the
AccessController• The AccessController tries to find out if the relevant
AccessControlContext contains sufficient permissions for the action to be taken
• If not, the SecurityManager updates the current AccessControlContext with the permissions granted to the subject via the Policy from the Policy file
Copyright 2003 Rizwan Ahmed
Execution flow
PrivilegedAction action = new SampleAction(); // The call to Subject.doAsPrivileged is performed via: Subject.doAsPrivileged(mySubject, action, null);
public class SampleAction implements PrivilegedAction { public Object run() { System.out.println("\nYour java.home property value is: " + System.getProperty("java.home")); System.out.println("\nYour user.home property value is: " + System.getProperty("user.home")); File f = new File("foo.txt"); System.out.print("\nfoo.txt does "); if (!f.exists()) System.out.print("not "); System.out.println("exist in the current working directory."); return null; }}
Copyright 2003 Rizwan Ahmed
Custom Policy
• Like the LoginModule, the Policy is also a pluggable module. You can hook up other Policy implementations by one of these means:– At runtime by calling Policy.setPolicy()– By changing the value of policy.provider property in
<JRE_HOME>/lib/security/java.security• The specified class name must point to a subclass of
Policy• The specified class must be in the boot classpath• Example included (you must change the java.security
property on your JRE)
Copyright 2003 Rizwan Ahmed
Extend JAAS
• JAAS is built on top of the existing Java security model, which is CodeSource based, and the plaintext format policy implementation.
• For an enterprise application you may want to use custom security repositories with JAAS, such as LDAP, database or another file system
• This can be done by writing a customized module thanks to the JAAS pluggable feature
Copyright 2003 Rizwan Ahmed
About the Speaker
Speaker is a Senior Architect at Ventyx Inc. He has over 5 years of experience in J2EE/Web development and has worked with extensive open source technologies. His interests are in the areas of technical architecture, enterprise application integration and web services.