Securing JSF Applications Against OWASP Top Ten

2y ago
57 Views
5 Downloads
265.29 KB
66 Pages
Last View : 9d ago
Last Download : 3m ago
Upload by : Ronnie Bonney
Transcription

Securing JSF ApplicationsAgainst the OWASP Top TenDavid ChandlerSr. Engineer, Intuitdavid.chandler@learnjsf.comJSF OneRich WebExperienceSep 2008http://www.webappsec.org/Copyright 2007 - The OWASP FoundationPermission is granted to copy, distribute and/or modify this document under theterms of the Creative Commons Attribution-ShareAlike 2.5 License. To view thislicense, visit http://creativecommons.org/licenses/by-sa/2.5/The OWASP Foundationhttp://www.owasp.org/

JSF is a Great FrameworkTool-friendlyMVCComponent-orientation makes reuse easyBut .Is it safe?JSF One / Rich Web Experience Sep 2008

Framework Security ContinuumMoresecureFramework makes it impossible fordevelopers to write insecure codeDevelopers must do all the right stuff, butyou can use code scanning tools andlimited inspection to find holesPossible, but developers must do all theright stuffNot possible to create a secure app(framework is flawed)Less secureJSF One / Rich Web Experience Sep 2008

Security Analysis GoalsAddress framework / implementationvulnerabilitiesLock front door and back doorInspect application code for vulnerabilities Ideally, centralize validation and use other JSFextensions to minimize inspection points Use automated scanning tools to verify thatApplication code uses only safe components / extensionsApplication code does not access the external contextdirectly (HttpSession) or use Lifecycle in unsafe waysJSF One / Rich Web Experience Sep 2008

Our Mission TodayLearn how to secure JSF applicationsUsing the OWASP Top Ten as a guideOWASP Open Web Application Security Project Fantastic resource Go to an OWASP conference sometime If your security folks are focused mainly on firewalls,they need to go to an OWASP conference, tooJSF One / Rich Web Experience Sep 2008

What is JavaServer Faces (JSF)?What is JSF? Spec, not an implementation (JSR 127, 252) Many vendor implementations and two open sourceMojarra (Sun)Apache MyFacesWhere does it fit in the frameworks universe? MVC, component-based framework servlet Builds on Struts controller, form bean concepts Builds on Tapestry componentsJSF One / Rich Web Experience Sep 2008

What’s in a Typical JSF AppView templates (JSP or Facelets)Managed bean for each view registered in facesconfig.xmlNavigation rules in faces-config.xmlJSF One / Rich Web Experience Sep 2008

Major JSF ConceptsComponentsRenderersManaged beansConverters / ValidatorsController (navigation model)Event handlingRequest lifecycleJSF One / Rich Web Experience Sep 2008

JSF ComponentsSeparate business logic from presentationEvery view is composed of a component hierarchyComponents can be added to view programmatically orvia template (JSP by default, Facelets for superiorperformance and ease of development)Standard components divided into two groups: Faces Core f:view , f:loadBundle HTML wrappers h:dataTable , h:selectMany , etc.Component class [renderer] tag handler (JSP)JSF One / Rich Web Experience Sep 2008

JSF RenderersComponent renderer encodes (generates theHTML) for the componentRenderer also decodes (sets component valuesfrom URL query string and form vars)Renderers are grouped into render kits Default render kit is HTML Provide device independence w/o changing thetemplating language or components themselvesMost String I/O happens in renderersJSF One / Rich Web Experience Sep 2008

JSF Managed BeansLink view to the model (like controller) Provide action methods which in turn call appropriatemodel code (save, new) Provide helper methods (getAvailableSelectItems) Hold references to one or more domain objectsManaged by the framework in one of severalscopes Standard: request, session, application, none SEAM offers conversation scope Spring Web Flow offers flashScope, flowScope,conversationScopeJSF One / Rich Web Experience Sep 2008

JSF Value BindingComponent values bind to model beansFor each request, the framework Converts each input value (String) into the underlyingJava type (MoneyAmount) On output, converts underlying Java type to StringYou register converters for custom typesAll security validation therefore handled centrallyand automatically by model typeJSF One / Rich Web Experience Sep 2008

JSF Value Binding Exampleview.xhtmlIn logger objectJSF One / Rich Web Experience Sep 2008

JSF Value Binding Exampleview.xhtmlManaged beans are registered in faces-config.xmlJSF One / Rich Web Experience Sep 2008

