The Anatomy Of A Secure Web App Using JavaEE, Spring .

Transcription

The Anatomy of a Secure Web AppUsing JavaEE, Spring Security andApache FortressOctober 5, 2017Little Rock Tech Fest

ObjectiveThink about how we should besecuring web apps.Little Rock Tech Fest 20172

IntroductionsShawn McKinney Software ArchitectPMC Apache Directory ProjectEngineering TeamLittle Rock Tech Fest 20173

AgendaHave a look at 1. Java Remote Code Execution erial-exploit-sample2. Apache Fortress Demo Java EE Spring -fortress-demo3. Fortress SAML Demo Spring Security l-demoLittle Rock Tech Fest 20174

RecommendationListen and absorb conceptually.Slides will be published and havethe details.Little Rock Tech Fest 20175

What’s The Problem Equifax Breach– 143 million Americans’ personal info,including names, addresses, dates ofbirth and SSNs compromised.– Only a veneer of security in place.Little Rock Tech Fest 20176

What’s The Exploit“The vulnerability was ApacheStruts CVE-2017-563CVE-2017-56388 or-data-breach/Little Rock Tech Fest 20177

The Exploit“The Jakarta Multipart parser in ApacheStruts 2 2.3.x before 2.3.32 and 2.5.xbefore 2.5.10.1 mishandles file upload,which allows remote attackers to executearbitrary commands via a #cmd string#cmd stringin a crafted Content-Type HTTP header,as exploited in the wild in March name CVE-2017-5638Little Rock Tech Fest 20178

How it Works Input data deserialized into anexecutable object with m-remote-codeexecution-exploit.htmlLittle Rock Tech Fest 20179

Apache Struts code-execution-vulnerability-cve-2017-9805/Little Rock Tech Fest 201710

Apache Struts code-execution-vulnerability-cve-2017-9805/Little Rock Tech Fest 201711

Equifax Breach“Generally when you successfully exploit aweb-applicationbug likelikethisthisyouyouwillwillweb-application bugbecomethe systemsystem useruserwhowhoownsownsthethewebbecome thewebserverprocess "serverprocess,”Alex McGeorge, the head of threatintelligence at the security firm h-no-excuse/Little Rock Tech Fest 201712

The SolutionEnsure all appropriate patcheshave been applied and that youaren’t running software withvulnerabilities or backdoors.?Little Rock Tech Fest 201713

How do we ensure that oursoftware is free of vulnerabilities,known or otherwise?Little Rock Tech Fest 201714

How do we ensure that oursoftware is free of vulnerabilities,known or otherwise?can’t be done - practicallyLittle Rock Tech Fest 201715

So Now What?“Security best practices dictate that thisuser have as on the server itself, since securityvulnerabilities in web applications andweb servers are so commonly reach-no-excuse/Little Rock Tech Fest 201716

The Solution (Take 2)Practice the principle of least privilege.Little Rock Tech Fest 201717

https://en.wikipedia.org/wiki/Principle of least privilege18

