practical dynamic modules (osgi) security · practical dynamic modules (osgi) security protecting...
TRANSCRIPT
Practical Dynamic Modules (OSGi) SecurityProtecting More Than Just Data
David SmithJames GouldVeriSign201
AGENDA
> Background on OSGi> Security per OSGI spec> Security beyond OSGI spec
Background on OSGi
> Why use OSGi?– Modularity– Service-oriented architecture– Hot-deployable updates– Multiple versions of code in residence– Hot-swappable versions
> Ideal for highly available, highly adaptable applications> OSGi containers include:
– Eclipse Equinox– Apache Felix– Knopflerfish
Bundle Lifecycle
Starting,
Started
Stopping,Stopped
Installed,Resolved
OSGi Layers
Module
Lifecycle
Service
Security
What Interactions Have To Be Secured?
ApplicationBundle
Management Bundle
SystemBundles
useradmin
Your Application Is A Castle
Keep Services Separated
Limiting Who Talks To Whom
What Security is Defined in the OSGi Spec?
> Java 2 Security!– Use of Security Manager, Security Policies with Permissions
> Permission Admin Service> Conditional Permission Admin Service> User Admin Service
What Security is Not Defined in the OSGi Spec?
> Truly cross-cutting security apart from Java 2 Security> Java Authentication and Authorization Service (JAAS) integration> Securing the container from bad people> An easy way to apply user-based, declarative access protections
– No @annotations– Only programmatic security– Not declarative
Java 2 Security
> Let’s walk through memory lane?
> Protect what bundles can do– Bundles granted permissions based on code base and jar signing– Programmatic checking permissions in bundles
Java 2 Security Steps
> Enable Security Manager -Djava.security.manager
> Define security policy in policy file-Djava.security.policy=<file>
> Create custom permissions or use java.security.BasicPermission new BasicPermission(“displayReports”);
> Check permissions in protected code segmentsSecurityManager sm = System.getSecurityManager();if (sm != null)
sm.checkPermission(new BasicPermission(“displayReports”));
Sample Policy Filekeystore “jazoon.jks”;
grant codeBase "file:Untrusted*" { permission java.io.FilePermission "<<ALL FILES>>", "read";};
grant signedBy ”jazoontest" { permission java.io.FilePermission "<<ALL FILES>>", "read, write, delete, execute";};
grant { permission java.security.AllPermission;};
Keystore and jarsigner
$ keytool -list -keystore jazoon.jks –storepass <pass>Keystore type: jksKeystore provider: SUN
Your keystore contains 1 entry
jazoontest, May 25, 2010, keyEntry,Certificate fingerprint (MD5): 93:48:DC:4B:E5:E3:B2:05:F2:9B:A4:74:73:22:A1:C9};$ jarsigner –keystore jazoon.jks jazoontest.jar jazoontestEnter Passphrase for keystore: <pass>
Java 2 Security Protection Domains
Class Loader A
Class Loader B
System Class Loader
Protection Domain A
Protection Domain B
Class A
Class B
File System PDSecurity.checkPermission( new FilePermission(file, “write”));
B.doAction()
File.createTempFile(“pre”, null);
AccessControlContext context = AccessController.getContext();
ProtectionDomain.implies(perm);
If all Protection Domains don’t imply the permission, then a SecurityException occurs
Class A, Class B, and File must imply FilePermission(file, “write”)
Use of AccessController.doPrivileged()
Class Loader A
Class Loader B
System Class Loader
Protection Domain A
Protection Domain B
Class A
Class B
File System PD
What if B.doAction() needs to create a temp file independent of Class A’s permissions?
Use AccessController.doPrivileged!
B.doAction()
AccessController.doPrivileged( new PrivilegedAction() { public Object run() { File.createTempFile( “pre”, null); return null; }});
AccessControlContext context = AccessController.getContext();
context.checkPermission(perm);
ProtectionDomain.implies(perm);
Java 2 Security and JAAS
> The Authorization of JAAS is handled by Java 2 Security> Policy grant supports Principals to define Permissions for users
grant Principal com.acme.MyPrincipal “jim” {
permission java.io.FilePermission “/home/jim/-”, “read, write, delete, execute”;
}
> To include user Principals with Protection Domain use Subject.doAsSubject.doAs(subject, new PrivilegedAction() {
public Object run() {
File newFile = new File(“/home/jim/test.txt”);
newFile.createNewFile();
return null;
});
OSGi Permission Admin Service
> What is missing from Java 2 Security for OSGi?– Define permissions based on bundles (location)– Allow management agent to lookup bundle permissions– Allow management agent to manage bundle permissions
> Superseded by Conditional Permission Admin Service> Features
– Permissions persisted– Support for default permissions– OSGi service management interface– Integration into Bundle Protection Domains
Setup Management Agent
> Default permission of AllPermission> First bundle to assign permissions wins!
– Management Agent must load first– Management Agent must give itself AllPermission
> ExamplepermAdmin.setPermissions( context.getBundle().getLocation(), new PermissionInfo[]{ new PermissionInfo( AllPermission.class.getName(),"”,"")});
OSGi Permission Admin Service Interface
PermissionInfo[] getDefaultPermissions();
String[] getLocations();
PermissionInfo[] getPermissions(java.lang.String location);
void setDefaultPermissions(PermissionInfo[] permissions);
void setPermissions(String location, PermissionInfo[] permissions);
OSGi Permission Admin Service Flow
Application Bundle
Service Bundle
Framework
Application PD
Service PD
Application
Service
Framework PD PermissionAdmin Service
Agent
Permissions
doServicehasPermission
hasPermission
setPermissions
FrameworkService
execute
hasPermission
OSGi Conditional Permission Admin Service
> What is missing from Permission Admin Service?– Permission Admin Service dependency on Bundle location as identifier– Not flexible for complex security models
> Features– Introduction of ordered security conditions– Allow and deny policies– Support for local bundle permissions– Mutable and immutable conditions– Immediate and postponed conditions
Conditions
> A Condition determines if a set of Permissions apply for a Bundle> A Condition is instantiated by the Bundle Protection Domain
– Reference from Condition to Bundle> Features
– Can be custom – Mutable– Postponed
> Implying a Permission with Conditions– Is the Condition satisfied?– Are one of the permissions applied?– Policy access type (ALLOW or DENY) determines success or failure
Local Permissions
> Allow Developer to specify what Permissions are needed by Bundle– Maximum Permissions for Bundle
> Defined using Bundle Permission Resource in the Bundle– OSGI-INF/permissions.perm
> Example
# Require all FilePermissions(java.io.FilePermission "<<ALL FILES>>” "read, write,
delete, execute”)
ConditionalPermissionAdmin Interface
AccessControlContext getAccessControlContext( String[] signers); ConditionalPermissionUpdate newConditionalPermissionUpdate();
ConditionalPermissionInfo newConditionalPermissionInfo( String name, ConditionInfo conditions[], PermissionInfo permissions[], String access);
ConditionalPermissionInfo newConditionalPermissionInfo( String encodedConditionalPermissionInfo);
OSGi Conditional Permission Admin Service Flow
Application Bundle
Service Bundle
Framework
ApplicationPD
Service PD
Application
Service
Framework Service
Framework PD
PermissionAdmin ServiceAgent Permissions
Conditional Permission
Admin Service
ConditionalPermissions
Security Manager
doService
execute
hasPermission
hasPermissionhasPermission
setPermissions
commithasPermission
OSGi Effective Permissions
> With Java 2 Security, Permission Admin Service, Conditional Permission Admin Server, and Local Permissions how is the effective permissions determined?– Java 2 Security always applies that can be extended with Implied
Permissions– Local Permissions intersected with the Permission Services– Permission Admin Service takes precedence over Conditional Permission
Admin Service
OSGi Effective Permissions
Local Permissions
Java 2 Permissions &
Implied Permissions
Limiting What Outsiders (Users) Can Do
OSGi User Admin Service
> What is missing from Permission Admin Services?– User level authentication and authorization!
> Features– Contains Users, Roles, and Groups– Used to authenticate users– Used to create Authorization objects for authorizing user actions– Support for Basic (any) and Required (all) roles
> Does not integrate with JAAS or Java 2 Security for user level security– Access to User Admin Service done via Java 2 Security
Role, User, Group, and Authorization
Role
User
Group
1..n
roles
Authorization
user
roles
UserAdmin Interface
Role createRole(String name, int type);
boolean removeRole(String name);
Role getRole(String name);
Role[] getRoles(String filter) throws InvalidSyntaxException;
Role[] getRoles(String filter) throws InvalidSyntaxException;
User getUser(String key, String value);
public Authorization getAuthorization(User user);
OSGi User Admin Service Flow
Application Bundle
Service Bundle
Framework
Application
Service
UserAdmin Service
Authenticate (“suzy”, “passwd”)
authenticate
User user = userAdmin.getUser( “auth.userid”, “suzy”);
If (user == null || !user.hasCredential( “auth.passwd”, hash(“passwd”))) throw SecurityException(“Invalid login”);
Authorization auth = userAdmin.getAuthorization(user);
doServiceService.doService(auth);
authorize
Service.doService(Authorization auth) { if (!auth.hasRole(“ServiceRole”)) throw new SecurityException( “authorization error”); }
doAction
Outside Attackers
Pull Up the Castle’s Drawbridge
> Disable the command-line console– Containers support this– For instance, in Equinox use –noConsole
> Disable any insecure access to remote command-line (e.g., telnet)– You wouldn’t allow telnet into a production box, would you?– Just in case, see whether your container starts this by default
> Disable any insecure access to any remote management– Container may have web interface, or you may use Felix’s– Container may expose JMX commands
Install Secure Entrances: Console
> Protect the command line– Custom authentication before granting access– Standard OS user security– LDAP, one-time password, custom challenge
Writing Your Own Console
public void acceptCommands () {BufferedReader consoleInput =
new BufferedReader( new InputStreamReader( System.in ) );while ( true ) { System.out.print( ">>> [install|start|stop]=[file|bundle]" ); String inputLine = null; try { inputLine = null; inputLine = consoleInput.readLine(); this.handle( inputLine ); } catch ( Exception e ) { e.printStackTrace(); }}
}
Writing Your Own Console, Continued
private void handle ( String inputLine ) throws BundleException {String[] cmdAndArg = inputLine.split( "=" );String cmd = cmdAndArg[ 0 ];String arg = cmdAndArg[ 1 ];
if ( "install".equals( cmd ) ) { this.bundleContext.installBundle( arg );} else if ( . . . ){ . . .}
}
No Remote Threats
Install Secure Entrances: Remote Connections
> Always use a secure network interface– Back-office communications should always be on secure interfaces – Accidental changes to ACLs can expose means of compromise
> Apply additional security standards native to the means of access– For web access: https/certificates– JMX:
JAAS (w/LDAP or some other auth mechanism) User Admin Service
– Web services: https and/or standard WSS
JMX AuthenticationSimple Authentication Server
> $JAVA_HOME/lib/management/jmxremote.password
> $JAVA_HOME/lib/management/jmxremote.access
> Start Java with command-line arg– com.sun.management.jmxremote.authenticate=true
bob b@B
bob readwrite
JMX AuthenticationSimple Authentication Client
JMXServiceURL url = new JMXServiceURL(“service:jmx:rmi:///jndi/rmi://1.1.1.1:9379/<…>”);
Map<String, Object> env = new HashMap<String, Object>();String[] creds = {“bob”, “b@B”};env.put(JMXConnector.CREDENTIALS, creds);
JMXConnector conn = JMXConnectorFactory.newJMXConnector(url, env);conn.connect();
MBeanServerConnection mBeanServer = conn.getMBeanServerConnection();
JMX™ AuthenticationUsing LDAP via JAAS> Authenticate with LDAP directory> Use Java 6 JAAS LDAP LoginModule
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
LocateRegistry.createRegistry(9379);JMXServiceURL jmxServiceURL = new JMXServiceURL(...);
Map<String, Object> env = new HashMap<String, Object>();env.put("jmx.remote.x.login.config", ”MyLdapConfig");
JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
cs.start();
JMX AuthenticationUsing LDAP via JAAS (cont.)
> jaas.config
> Start with command-line arg– java.security.auth.login.config=jaas.config
MyLdapConfig { com.sun.security.auth.module.LdapLoginModule REQUIRED userProvider=
"ldap://sun-ds/ou=people,dc=sun,dc=com" userFilter="(&(uid={USERNAME})(objectClass=inetOrgPerson))" authzIdentity=adminRole useSSL=false; };
JMX Custom Authenticator
> A Custom JMXAuthenticator can– Authenticate to custom identity data store– Accept additional login credentials– Be an alternative to writing custom LoginModule
Custom AuthenticatorServer Code Examplepublic class MyOsgiJmxAuthenticator implements JMXAuthenticator { public Subject authenticate(Object aCredentials) { final String[]credentials = (String[]) aCredentials; String username = (String) credentials[0]; String password = (String) credentials[1]; // Validate credentials... if ([ok]) { Set<JMXPrincipal> principals = new Set<JMXPrincipal>();
principals.add(new JMXPrincipal(username));principals.add(new JMXPrincipal(“admin”));
return new Subject(true, principals, Collections.EMPTY_SET, Collections.EMPTY_SET); } else { throw new SecurityException(“Authentication failure”); } } }
Custom AuthenticatorServer Code Example
JMXServiceURL url = new JMXServiceURL(. . .);
Map<String, Object> env = new HashMap<String, Object>();env.put(JMXConnectorServer.AUTHENTICATOR, new MyOsgiJmxAuthenticator());
JMXConnector conn = JMXConnectorFactory.newJMXConnector(url, env);conn.connect();
MBeanServerConnection mBeanServer = conn.getMBeanServerConnection();
Remote Deployment
I have a msg for
you!
OK. I’ll open a window for
you.
Send it over here.
Cluster
Remote JMX Installer
> With clustering, remote distribution becomes a problem> Remote, secure distribution even more difficult
Central JMX-Based
Installer
Instance:JMX
:1379request install
send jar
Instance
Instance:JMX
:9731request install
:JMX
Install Guards
> Deployment watchdog– Watches for deployments– Has criteria for allowed deployments– Alerts on unexpected deployments
> Could ask bundle for shared secret/digital signature– bundle.getEntry( "/sharedSecret.txt" );– bundle.findEntries(“secret", "*.txt", noRecurse);
Custom Watchdog (BundleListener)
public void bundleChanged ( BundleEvent aEvent ) { int type = aEvent.getType(); String symbolicName = bundle.getSymbolicName(); boolean bundleIsAllowed = allowedBundles.contains ( symbolicName ); BundleEventEnum eventType = BundleEventEnum.getByCode( type ); if ( !bundleIsAllowed
&& (eventType.isInProcessOfStarting()) ) { try { bundle.uninstall(); } catch ( Exception e ) { e.printStackTrace(); } }}Activator: context.addBundleListener( listener );
Bundle-Event Enumeration
public enum BundleEventEnum {INSTALLED(BundleEvent.INSTALLED, "INSTALLED"), LAZY_ACTIVATION(BundleEvent.LAZY_ACTIVATION, "LAZY_ACTIVATION"), RESOLVED(BundleEvent.RESOLVED, "RESOLVED"), . . . ;private final String name;private final int code;
BundleEventEnum ( final int aCode, final String aName ) { this.code = aCode; this.name = aName;}
public boolean isInProcessOfStarting () { return (this == INSTALLED) || (this == RESOLVED) || (this == STARTED) || (this == STARTING) || (this == UPDATED);}
}
BundleTracker (OSGi 4.2)
> Not necessary to write your own listener> Works like ServiceTracker> Add BundleTrackerCustomizer
– addingBundle(Bundle bundle, BundleEvent event) – modifiedBundle(Bundle bundle, BundleEvent event, Object object) – removedBundle(Bundle bundle, BundleEvent event, Object object)
Summary
> We covered a lot of territory including– Java 2 Security– Permission Admin Service and Conditional Permission Admin Service– User Admin Service– Removing insecure admin access– Adding secure admin access
> Let’s protect the OSGi Castle!
David Smith verisign.com VeriSign [email protected]
Jim Gould verisign.comVeriSign [email protected]