JSF Converters / ValidatorsConverters are bi-directional Input converter: getAsObject() Output converter: getAsString()Validators work with Objects, not just StringsJSF supplies standard converters for date / time,numbers, etc.You write custom converters for rich types orspecial behaviorJSF One / Rich Web Experience Sep 2008

JSF Converters / ValidatorsJSF One / Rich Web Experience Sep 2008

JSF Converter ExampleConverter is registered in faces-config.xml, so allValuedTypesafeEnum properties of any bean will use this converterValidators also registered in faces-config.xml, but not by classJSF One / Rich Web Experience Sep 2008

JSF ControllerStateful or stateless navigation modelFramework selects next view based on Previous view Outcome of the event handler Event itself (regardless of outcome) Any combination of the abovePossibilities Universal error view (triggered by “error” outcome) Wildcard matching permitted in outcomes, view IDsJSF One / Rich Web Experience Sep 2008

JSF Event Handling h:commandButton action “#{ReportCtrl.save}” Generates an event when pressed save() is a method on a managed beanJSF calls ReportController.save()Can also define action listeners associated with othercomponents in the form Example: AccountSearch on any page without having to tell JSFnavigation controller about each instanceCustom ActionListenerImpl runs before invoking methodJSF One / Rich Web Experience Sep 2008

JSF Request LifecycleRestoreViewRetrieve component treefrom client or sessionApply RequestValuesRequestRequestDecode components(populate w/ String values)Convert Strings to ObjectsValidate ObjectsProcessValidationsCall setterson managed beansUpdateModelInvoke bean method(s)Compute navigationResponseResponseMay skip torender phaseor abort requestInvokeApplicationCall bean getters topopulate componentsJSF One / Rich Web Experience Sep 2008RenderResponse

JSF Extension PointsCustom componentsPhase listeners (before, after any phase)Custom converters / validatorsCustom renderersCustion ActionListenerImpl to handle eventDecorate or replace view handler, navigationhandler, state manager, etc.JSF One / Rich Web Experience Sep 2008

JSF Configurationfaces-config.xmlContains navigation rules as well as anycustomizations / extensionsCan be split among directories and subdirectories as well as jars Set javax.faces.application.CONFIG FILES in web.xml Or put META-INF/faces-config.xml in jars so canbundle required configuration with codeJSF One / Rich Web Experience Sep 2008

OWASP Top Ten*A1 Unvalidated InputA2 Broken AccessControlA3 Broken Authenticationand Session MgmtA4 Cross Site ScriptingA5 Buffer OverflowA6 Injection FlawsA7 Improper ErrorHandlingA8 Insecure StorageA9 Application Denial ofServiceA10 InsecureConfiguration Mgmt* 2004 Top Ten listing used for better presentation flowJSF One / Rich Web Experience Sep 2008

A1 Unvalidated InputParameter tampering (hidden & list boxes)Required fieldsLength, data type, allowed valuesCross site request forgery (CSRF)Buffer overflows (see A5)JSF One / Rich Web Experience Sep 2008

A1 Unvalidated InputJSF Validation ProcessValidation is part of the request lifecycleWhen validation fails Throw ConverterException or ValidationException Add message to the message queueMessage is associated with offending componentUse h:messages/ or h:message for “component id”/ Don’t forget one of these in your view! Skip directly to render response phaseJSF One / Rich Web Experience Sep 2008

JSF Request LifecycleRetrieve component treeRestorefrom client or sessionViewApply RequestDecode componentsValues(populate w/ String values)Convert Strings to ObjectsValidate ObjectsProcessValidationsRequestRequestCall setterson managed beansUpdateModelInvoke bean method(s)Compute navigationResponseResponseMay skip torender phaseor abort requestInvokeApplicationCall bean getters topopulate componentsJSF One / Rich Web Experience Sep 2008RenderResponse

A1 Unvalidated InputJSF Validation ProcessThing of beauty! Model values never updated with invalid data User remains on current view No action methods called Messages tagged with component IDUnless immediate “true” for some component If so, managed bean can access raw component values throughcomponent tree (don’t!) JSF will NEVER update model unless validation passesJSF One / Rich Web Experience Sep 2008

A1 Unvalidated InputParameter TamperingHidden fieldsMultiple choices (radio, check box, select)Required fieldsJSF One / Rich Web Experience Sep 2008

