Guidelines to Improve OSGi Framework Robustness against Malicious Bundles
1.
2. Guidelines to
Improve the Robustness
of the OSGi Framework
and Its Services
against
Malicious or Badly
Coded Bundles
Michel D'HOOGE, TRIALOGMichel D'HOOGE, TRIALOG
3. 3Michel D'HOOGE, TRIALOG
BiographyBiography
• Michel D’HOOGEMichel D’HOOGE
– michel.dhooge@trialog.commichel.dhooge@trialog.com
• Using OSGi since 2001Using OSGi since 2001
• Involved in Oscar since 2003Involved in Oscar since 2003
– Participation to the Mailing ListParticipation to the Mailing List
– Open Source DevelopmentOpen Source Development
• Preferences ServicePreferences Service
• Permission Admin ServicePermission Admin Service
4. 4Michel D'HOOGE, TRIALOG
The PISE ProjectThe PISE Project
• Secure and Flexible Internet GatewaySecure and Flexible Internet Gateway
• RNRT Sponsored ProjectRNRT Sponsored Project
(National Telecommunication Research Network)(National Telecommunication Research Network)
– French National Research and Innovation ProgrammeFrench National Research and Innovation Programme
for Telecommunication.for Telecommunication.
• PartnersPartners
– France TélécomFrance Télécom
– IMAG/LSRIMAG/LSR
– INRIAINRIA
– Schneider Electric SASchneider Electric SA
– TrialogTrialog
– Université Joseph FourierUniversité Joseph Fourier
5. 5Michel D'HOOGE, TRIALOG
Dissemination by PISEDissemination by PISE
• Guidelines for Developing Robust OSGi BundlesGuidelines for Developing Robust OSGi Bundles
• Modification of Oscar for Automated Generation ofModification of Oscar for Automated Generation of
Service RepeatersService Repeaters
• URLs will be published on Oscar Mailing ListURLs will be published on Oscar Mailing List
6. 6Michel D'HOOGE, TRIALOG
Title ExplainedTitle Explained
• Improve the Robustness of the Framework and ...Improve the Robustness of the Framework and ...
– Provide guarantees that when a problem occurs in aProvide guarantees that when a problem occurs in a
part of the system, the rest still operates properly.part of the system, the rest still operates properly.
• Malicious BundleMalicious Bundle
– A bundle purposely coded to do some kinds of harm toA bundle purposely coded to do some kinds of harm to
the system and its datathe system and its data
• Badly Coded BundleBadly Coded Bundle
– A bundle developed by a developer which lacksA bundle developed by a developer which lacks
• ExperienceExperience
• Java and/or OSGi knowledgeJava and/or OSGi knowledge
7. 7Michel D'HOOGE, TRIALOG
Who Must Feel Concerned?Who Must Feel Concerned?
• A single problem but many involved!A single problem but many involved!
• On the Framework SideOn the Framework Side
– OSGi AllianceOSGi Alliance
– Framework ProviderFramework Provider
• ““Hardened” OSGi FrameworkHardened” OSGi Framework
• On the Bundle SideOn the Bundle Side
– Bundle DevelopersBundle Developers
• For Deployment / UseFor Deployment / Use
– Framework AdministratorFramework Administrator
– End-user (?)End-user (?)
8. 8Michel D'HOOGE, TRIALOG
ContentsContents
• Java & OSGi Security MechanismsJava & OSGi Security Mechanisms
• Finding the right set of Permissions for a bundleFinding the right set of Permissions for a bundle
• Stopping a BundleStopping a Bundle for surefor sure
• Protection against Stale ReferencesProtection against Stale References
• Listeners ManagementListeners Management
• Other AdvicesOther Advices
9. 9Michel D'HOOGE, TRIALOG
Java 2: Overview of Security MechanismsJava 2: Overview of Security Mechanisms
• PermissionsPermissions
– Used for 2 complementary purposesUsed for 2 complementary purposes
• put in Security Policy file to describe allowed actionsput in Security Policy file to describe allowed actions
• created on the fly by the system to assert authorization atcreated on the fly by the system to assert authorization at
runtimeruntime
– But no repudiation of Granted Rights & no QuotaBut no repudiation of Granted Rights & no Quota
• Security PolicySecurity Policy
– Lists the permissions given to the applicationLists the permissions given to the application
– However a good policy isn't easy to defineHowever a good policy isn't easy to define
• Who is knowledgeable enough to decide? Can he be trusted?Who is knowledgeable enough to decide? Can he be trusted?
[Inside Java 2 Platform Security. Gong, Ellison, Dageforde. Addison Wesley][Inside Java 2 Platform Security. Gong, Ellison, Dageforde. Addison Wesley]
10. 10Michel D'HOOGE, TRIALOG
OSGi Security MechanismsOSGi Security Mechanisms
• Relies on Java 2Relies on Java 2
• Specifies new PermissionsSpecifies new Permissions
– Admin PermissionAdmin Permission
• Identifies theIdentifies the Management AgentManagement Agent
• Checked by all System ServicesChecked by all System Services
– Configuration AdminConfiguration Admin
– Package AdminPackage Admin
– Permission AdminPermission Admin
– Start LevelStart Level
– UserAdmin PermissionUserAdmin Permission
• Rights to change properties and credentialsRights to change properties and credentials
• Solely for the User Admin ServiceSolely for the User Admin Service
11. 11Michel D'HOOGE, TRIALOG
OSGi Security Mechanisms (2)OSGi Security Mechanisms (2)
– Service PermissionService Permission
• Rights toRights to registerregister andand useuse servicesservices
• Security Risk with Registering:Security Risk with Registering: TrojanTrojan-ed Service-ed Service
– HTTP Server sees in clear all the dataHTTP Server sees in clear all the data
– Log Server and Log Clients may see valuable dataLog Server and Log Clients may see valuable data
– Package PermissionPackage Permission
• Rights to import andRights to import and exportexport packagespackages
• Security Risk with Exporting:Security Risk with Exporting: TrojanTrojan-ed Java Classes-ed Java Classes
– Data leakData leak
– Weak Cryptographic ImplementationWeak Cryptographic Implementation
• Permission Admin ServicePermission Admin Service
– Allows dynamic modification of the policyAllows dynamic modification of the policy
– But is just a technical answerBut is just a technical answer
12. 12Michel D'HOOGE, TRIALOG
ContentsContents
• Java & OSGi Security Mechanisms
• Finding the right set of Permissions for a bundleFinding the right set of Permissions for a bundle
• Stopping a Bundle for sure
• Protection against Stale References
• Listeners Management
• Other Advices
13. 13Michel D'HOOGE, TRIALOG
OSGi Life Cycle ModelsOSGi Life Cycle Models
• During dDuring development and deployment,evelopment and deployment,
anan OSGi framework can be used as aOSGi framework can be used as a
– Development EnvironmentDevelopment Environment
– Updatable PlatformUpdatable Platform
– Hosting PlatformHosting Platform
– Open PlatformOpen Platform
14. 14Michel D'HOOGE, TRIALOG
Security of the Life Cycle ModelsSecurity of the Life Cycle Models
• Each model implies different security constraintsEach model implies different security constraints
• Development Environment ModelDevelopment Environment Model
– OSGi Services used as COTSOSGi Services used as COTS
– No dynamic, runtime update is foreseenNo dynamic, runtime update is foreseen
=> Same security risk as a standard Java development=> Same security risk as a standard Java development
• Updatable Platform ModelUpdatable Platform Model
– OSGi framework is closed:OSGi framework is closed:
• Everything is controlled by the providerEverything is controlled by the provider
=> “Bundle Policy” may be directly provided by the bundle=> “Bundle Policy” may be directly provided by the bundle
with no riskwith no risk
• Model currently used for commercial deploymentModel currently used for commercial deployment
15. 15Michel D'HOOGE, TRIALOG
Security of the Life Cycle Models (2)Security of the Life Cycle Models (2)
• Hosting Platform ModelHosting Platform Model
– AllowsAllows trustedtrusted 33rdrd
Parties to install their servicesParties to install their services
=> Security model defined by OSGi R4=> Security model defined by OSGi R4
• Policy provided through a web of trustPolicy provided through a web of trust
• Open Platform ModelOpen Platform Model
– Allows installation ofAllows installation of untrusteduntrusted bundlesbundles
=> Security model to be invented!=> Security model to be invented!
• Use pre-loaded rights?Use pre-loaded rights?
– Could be restricted to the bare minimum (i.e. unusable)Could be restricted to the bare minimum (i.e. unusable)
• Use a central Permissions server?Use a central Permissions server?
• Interactively ask the end-user? (MIDP like)Interactively ask the end-user? (MIDP like)
16. 16Michel D'HOOGE, TRIALOG
PeriPerimeter of an Applicationmeter of an Application
• Static Part – Permissions must be usedStatic Part – Permissions must be used
– Java classesJava classes
• Runtime Part – Permissions are not relevantRuntime Part – Permissions are not relevant
– Java ThreadsJava Threads
– Class InstancesClass Instances
• Shared Part – Permissions are hardly relevantShared Part – Permissions are hardly relevant
– Shared ClassesShared Classes
– Shared InstancesShared Instances
– Shared ThShared Threadsreads
17. 17Michel D'HOOGE, TRIALOG
Steps for Granting PermissionsSteps for Granting Permissions
• Identify the Development & Deployment ModelIdentify the Development & Deployment Model
• Define the perimeter of the applicationDefine the perimeter of the application
• Choose PermissionsChoose Permissions
– Be a bit ParanoidBe a bit Paranoid
• Deploy the BundleDeploy the Bundle
– Check integrity of the bundle, if applicableCheck integrity of the bundle, if applicable
– Be a bit Paranoid againBe a bit Paranoid again
18. 18Michel D'HOOGE, TRIALOG
ContentsContents
• Java & OSGi Security Mechanisms
• Finding the right set of Permissions for a bundle
• Stopping a BundleStopping a Bundle for surefor sure
• Protection against Stale References
• Listeners Management
• Other Advices
19. 19Michel D'HOOGE, TRIALOG
How to Stop a BundleHow to Stop a Bundle for Surefor Sure??
• CallCall stop()stop() methodmethod
– Asks “politely” the bundle to stopAsks “politely” the bundle to stop
• On return, the frameworkOn return, the framework
– flags the bundle as “stopped”flags the bundle as “stopped”
– removes remaining services from service registryremoves remaining services from service registry
– sends some events to the other active bundlessends some events to the other active bundles
• But there is no control onBut there is no control on
– ThreadsThreads
– Memory usageMemory usage
– Non-Java resourcesNon-Java resources
• Hence the question...Hence the question...
20. 20Michel D'HOOGE, TRIALOG
... By Restarting the JVM!... By Restarting the JVM!
• Two Framework's states existTwo Framework's states exist
– logical state, as recorded by the frameworklogical state, as recorded by the framework
– real state, as seen by the JVMreal state, as seen by the JVM
• Before firstBefore first stop()stop(), both states should be equal, both states should be equal
• AfterAfter stop()stop(), states can be different, states can be different
– Threads still runningThreads still running
– Resources not releasedResources not released
• SimplestSimplest way to guarantee equality between statesway to guarantee equality between states
is to restart the JVM!is to restart the JVM!
– Must be done only when there is evidence of a problemMust be done only when there is evidence of a problem
=> Need to track bundles' resources=> Need to track bundles' resources
21. 21Michel D'HOOGE, TRIALOG
Or By Using a Hardened Java EnvironmentOr By Using a Hardened Java Environment
• ThreadsThreads
– Tracking & AccountingTracking & Accounting
– KillingKilling
• MemoryMemory
– Tracking & AccountingTracking & Accounting
– FreeingFreeing
• Other ResourcesOther Resources
– Tracking & AccountingTracking & Accounting
22. 22Michel D'HOOGE, TRIALOG
ContentsContents
• Java & OSGi Security Mechanisms
• Finding the right set of Permissions for a bundle
• Stopping a Bundle for sure
• Protection against Stale ReferencesProtection against Stale References
• Listeners Management
• Other Advices
23. 23Michel D'HOOGE, TRIALOG
Stale References (a.k.a. Dangling Pointers)Stale References (a.k.a. Dangling Pointers)
• A Sample Use CaseA Sample Use Case
– Service Provider registers its implementationService Provider registers its implementation
– Client gets a reference to the object (and uses it)Client gets a reference to the object (and uses it)
– Service Provider unregisters its implementationService Provider unregisters its implementation
• Framework event distributed to listenersFramework event distributed to listeners
– Client doesn't nullify the referenceClient doesn't nullify the reference
• Maybe it keeps using the service: not designed for thisMaybe it keeps using the service: not designed for this
• In all cases, it prevents garbage collectionIn all cases, it prevents garbage collection
• So, the client is faultySo, the client is faulty
– But then?But then?
24. 24Michel D'HOOGE, TRIALOG
Protection against Stale ReferencesProtection against Stale References
• Service FactoryService Factory
– ““To provide distinct instances to clients” [OSGi R3]To provide distinct instances to clients” [OSGi R3]
• Can help to track down the faulty clientCan help to track down the faulty client
• But won't prevent the problemBut won't prevent the problem
• Service RepeaterService Repeater
– Provide to clients a dummy class thatProvide to clients a dummy class that
• hides the real implementation of the servicehides the real implementation of the service
• forwards method calls to the real implementationforwards method calls to the real implementation
– When service is unregistered,When service is unregistered,
• The repeater nullifies its reference to the real implementationThe repeater nullifies its reference to the real implementation
• And that's it!And that's it!
25. 25Michel D'HOOGE, TRIALOG
Example: The LogService InterfaceExample: The LogService Interface
public interface LogService {
void log(int level, String message);
void log(int level, String message,
Throwable exception);
void log(ServiceReference sr, int level,
String message);
void log(ServiceReference sr, int level,
String message, Throwable exception);
}
26. 26Michel D'HOOGE, TRIALOG
Using a Service RepeaterUsing a Service Repeater
When the service is available
When the service is unregistered
27. 27Michel D'HOOGE, TRIALOG
Example: The Repeater ClassExample: The Repeater Class
class LogServiceRepeater implements LogService {
LogService impl;
public void log(int level, String message) {
impl.log(level, message);
}
public void log(int level, String message,
Throwable exception) {
impl.log(level, message, exception);
}
......
28. 28Michel D'HOOGE, TRIALOG
Example: The LogService ActivatorExample: The LogService Activator
public class Activator implements BundleActivator {
LogServiceRepeater repeater;
ServiceRegistration sr;
public void start(BundleContext bc) throws ...
repeater = new LogServiceRepeater ();
repeater.impl = new LogServiceImpl ();
sr = bc.registerService("...", repeater, null);
}
public void stop(BundleContext bc) throws ...
sr.unregister();
repeater.impl = null;
}
}
29. 29Michel D'HOOGE, TRIALOG
Automated Generation of RepeatersAutomated Generation of Repeaters
• Manual Implementation is Painful & Error-ProneManual Implementation is Painful & Error-Prone
– Better to have the framework generate the RepeatersBetter to have the framework generate the Repeaters
automaticallyautomatically
• Experiment done in TrialogExperiment done in Trialog
– Java Reflection & Jakarta/BCEL libraryJava Reflection & Jakarta/BCEL library
– Quite simple as soon as you understand how toQuite simple as soon as you understand how to
generate a class and its bytecode on the fly!generate a class and its bytecode on the fly!
– Some issuesSome issues
• No repeater for Service FactoriesNo repeater for Service Factories
• An instance can register more than a single serviceAn instance can register more than a single service
• Source Code distributed for OscarSource Code distributed for Oscar
30. 30Michel D'HOOGE, TRIALOG
Performance ConsiderationPerformance Consideration
• A simple “forward” of method callsA simple “forward” of method calls
– Null Pointer Exceptions automatically thrown by JVMNull Pointer Exceptions automatically thrown by JVM
• Overhead proportional to number of parametersOverhead proportional to number of parameters
– Maybe possible to improve this by using some kind ofMaybe possible to improve this by using some kind of
Java assemblyJava assembly
• Unavoidable if we want real security :-(Unavoidable if we want real security :-(
– But security is mandatory!But security is mandatory!
– Must be taken into account when assessing footprintsMust be taken into account when assessing footprints
31. 31Michel D'HOOGE, TRIALOG
ContentsContents
• Java & OSGi Security Mechanisms
• Finding the right set of Permissions for a bundle
• Stopping a Bundle for sure
• Protection against Stale References
• Listeners ManagementListeners Management
• Other Advices
32. 32Michel D'HOOGE, TRIALOG
Listeners ManagementListeners Management
• Calling listeners is riskyCalling listeners is risky
– Listeners' methods are executed in the caller's threadListeners' methods are executed in the caller's thread
• DoS: Java Exception can stop the thread of the caller serviceDoS: Java Exception can stop the thread of the caller service
• DoS: the listener never returnsDoS: the listener never returns
• In case of Thread Accountability: the caller is chargedIn case of Thread Accountability: the caller is charged
• Listener disappearanceListener disappearance
– Clients shall unregister their listeners before stoppingClients shall unregister their listeners before stopping
– Service providers shall listen to framework eventsService providers shall listen to framework events
• to unregister themselves the stopped clientto unregister themselves the stopped client
• Easy way: UseEasy way: Use ServiceFactory.ungetServiceServiceFactory.ungetService methodmethod
– Design Listeners as another Service ProviderDesign Listeners as another Service Provider
• For instance: UserAdminListenerFor instance: UserAdminListener
33. 33Michel D'HOOGE, TRIALOG
Counter Measure for Listeners' ExceptionsCounter Measure for Listeners' Exceptions
• Surround call with a try...catch blockSurround call with a try...catch block
– But, Common advice is to never attempt to catch ErrorBut, Common advice is to never attempt to catch Error
and Throwableand Throwable
– But, here, we are at the border between 2 applications...But, here, we are at the border between 2 applications...
• Log a message with levelLog a message with level
– LOG_INFO for RuntimeExceptionLOG_INFO for RuntimeException
– LOG_WARNING for ExceptionLOG_WARNING for Exception
– LOG_ERROR for Error and ThrowableLOG_ERROR for Error and Throwable
• Warn any Administrator availableWarn any Administrator available
– by e-mailby e-mail
– ......
34. 34Michel D'HOOGE, TRIALOG
ContentsContents
• Java & OSGi Security Mechanisms
• Finding the right set of Permissions for a bundle
• Stopping a Bundle for sure
• Protection against Stale References
• Listeners Management
• Other AdvicesOther Advices
35. 35Michel D'HOOGE, TRIALOG
Other AdvicesOther Advices
• Sanity ChecksSanity Checks
– An OSGi framework is as evil as InternetAn OSGi framework is as evil as Internet
• Never trust other partsNever trust other parts
• Bundle CertificationBundle Certification
– Automated Test SuiteAutomated Test Suite
– Code ReviewCode Review
– See Conditional Permission Admin [OSGi R4]See Conditional Permission Admin [OSGi R4]