Java Object Serialization Exploitpublic class BadCodeimplements java.io.Serializable { private voidreadObject(java.io.ObjectInputStream ec(cmd cmd); );Runtime.getRuntime().exec(Java’s remote code execution exploit occurs when a rogue object isread from an input resource and deserialized.19

Employ a Runtime Java Security Policygrant codeBase "file: {catalina.home}/webapps/my-web-app-1/-" {permission java.net.SocketPermission "localhost", "resolve";permission java.net.SocketPermission "127.0.0.1:32768", "connect,resolve";permission java.lang.reflect.ReflectPermission "suppressAccessChecks";permission java.io.SerializablePermission "enableSubclassImplementation";permission java.io.FilePermission“ ssion“ /resources/","execute"; }; use w/ cautionLittle Rock Tech Fest 201720

Demo # ampleLittle Rock Tech Fest 201721

Not a Perfect Solutiongrant codeBase "file: {catalina.home}/webapps/my-web-app-1/-" {permission java.net.SocketPermission "localhost", "resolve";permission java.io.FilePermission “ /resources/good-scripts*", "execute";permission java.net.SocketPermission "127.0.0.1:32768", "connect,resolve";permission java.lang.reflect.ReflectPermission "suppressAccessChecks";permission java.io.SerializablePermission "enableSubclassImplementation";permission java.lang.reflect.ReflectPermission "suppressAccessChecks";};Little Rock Tech Fest 201722

Changes coming down the pike Java 9– Modularization– Improved encapsulation– Finer control over package access.Little Rock Tech Fest 201723

Meanwhile What should we do?Little Rock Tech Fest 201724

https://en.wikipedia.org/wiki/Information securityThe building up, layering on and overlapping ofsecurity measures is called defense in depth. In contrast to a metal chain, which is famouslyonly as strong as its weakest link, the defense-in-depth aims at a structure where, should onedefensive measure fail, other measures will continue to provide protection.25

Java Web Security Layers1. Java SE Security2. Java Secure SocketExtension (JSSE)3. Java EE Security4. Spring Security5. Web App Framework6. Database FrameworkLittle Rock Tech Fest 201726

Each with a specific purpose1.Java SE Security ----------- principle of least privilege2.JSSE ---------------------------- private conversations3.Java EE Security ---------- deadbolt on front door4.Spring Security ------------ locks on room doors5.Web App Framework - locks on equipment in rooms6.Database Functions ---- content filteringLittle Rock Tech Fest 201727

Two Areas of Access Control1.Java and Spring Role Declarativechecks2.RBAC Permission ProgrammaticchecksLittle Rock Tech Fest 201728

Example ey/apache-fortress-demoLittle Rock Tech Fest 201729

Start with Tomcat Servlet ContainerLittle Rock Tech Fest 201730

1 & 2. Enable HTTPSssssh!!!1. Update theServer.xml2. Add private keyLittle Rock Tech Fest 201731

Enable Tomcat TLS1. Generate keystore with private key (Steps 1 - demo/apidocs/doc-files/keys.html2. Add the following to server.xml: Connector port "8443" maxThreads "200" scheme "https"secure "true"SSLEnabled "true“keystoreFile “/path/mykeystore”keystorePass “******”clientAuth "false" sslProtocol "TLS"/ o/apidocs/doc-files/apache-tomcat-ssl.html

3. Enable Java EE Security the deadbolta. Update web.xmlb. Drop the proxy jarc. Add context.xmld. Add fortress to pom.xmlLittle Rock Tech Fest 201733

Current Specs for Java EE Security1. JSR-196 – JASPIC - AuthN2. JSR-115 – JAAC - AuthZ3. JSR-375 – JavaEE Security APILittle Rock Tech Fest 201734

Enable Java EE Security RealmAdd to App’s Web.xml security-constraint display-name My Project Security Constraint /display-name web-resource-collection web-resource-name Protected Area /web-resource-name 1. Java EE containerprotects this URLAutomatically. url-pattern /wicket/* /url-pattern /web-resource-collection auth-constraint 2. All users must role-name DEMO2 USER /role-name have this role to /auth-constraint /security-constraint login-config gain entry. auth-method FORM /auth-method 3. Route un-authN realm-name MySecurityRealm /realm-name form-login-config requests to my form. form-login-page /login/login.html /form-login-page tle Rock Tech Fest 201735

Enable Java EE Security RealmDrop the Fortress Realm Proxy Jar in Tomcat’s lib folder:Little Rock Tech Fest 201736

Enable Java EE Security RealmAdd context.xml to META-INF folder: Context reloadable "true" Realm className Apache Fortress Tomcat .Tc7AccessMgrProxy"defaultRoles "ROLE DEMO2 SUPER USER,DEMO2 ALL PAGES,ROLE PAGE1, ROLE PAGE2, ROLE PAGE3"The set of role candidates eligible to be actived into a session./ /Context t.xmlLittle Rock Tech Fest 201737

Enable RBAC Policy Decision PointAdd Fortress Dependency to web app’s pom.xml: dependency groupId org.apache.directory.fortress /groupId artifactId fortress-realm-impl /artifactId version 2.0.0 /version /dependency Little Rock Tech Fest 201738

4. SetupRBACPDPthe security systemPolicy Decision Pointa. Installb. Configurec. UseLittle Rock Tech Fest 201739

Use ANSI RBAC INCITS 359 SpecificationRBAC0:– Users, Roles, Perms, SessionsRBAC1:– Hierarchical RolesRBAC2:– Static Separation of DutiesRBAC3:– xDynamic Separation of DutiesToday we demo thisLittle Rock Tech Fest 201740

Use RBAC Object ModelSix basic elements:1. User – human or machine entity2. Role – a job function within an organization3. Object – maps to system resources4. Operation – executable image of program5. Permission – approval to perform an Operation on oneor more Objects6. Session – contains set of activated roles for UserLittle Rock Tech Fest 201741

Use RBAC Functional ModelAPIs form three standard interfaces:Management andConfig processes1. Admin – Add, Update, Delete2. Review – Read, Search3. xSystem – Access ControlDemo runtimeprocessesLittle Rock Tech Fest 201742

Use RBAC Functional ModelSystem Manager /impl/AccessMgrImpl.html1. createSession – authenticate, activate roles2. checkAccess – permission check3. sessionPermissions – all perms active for user4. sessionRoles – return all roles active5. addActiveRole – add new role to session6. dropActiveRole – remove role from sessionLittle Rock Tech Fest 201743

blob/master/README-QUICKSTART-APACHEDS.mdLittle Rock Tech Fest 201744

e/blob/master/README-QUICKSTART-SLAPD.mdLittle Rock Tech Fest 201745

5–8EnableLDAPSSLconfidentialityLittle Rock Tech Fest 201746

Enable LDAP SSL Client1. Import public key to java ortressdemo/apidocs/doc-files/keys.html2. Add to fortress.propertiescommon namehost ldap-server-domain-name.comin server certport 636enable.ldap.ssl truetrust.store mytruststoretrust.store.password changeitCan be foundtrust.store.onclasspath trueon classpathLittle Rock Tech Fest 201747

Enable ApacheDS LDAP SSL Server1.Import keystorewith ApacheDirectory Studio2.RestartApacheDS l

Or Enable OpenLDAP SSL ServerAdd locations of crypto artifacts to slapd server config:TLSCACertificateFile /path/to/my/ca-certificateTLSCertificateFile e p-ssl.htmlLittle Rock Tech Fest 201749

9. EnableSpringSecuritylocks on the roomsa. Authorizationb. Role mappingLittle Rock Tech Fest 201750

Enable Spring SecurityAdd dependencies to pom: dependency groupId org.springframework.security /groupId artifactId spring-security-core /artifactId version 4.1.3.RELEASE /version /dependency dependency groupId org.springframework.security /groupId artifactId spring-security-config /artifactId version 4.1.3.RELEASE /version /dependency dependency groupId org.springframework.security /groupId artifactId spring-security-web /artifactId version 4.1.3.RELEASE /version /dependency Little Rock Tech Fest 201751

Add the Spring Context File to AppEnable Spring’s context file via web app’s web.xml file: context-param param-name contextConfigLocation /param-name param-value classpath:applicationContext.xml /param-value /context-param Little Rock Tech Fest 201752

Enable Spring Security Interceptor bean id "fsi“ .FilterSecurityInterceptor " property name "authenticationManager" ref "authenticationManager"/ property name "accessDecisionManager" ref "httpRequestAccessDecisionManager"/ property name "securityMetadataSource" sec:filter-security-metadata-source use-expressions "false" sec:intercept-url pattern “ /com.mycompany.page1“access “ROLE PAGE1“/ page-levelauthorization(declarative) /sec:filter-security-metadata-source /property /bean By default name must contain ROLELittle Rock Tech Fest 201753

Role MappingRole Propagation between Java EE & Spring SecuritySpring Security uses PreAuthenticatedAuthentication filter to get java EE role mappings.From the applicationContext.xml: bean id "preAuthenticatedAuthenticationProvider”class reauth.PreAuthenticatedAuthenticationProvider" property name "preAuthenticatedUserDetailsService" ref "preAuthenticatedUserDetailsService"/ /bean Little Rock Tech Fest 201754

Role MappingShare Roles Between Java EE and SpringComplete list of eligible roles found in app’s web.xml: !-- Declared in order to be used by Spring Security -- security-role role-name ROLE DEMO2 SUPER USER /role-name /security-role security-role role-name ROLE PAGE1 /role-name /security-role security-role role-name ROLE PAGE2 /role-name /security-role security-role role-name ROLE PAGE3 /role-name /security-role Little Rock Tech Fest 201755

10. Web AppAuthorizationlocks on equipmentAdd fine-grainedchecks:a. Page linksb. Buttonsc. Other controlsLittle Rock Tech Fest 201756

Inject Fortress APIs via Spring BeansEnable Fortress RBAC Spring Beans in applicationContext.xml: bean id “accessMgr”class ry"scope "prototype"factory-method "createInstance" constructor-arg value "HOME"/ /bean Little Rock Tech Fest 201757

Share the Session with TomcatSession Propagation between Tomcat, Fortress and Web app:1. The Fortress Tomcat Realm creates the session after user successfullyauthenticates. It serializes the data and stores inside a principal object.2. Tomcat returns the serialized principal to Web app on ();StringszPrin servletRequest.getUserPrincipal().toString(); -StandardJava api3. Next deserialize the java security principal into a ‘Fortress’ session:j2eePolicyMgr.deserialize(szPrincipal )SessionftSess j2eePolicyMgr.deserialize(szPrin ); - FortressRealm api4. Store the Fortress session into an HTTP session object for later usage: - Web app’s own apimyAppFw.setSession( ftSess );58

Add Web Framework Securitypublic class Page1 extends MyBasePage{Add( new SecureIndicatingAjaxButton({@Overrideprotected void onSubmit( . ){if( checkAccess( customerNumber{// do something here:"Page1", "Add" get.appendJavaScript( ";alert('Unauthorized');" );}}});Little Rock Tech Fest 201759

filtering11. DAOAuthorizationAdd fine-grainedChecks to:a. Createb. Readc. Updated. DeleteLittle Rock Tech Fest 201760

Add Security Aware DAO componentspublic class Page1DaoMgr implements Serializable{ public Page1EO updatePage1( Page1EO entity tCust())){// Do normal DAO.update stuff here.}elsethrow new RuntimeException("Unauthorized”);.return entity;} }Little Rock Tech Fest 2017fine-grainedauthorization(programmatic)61

12, 13.EnableDB SSLConfidentiality12. Clienta. public keyb. config13. Servera. private keyb. configLittle Rock Tech Fest 201762

Enable JDBC SSL ClientAdd to fortress.properties of Web app:trust.store /path/mytruststoretrust.store.onclasspath falsemust be foundon file path# These are the JDBC configuration params forMyBatis DAO connect to MySQL databaseexample:database.driver com.mysql.jdbc.Driverdatabase.url db-domain-name.com:3306/jdbc:mysql://demoDB ?useSSL true&requireSSL trueLittle Rock Tech Fest 201763

Enable MySQL SSL ServerAdd to MySQL my.cnf the server’s keys:ssl-ca /path/ca-cert.pemssl-cert /path/server-cert.pemssl-key /path/server-key.pem2. Instruct listener to use host name in certificateon server restart:bind-address ttle Rock Tech Fest 201764

Apache Fortress Demo Three Pages and Three CustomersOne role for every page to customer comboUsers may be assigned to one or more rolesOne and only one role may be activatedPagesCustomer 123Customer 456Customer 789Page OnePAGE1 123PAGE1 456PAGE1 789Page TwoPAGE2 123PAGE2 456PAGE2 789Page ThreePAGE3 123PAGE3 456PAGE3 789Little Rock Tech Fest 201765

User123Customer 123Customer 456Customer FalseFalseUser1Customer 123Customer 456Customer FalseFalseUser1 123Customer 123Customer 456Customer seFalseFalseLittle Rock Tech Fest 201766

Testing Verify security functionality viaautomation. Otherwise vulnerabilities may stillexist in your ittle Rock Tech Fest 201767

Apache Fortress Demo moUser FooCustomer 123Customer 456Customer alseFalseLittle Rock Tech Fest 201768

Example /fortress-saml-demoLittle Rock Tech Fest 201769

The Security Layers with SAML1.Java SE Security2.JSSE3.Java EE Security4.Spring Security5.Web App Framework6.Database FunctionsLittle Rock Tech Fest 2017Turned off (for now)Deadbolt is now hereNot much to change70

Two Areas of Access Control1.Spring SAML Declarative checks2.RBAC Permission ProgrammaticchecksLittle Rock Tech Fest 201771

Start with Tomcat Servlet ContainerLittle Rock Tech Fest 201772

1. Deploy the Spring SAML DemoLittle Rock Tech Fest 201773

Get the Spring SAML DemoPick one: spring-security-saml - Spring's SAML sample isthe first place java developers should look forbasic SAML 2.0 programming concepts. shibboleth-sample-java-sp - Unicon's sample iswhere ones goes to understand how to combineSpring SAML's SP with Shibboleth's IdP.Little Rock Tech Fest 201774

Generate SAML Service Provider MetadataMatching Fields: Entity ID mustmatch Spring configin web app Entity base URLmust match the webapp’s URL.To use TLSLittle Rock Tech Fest 201775

Spring SAML Metadata Generation TipTheseentityId’smust bean id "metadataGeneratorFilter" class "org.springframework MetadataGeneratorFilter" constructor-arg match bean class "org.springframework MetadataGenerator” property name "entityId" value "fortress-saml-demo"/ /bean /constructor-arg /bean Bind the service provider with the IdP.Little Rock Tech Fest 201776

2. Setup Global Identity ProviderLittle Rock Tech Fest 201777

Setup SSOCircle SAMLv2.0 IdPCreating your Identity with SSOCircle (from their website)For creating your account you need to follow a few steps: Register at the SSOCircle SAMLv2.0 Identity Provider Provide the required data Agree to the Terms of Use After successful creation you will receive an email asking forconfirmation of your registration. Confirm

The Exploit The Jakarta Multipart parser in Apache Struts 2 2.3.x before 2.3.32 and 2.5.x before 2.5.10.1 mishandles file upload, which allows remote