A1 Unvalidated InputParameter Tampering (Hidden Fields)Did you say hiddenfields ?YUCK!Of course, they can betampered with!Must rely on validation aswith any other fieldJSF One / Rich Web Experience Sep 2008

A1 Unvalidated InputParameter Tampering (Select Options)List boxes, radio buttons, check boxes h:selectOneRadio value “#{bean.choice}” f:selectItems value “#{bean.allChoices} /h:selectOneRadio JSF selectOne and selectMany components validateselected items against available choicesComponent calls selectItems getter again and comparesselected String with available StringsSee java.faces.component.UISelectOne/ManyJSF One / Rich Web Experience Sep 2008

A1 Unvalidated InputParameter Tampering (Req’d Fields)Required fields h:inputText value “#{bean.prop}”required “true or EL” / If required field is empty (“”, not null),JSF will fail validation as usual Can change default msg in properties file Or for really custom requiredness checking, write acustom converter (because validator doesn’t getcalled for empty fields, but converter does)JSF One / Rich Web Experience Sep 2008

A1 Unvalidated InputValidating Length, Format, Data TypeBuilt-in validators for length & range f:validateLength / , f:validateDoubleRange / , f:validateLongRange / maxLength DOESN’T affect validationBuilt-in converters For all wrapper types (Boolean, Byte, etc.) f:convertDateTime / , f:convertNumber / See Tomahawk for e-mail, regex, credit cardServer client validators in Spring Web Flow Number, text (regex), date, currency Client-side built on DojoJSF One / Rich Web Experience Sep 2008

A1 Unvalidated InputCustom ValidatorsSimple interface public void validate( )throws ValidatorExceptionCan invoke one of three ways setValidator() in custom component As validator tag (Facelets auto-wiring ) like built-ins my:customValidator / h:inputText validator “id #{bean.validator} JSF One / Rich Web Experience Sep 2008

A1 Unvalidated InputCustom ConvertersSimple interface getAsObject( ) getAsString( )Invoke one of four ways By type of model property bound to component setConverter() in custom component As converter tag (Facelets auto-wiring ) like builtins my:customConverter / h:inputText converter “id #{bean.converter} JSF One / Rich Web Experience Sep 2008

