Building trustworthy Windows Store apps – from design to servicing
Tiller BeauchampSenior SDET
Why build trustworthy apps?
• Trust and reputation are integral.• Your reputation is at the fingertips of the user.• Bad reputation may lead to low app
acquisition.
Protect your customers data, privacy, and credentials.
Trust, like reputation, must be built and maintained.
Delivering confidence to customers
Trust is part of developing customer confidence.
Three pillars to delivering confidence:Platform• App isolation, capability model, compiler features.
Windows Store• Onboarding, ratings and reviews, telemetry.
App developers• Follow best practices to design, implement, test, and service
apps.
Users can try and buy apps with confidence.
Building trustworthy apps
Trustworthy apps are built by following best practices throughout the development lifecycle.
• Design• Implementation• Verification• Servicing
Trustworthiness cannot be obtained with an implementation requirement or a test case.
Key Design Decisions
Many aspects can influence your choice of language.
Language choice also determines the classes of issues you must protect against.
Choosing a language
Problem class C/C++ C# JavaScript
Design and logic issues
Yes Yes Yes
Memory corruption (buffer overflows)
Yes - -
Malicious script injection
- - Yes
Leveraging 3rd party frameworks
• Existing frameworks can be leveraged in your app.
• Beware that frameworks may be built with different security assumptions.
• Favor frameworks that advertise compatibility with Windows Store apps. Ex: JQuery 2.0
Good resources to review before including a framework• Microsoft Interoperability blog.• MSDN Windows Store App samples.• Visual Studio Gallery templates and samples.
Managing user credentials
Many policy choices for managing authentication. Eg.• Session timeout lengths.• Handling login after app suspension and termination.
Windows.Security.Authentication.Web • Broker for Oauth, OpenID
Windows.Security.Credentials.PasswordVault • Provides app-specific secure storage for passwords
and tokens.• Roamed across the users trusted devices.
If you must directly handle user credentials remember to only transmit them over secure channels.
Minimize exploit value
Apps with more privileges are more valuable to attackers.
Declare only the capabilities your app needs.• Use file picker instead of declaring library capabilities.• At design time, identify the capabilities that will be
needed. • If capabilities must be added during implementation,
re-evaluate if new threats will be introduced.
Don’t expose WinRT functionality to the web.
The more capabilities you declare, the more valuable your app is to an attacker.
Vulnerability example: exposing WinRT to the webWinJS.xhr({url:”http://contoso.com/fetchcmd”}).done(
function fulfilled(result) {
var cmd = JSON.parse(result.responseText);
eval(cmd.evalMe);
}
}
Vulnerability example: exposing WinRT to the webWinJS.xhr({url:”http://contoso.com/fetchcmd”}).done(
function fulfilled(result) {
var cmd = JSON.parse(result.responseText);
switch(cmd.apiNum) {
case 0:
localFolder.createFileAsync(cmd.filename).then(function (f){
windows.Storage.FilIO.writeTextAsync(f,cmd.content);
}
case 1:
…
Analyzing the Design
App attack surface
• Attack surface can be understood by the data flows in and out of the app.
• Windows Store app inputs and outputs are more structured and consistent than classic apps.
• Attack surface of a Windows Store app can be inferred by capability usage, app contracts, and app extensions.
Attack surface is simply the portions of your app that are exposed to abuse or attack.
Plan to mitigate common threats
Most security issues in apps arise from:• Assuming input is trusted when it isn’t.• Failing to protect data in flight or in storage.• Turning off built-in protections.
These issues can be easily avoided by evaluating the attack surface of your app and planning mitigations.
A threat is a potential attack against your app.
A simple app has
no attack surface.
Attack surface is introduced
when a capability or app
contract is added.
Threat modeling process
• Enumerate threats that apply to the attack surface.
• Identify existing mitigations to those threats.
• Design mitigations for unaddressed threats.
• Validate mitigations.
Threat taxonomies like S.T.R.I.D.E exist to help organize threat enumeration.
Common attack surface of apps
• Opening files – files from documents library should be considered untrusted.
• The web – consuming remote content.• Contracts – share, actions, search• Extensions
Protocol activation – ex: myApp://action/.File activation – ex: somefile.myapp
Local context has much higher privilege than web context.
Local context vs. web context
Feature Local context Web contextWindows Runtime andcapabilities
Yes No
Cross-domain XHR requests
Yes No
External script references
No Yes
Automatic toStaticHTML validation
Yes No
Attack surface, threat, mitigation example
• Attack Surface: App implements custom URI scheme contosoapp://savecontent?URI={foo}.
• Threat: Malicious webpage invokes contosoapp:// URI to cause untrusted content to be saved to the app.
• Mitigation: content is only saved if URI parameter has domain = contoso.com or proseware.com.
Threat modeling is a brainstorming exercise
Consider each element and dataflow on the attack surface.
What could possibly go wrong?• Assume unencrypted traffic can be read/modify by an
attacker.• Assume remote data sources are malicious.
Goal is to ensure that the design is resilient to attack.
Implementing a trustworthy app
Build testable code
Follow a pattern that produces well factored code.• Model view ViewModel (MVVM).• Test driven development.
Visual Studio Test Explorer for unit testing.• Built-in unit test sample projects.• Visual Studio gallery has additional unit test
extensions and frameworks.
Avoid minifying JavaScript code.
Following established patterns can produce code that’s easier to test and debug.
Leverage built-in mitigations
Compile with latest version Visual Studio.• /GS, ASLR, DEP, SeHOP on by default.
Automatic script injection protections in WWAs.• Do not disable this protections with
execUnsafeLocalFunction.
Treat remote data as untrusted
• Files in documents library can be malformed.• Brokers pass data directly from other sources.• Data can be tampered with when transferred
unencrypted.
• Improper handling can lead to:Script injection in WWAs.Classic memory corruption flaws in native apps.
When handling data from remote sources, assume that the format might have been tampered with or malformed.
Sources of untrusted data
• Files (libraries, file picker, file activation)
• Protocol activation• Sharing sources• Actions sources• Web content• Messages from iframes and webviews
Only trust data packaged with your app.
Handling untrusted data
• Leverage platform APIs for handling files, parsing XML and Json.
• Validate or restrict source of data where possible.
• Sanitize or verify format.• Use a convention to indicate untrusted
dataVariable naming or comments
Only trust data packaged with your app.
Validate source of postMessage event
// Secure message handler, validates message domain origin
window.addEventListener('message', function (e) {
if (e.origin === 'http://data.contoso.com') {
div.innerHTML = window.toStaticHTML(e.data);
}
}, false);
Sanitizing HTML from share source
if(shareOperation.data.contains(StandardDataFormats.html)) {
shareOperation.data.getHtmlFormatAsync().then(function (ut_html) {
if (ut_html !== null) {
var s_htmlFragment = HtmlFormatHelper.getStaticFragment(ut_html);
var myDiv = document.getElementById("htmlContent");
myDiv.innerHTML = s_htmlFragment;
}
});
Navigating to saved HTML content
• You can now navigate a WebView directly to saved content in your AppData directory.
• The domain for saved content is based on the directory.
• Preserve same-origin policy.Save HTML content from different domains to
different directories.
Vulnerability: SOP violation (pseudo code)page1 = xhr(“http://contoso.com/page1.html”);
page2 = xhr(“http://adnetwork.net/1-78235-872.html”);
Windows.Storage.ApplicationData.current.localFolder.createFolderAsync(“MySaved”);
// save page1 and page2 content to files in MySaved folder
// navigate to page2.html
myWebView.navigate(“ms-appdata:///local/MySaved/page2.html”)
// page2 can access contents of page 1.
Using self-signed certs in apps
• Create your self signed certificate• Install private key and cert on server• Package your certificate with your app• Declare certificate extension in app manifest
You cert will be installed in a certificate store specific to your app.
Adding custom cert in Visual Studio
Custom certificate in the app manifest
<Extensions><Extension Category="windows.certificates"> <Certificates> <Certificate StoreName="Root" Content="myroot.cer" /> <Certificate StoreName="CA" Content="mystandca.cer"/> <TrustFlags ExclusiveTrust="true" /> <SelectionCriteria AutoSelect="true"/> </Certificates> </Extension> </Extensions>
Other Tips
Encrypt sensitive data using WinRT API• Windows.Security.Cryptography.DataProtectio
n
Use XDomainRequest instead of XHR when cookies are not needed
See MSDN documentation and links in resources for more details.
Verification
Principles of effective testing
• Complete coverageCoverage of all attack surfaces and functional
scenariosInclude testing of mitigations.
• RepeatableAutomate test cases as much as possible.
• Easy to extendAdded app functionality means new tests.
Validate mitigations
• Identify mitigations that were planned up front
• Execute on test cases to validate
Ensure that mitigations:• function properly• cannot be bypassed
Validate mitigation example
Contosoapp://savecontent?URI=http://contoso.com/inappcontent/en-us/1234
Implement a test app to invoke the URI scheme.Create list of cases that attempt to bypass the check.
http://evil.com/contoso.com/inappcontent...http://evil.com/&http://contoso.com/inappcontent...evil.com/http://contoso.com/inappcontent……
Mitigation was to validate domain of URI against a white list.
Review attack surface
Attack surface is wholly defined in appxmanifest.xml
• Capabilities: Network, Libraries and removable storage
• Contracts: File save picker, Search, Share, Actions• Extensions: Autoplay, File activation, Protocol
activation
Review the manifest file and confirm the attack surface matches the initial design.
Planned attack surface may not be the final attack surface.
Put on your adversarial hat.Forget what you know of the design.
Tips:• Use a web proxy to tamper with traffic to your app.• Inspect captured traffic for any sensitive customer
data sent unencrypted.• Can a customer configure insecure settings in your
app?• Use malformed inputs in search and share contracts.
Follow a black box approach and pretend you are the attacker.
Hack your app
Perform code review
Search the source code and review usage of dangerous APIs.• eval should never be called on untrusted data• execUnsafeLocalFunction should not wrap DOM
manipulation functions that operate on untrusted data
• scriptNotify/postMessage handlers should not expose WinRT functionality
• SDL Banned API list. Ex: strcpy, memcpy, sprintf, etc.
Review usage of sanitizing functions like toStaticHTML, to ensure their code path cannot be skipped.
Fuzz test native code parsers
Custom parsing could be:• Media file formats, video streams• Network protocols
Well isolated parsing code can be fuzzed using API fuzzing approach. File fuzzing is another approach.
Favor API fuzzing approach when possible.
Fuzz testing is an effective approach to finding bugs in native code parsers.
Document results
Document what was tested, test cases, and results.
You cannot improve without understanding what you’ve done in the past.
• Run Windows App Certification Kit• Remove private networking capability if you
had added it for local testing.• Strip EXIF data from images (ex: geo
coordinates).• Remove debug code.• Do not ship minified scripts or obfuscated
code.
Checklist before onboarding
Servicing
Many reasons to update your app• Add new features.• Address customer feedback.• Improve reliability and security.• Include updated versions of third-party frameworks.
Updating your app
Windows Store developer dashboard provides telemetry data on JavaScript exceptions, crash rate, and hangs.
Crashes might indicate a security problem
• For native apps, pay attention to crashes due to memory corruption, such as write and read access violations.
• For JavaScript apps, watch out for exceptions regarding dynamic content injection.
• Only the top occurring issues for your app are reported. Fixing these issues causes less common issues to bubble up.
Follow updates for 3rd party frameworks
• Frameworks you package may have their own bug fixes.
• Subscribe to framework announcement lists.
• Plan to update your app with new version of frameworks.
Security response
• Coordinate a vulnerability disclosure.• Publish contact for security reports.• Respond in timely matter.• Allocate resources to triage and fix
reported issues.
Security response
• Third-party researchers or Microsoft may become aware of security or privacy issues in your app.
• Microsoft can coordinate communication between you and the finder.
• If you are contacted about a vulnerability in your app that also affects a Microsoft product, please contact [email protected].
Conclusion
DesignKey choices: language, auth, frameworks, exploit
valueAnalysis: Attack surface, threats, mitigations
ImplementBuild testable code, built-in mitigationsHandling untrusted data, other tips.
VerifyTest mitigations, hack your app, code review, fuzz
test
Service Leverage telemetry, security response, update
frameworks
Resources
Delivering reliable and trustworthy appshttp://blogs.msdn.com/b/b8/archive/2012/05/17/delivering-reliable-and-trustworthy-metro-style-apps.aspx
Security best practices for building Windows Store apps
http://blogs.msdn.com/b/windowsappdev/archive/2012/12/18/security-best-practices-for-building-windows-store-apps.aspx
Uncover Security Design Flaws Using The STRIDE Approach
http://msdn.microsoft.com/en-us/magazine/cc163519.aspx
Resources (cont.)
Features and Restrictions by context (Windows Store apps using JavaScript and HTML)
http://msdn.microsoft.com/en-us/library/windows/apps/hh465373.aspx
Developing secure appshttp://msdn.microsoft.com/en-us/library/windows/apps/hh849625.aspx
© 2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.