A1 Unvalidated InputRich Type (Model Centric) Converter converter-for-class StringAN / public static class UserCode extends StringAN {Public UserCode (String value) throws InvalidStringException {super(value, 14); // length}}In your model class, define & use type UserCodeNow all components bound to property of type UserCodeare automatically converted / validatedStringAN does validation in constructor so an invalidinstance can never be createdJSF One / Rich Web Experience Sep 2008

A1 Unvalidated InputJSF Validation SummaryStrengths All validations declarative Associated with view, not action (so can’t beoverlooked in case of multiple actions) Model never updated unless all validations pass Converter-for-class eliminates need for explicitvalidator on every widgetJSF One / Rich Web Experience Sep 2008

A1 Unvalidated InputJSF Validation SummaryWeaknesses Requires manual inspection of views and beans toconfirm that you didn’t miss a validator or twoBut can be automated You use only custom converters / validators that addthe id of each validated component to a Requestvariable And use a phase listener after validation to walk thecomponent tree and find unvalidated UIInputs Appropriate for QA, but likely not productionJSF One / Rich Web Experience Sep 2008

A1 Unvalidated InputJSF Validation ExtraHow can I validate related fields together? i.e., StartDate EndDate Can do in bean action method. Not part of validationlifecyle, but can have all the same effectsReturn null outcome to remain on viewAdd message to queueSkip remainder of action method Alternatively, put a dummy tag after last form field h:inputHidden validator “#{bean.method}” / But model not updated yet, so must hard code componentIDs in beanJSF One / Rich Web Experience Sep 2008

A1 Unvalidated InputWhat About JSF and AJAX?Approach 1 Separate servlet or JSF phase listener to interceptand handle AJAX queries Bypasses JSF validation (ouch)Approach 2 ICEFaces and AJAX4JSF provide simple AJAX-capableJSF components Retains JSF server-side validation (good!)Careful! Some AJAX components use JSON andmay be subject to JavaScript hijackingJSF One / Rich Web Experience Sep 2008

A1 Unvalidated InputCross Site Request Forgery (CSRF)Aka session riding, one-click attack Example img src "http://www.example.com/transfer.do?frmAcct document.form.frmAcct&toAcct 4345754&toSWIFTid 434343&amt 3434.43" How to prevent? JSF always uses POST to invoke actionsAttack above would therefore failBut attacker can POST via JavaScript Solution: random token in each request For sensitive transactions, also some form oftransaction signing with request (token, etc.)JSF One / Rich Web Experience Sep 2008

A1 Unvalidated InputCross Site Request Forgery (CSRF)JSF can be extended to prevent all out-ofsequence requests, including CSRF Postback URL is obtained from the ViewHandler Decorate ViewHandlerImpl to override getActionURL()and append a hash of the URL Write custom phase listener toGenerate new token in Session for each requestCompare hash in the URL with expected token All h:commandLink s and h:commandButton sare now protected (w/ no mappings required!)JSF 1.2 isPostback() headed the right direction,but not there yet (no random token)JSF One / Rich Web Experience Sep 2008

A2 Broken Access ControlInsecure IDsForced Browsing Past Access Control ChecksPath TraversalFile PermissionsClient Side CachingJSF One / Rich Web Experience Sep 2008

A2 Broken Access ControlForced Browsing Past Access ControlSafe approaches to user authentication Use built-in features of servlet container or portal Servlet filter Spring / ACEGI (see Cagatay Civici’s presentation) Extend MyFacesGenericPortlet with auth hooks Portlet filter—see MyFaces JIRA 434 Phase listener before RESTORE ext.isUserInRole()Both servlet impl and portlet impl define these methodsJSF One / Rich Web Experience Sep 2008

A2 Broken Access ControlForced Browsing Past Access ControlSafe ways to control access to views (easy) Use rendered attribute with bean permissiongetters for fine-grained control h:column rendered “#{bean.hasPermX}”/ Use above with CSRF preventerOnly have to check view perms when you display a link Mapping approachesPhase listener that maps view IDs to user permsAnd/or custom component to restrict access to view my:authChecker reqPerm “view accounts” / Spring SecurityJSF One / Rich Web Experience Sep 2008

A2 Broken Access ControlForced Browsing Past Access ControlSafe ways to control access to actions (easy) Check perms in each bean action method Use rendered attribute with bean permission getterswhen displaying links h:commandLink rendered “#{bean.hasEditPerm}” / JSF automatically prevents forcing the action, even withoutforced browsing preventer Centralized approachDecorate ActionListenerImpl to intercept eventsConceivable to annotate bean methods with requiredpermissions Spring SecurityJSF One / Rich Web Experience Sep 2008

A2 Broken Access ControlClient Side CachingConcern: browser caching, shared terminalsUse phase listener to write no-cache headersJSF One / Rich Web Experience Sep 2008

A3 Broken Authenticationand Session ManagementNot JSF-specific Password policy, storage Roll-your-own session management (don’t!) Protect login via SSLLogin page should always POST, not GETJSF forms are always POSTedJSF One / Rich Web Experience Sep 2008

A4 Cross Site ScriptingTwo types of attacks Stored (ex: malicious input stored in DB) Reflected (ex: malicious e-mail submits a requestwith cookie-stealing Javascript in text field)Reflected attacks are initiated externally (as via e-mail)Forced browsing / session riding preventer stops these sincerequest doesn’t contain a valid hashJust make sure you don’t put an unchecked HTTP header orcookie in the error messageTwo approaches: input & output filteringJSF One / Rich Web Experience Sep 2008

A4 Cross Site ScriptingApproach 1: Input FilteringFilter all input with Converters, Validators Positive enforcement (allowed characters only)stronger than negative enforcement (remove “bad”chars) JSF numeric converters protect numeric properties Don’t forget HTTP headers & cookies are input, tooRich type converters greatly help with text input(i.e., UserCode alphanumeric, maxlen 14) Then you only need to worry about value bindings tofree form String model propertiesJSF One / Rich Web Experience Sep 2008

A4 Cross Site ScriptingApproach 2: Output FilteringJSF does this mostly for you h:outputText , h:outputFormat , h:outputLabel , and h:select values areescaped unless you turn off with escape ”false” h:outputLink URIs beginning with “javascript:” areescaped All other MyFaces 1.1.x components and attributesare safely rendered, but in 1.2 spec image attribute of h:commandButton not esc’dsrc attribute of h:graphicImage not esc’d Escaped output chars are “ &NOT sufficient if JSF component within a JavaScript block!JSF One / Rich Web Experience Sep 2008

A4 Cross Site ScriptingXSS Code ReviewWhat to look for in view templates escape “false” h:outputLink value “#{bean.property}” / Any output components between script tagsWhat to look for elsewhere Rich type (custom) converters should properly escapeoutput characters “ & Likewise custom components and renderersJSF One / Rich Web Experience Sep 2008

A5 Buffer OverflowsNot an issue in Java per seMight be an issue for 3rd party systems (DB)Always validate input for length Numeric types are safe (Integer, Long, etc.) Prefer rich types to Strings Use f:maxLength for String properties Keeping max lengths short also helps with XSSJSF One / Rich Web Experience Sep 2008

A6 Injection FlawsEx: SQL injectionSELECT * FROM users where ID URL.IDSuppose URL.ID “34; DROP TABLE users”Most effective protection is nearest the calls toexternal system Use O/R mapping Parameterize all queriesJSF can help prevent often related informationleakageJSF One / Rich Web Experience Sep 2008

A6 Information LeakageCommon Problem: IDs in URLsJSF h:dataTable uses indexed rows Don’t use f:param with real IDs Use ListDataModel and getRowData(). JSF will do themapping and get the Object for you What if an item is added to the table between clicks? Could write custom HtmlDataTable component thatoverrides getClientId() to hash row values vs. index UIData is broken, see RichFaces ExtendedDataModelJSF One / Rich Web Experience Sep 2008

A6 Information LeakageCommon Problem: IDs in OPTIONsValues of select options, radio buttons, checkboxes often use real IDs Parameter tampering OK, but possible info leakageSeveral ways to avoi

JSF One / Rich Web Experience Sep 2008 JSF Event Handling h:commandButton action “#{ReportCtrl.save}” Generates an event when pressed save() is a method on a managed bean JSF calls ReportController.save() Can also define action listeners associated with other components in the form Example: AccountSearc

Related Documents:

OWASP Code review guide, V1.1 The Ruby on Rails Security Guide v2 OWASP UI Component Verification Project (a.k.a. OWASP JSP Testing Tool) Internationalization Guidelines and OWASP-Spanish Project OWASP Application Security Desk Reference (ASDR) OWASP .NET Project Leader OWASP Education Project

JSF has nothing to do with JSP per se. JSF works with JSP through a JSP tag library bridge. However, the life cycle of JSF is very different from the life cycle of JSP. Facelets fits JSF much better than JSP because Facelets was designed with JSF in mind, whereas integrating JSF and JSP has

Building JavaServer Faces Applications 7 JSF – A Web Framework JSR 127 – JSF specification v1.1 JSF 1.2 in progress (JSR 252) JSP 2.1 (JSR 245) will align with JSF JSF spec lead was the Struts architect JavaServer Faces technology simplifies building user interfaces for JavaServer

JSF includes a set of predefined UI components, an event-driven programming model, and the ability to add third-party components. JSF is designed to be extensible, easy to use, and toolable. This refcard describes the JSF development process, standard JSF tags, the JSF expressi

What is JSF? Java Server Faces Java specification for building component-based user interfaces for web applications. It gives you the tools to communicate with java backing beans. JSF has all the javascript behind the scenes, creates the endpoints from JSF managed beans, and wires it all together. Agility. D

JSF control boards JSF changes holding tank Individual JSF design changes S s a Study-specific archives NIMA, DTRA, NRO, etc. Program Offices Intel Centers JSFPO, JFCOM, DoD, etc. Threat C&P information Operational context information Natural environment & infrastructure C&P information Blue s

NOTE: Both JSF and Struts developers implement web pages with JSP custom tags. But Struts tags generate HTML directly, whereas JSF tags rep-resent a component that is independent of the markup technology, and a renderer that generates HTML. That key difference makes it easy to adapt JSF

North & West Sutherland LHP – Minutes 1/3/07 1 NORTH & WEST SUTHERLAND LOCAL HEALTH CARE PARTNERSHIP Minutes of the meeting held on Thursday 1st March 2007 at 12:00 noon in the Ben Loyal Hotel, Tongue PRESENT: Dr Andreas Herfurt Lead Clinician Dr Alan Belbin GP Durness Dr Cameron Stark Public Health Consultant Dr Moray Fraser CHP Medical Director Mrs Georgia Haire CHP Assistant General .