Create more secure apps with less effort (10 by 10)

  • Thread starter Thread starter Rajen Kishna
  • Start date Start date
R

Rajen Kishna

In our final post of the Windows 10 by 10 development series, we’ll talk about the feature introductions and enhancements in Windows 10 that help you create more secure apps. When we think of security, we can split it up in these three main areas: authentication, data-in-flight and data-at-rest. With Windows 10, a number of improvements have been made to lessen the effort for developers in the authentication and data-at-rest areas, specifically around protecting sensitive data on the device and moving away from using passwords. Additionally, Azure API Management can help simplify exposing app APIs securely.

From passwords to Microsoft Passport


Dealing with user credentials for authentication and authorization is something that users and administrators have been doing for quite some time. The problems with traditional user credentials: credential theft, reuse, password complexity and reset mechanisms can make creating secure apps more complex. With Windows 10, Microsoft addresses these problems with two new technologies: Windows Hello and Microsoft Passport. Working together, these technologies help create a more secure, yet convenient way to manage authentication for both end-users and developers.

Windows Hello is the biometric framework built into Windows 10. The three types of biometrics currently supported with Windows Hello are: facial recognition, fingerprint recognition and iris scan. Microsoft Passport is the component that provides strong two-factor authentication, replacing reusable passwords with the combination of a specific device and a user defined PIN or the biometric modalities of Hello. This combination can be used to authenticate users directly with Windows and apps can use the Universal Windows Platform (UWP) APIs offered to implement this authentication. For more information on Windows Hello and Microsoft Passport, check out the extensive Microsoft Passport guide on TechNet, but for now let’s dig into the APIs to use in your UWP apps.

The first thing to do is check whether or not the user is set up for Microsoft Passport in Windows. This can be done with the KeyCredentialManager.IsSupportedAsync method:


var keyCredentialAvailable = await KeyCredentialManager.IsSupportedAsync ();

if (keyCredentialAvailable != true)
{
// Key credential is not enabled yet as user, prompt user to
// set up a PIN by visiting Settings->Accounts->Sign-in options->Pin->Add
return;
}


The next step is to call the KeyCredentialManager.RequestCreateAsync method to generate a private and public key pair. This generation is performed by the Trusted Platform Module (TPM) chip on the device, or by Windows when there’s no TPM-chip available on the device:

var keyCreationResult = await KeyCredentialManager.RequestCreateAsync(AccountId, KeyCredentialCreationOption.ReplaceExisting);


The private keys are opaque to the caller, but the public key should be stored on your identity provider server, together with the user’s unique identifier (e-mail address, username, etc.).

With subsequent uses of the app, the KeyCredentialManager.OpenAsync method is used to prompt the user to authenticate with Microsoft Passport and get the KeyCredential on successful authentication. In the case below the server sends a challenge the client needs to sign with the private key.

var openKeyResult = await KeyCredentialManager.OpenAsync(AccountId);

if (openKeyResult.Status == KeyCredentialStatus.Success)
{
var userCredential = openKeyResult.KeyCredential;
var publicKey = userCredential.RetrievePublicKey();
var signResult = await userCredential.RequestSignAsync(message);

if (signResult.Status == KeyCredentialStatus.Success)
{
return signResult.Result;
}
}



As you can see above, after we get the KeyCredential, we use that to sign a message with the RequestSignAsync method. The message is signed with the private key and sent back to server. The server can check if the message is signed by validating the signature with the stored public key of the user:



This high-level overview of Windows Hello and Microsoft Passport should give you an idea of how this can be implemented in your app. We’ll have a full sample and developer whitepaper to share soon, taking you through the end-to-end approach for implementation in new apps or moving an existing solution from using passwords to Microsoft Passport.

Connecting securely to your web services


Connecting with your back end in a secure way is important for making sure that data does not get intercepted while in flight. The basic requirement of using Secure Sockets Layer (SSL) to establish and maintain secure connections to servers supporting the Secure Hypertext Transfer (HTTPS) protocol is essential in ensuring this message confidentiality. Simply relying on SSL, however, still leaves the possibility for malicious third parties to sit between the client and server, for example by offering insecure “free Wi-Fi” to users and intercepting all traffic. To prevent this, you can validate the SSL certificates that are used by the server by using a technique commonly referred to as “SSL pinning”.

There are a few different ways to implement SSL pinning, each with their own pros and cons. The easiest way to implement it is via the Certificates declaration in the app’s manifest. This declaration enables the app package to install digital certificates and specify exclusive trust to them. This means SSL connections are only allowed from the app to servers with the corresponding root certificate on the server.



For some more flexibility (when communicating with various web servers over SSL, for example), validating the thumbprint(s) of the certificate(s) the server returns when sending an HTTP request might be a better option. One thing to be aware of is that this method requires sending a request and inspecting the response, so be sure to add this as a validation before actually sending sensitive information in a request. The C# code will look similar to this:

private async Task DemoSSLRoot()
{
// Send a get request to Bing
HttpClient client = new HttpClient();
Uri bingUri = new Uri("https://www.bing.com");
HttpResponseMessage response = await client.GetAsync(bingUri);

// Get the list of certificates that were used to validate the server's identity
IReadOnlyList<Certificate> serverCertificates = response.RequestMessage.TransportInformation.ServerIntermediateCertificates;

// Perform validation
if (!ValidCertificates(serverCertificates))
{
// Close connection as chain is not valid
return;
}

PrintResults("Validation passed\n");
// Validation passed, continue with connection to service
}

private bool ValidCertificates(IReadOnlyList<Certificate> certs)
{
// In this example, we iterate through the certificates and check that the chain contains
// one specific certificate we are expecting
for(int i=0; i<certs.Count; i++)
{
PrintResults("Cert# " + i + ": " + certs.Subject + "\n");
byte[] thumbprint = certs.GetHashValue();

// Check if the thumbprint matches whatever you are expecting
// ‎d4 de 20 d0 5e 66 fc 53 fe 1a 50 88 2c 78 db 28 52 ca e4 74
byte[] expected = new byte[] { 212, 222, 32, 208, 94, 102, 252, 83, 254, 26, 80, 136, 44, 120, 219, 40, 82, 202, 228, 116 };

if (ThumbprintMatches(thumbprint, expected))
{
return true;
}
}

return false;
}


In the above example, the DemoSSLRoot method uses the HttpClient class to execute an HTTP request. When the response is given by the client, the RequestMessage.TransportInformation.ServerIntermediateCertificates collection can be used to inspect the certificates returned by the server. This way, the client can validate the entire certificate chain with the thumbprints it has prepopulated. Be aware that this requires the thumbprints of all certificates to be updated in the app, once the server certificate expires and is renewed.

Providing secure access to your back end web APIs can prevent unauthorized use of your APIs. With the growing popularity of RESTful services, however, this becomes increasingly difficult, as data should be accessible through basic HTTP GET/POST requests. The use of API keys for securing RESTful services is a common practice and, while you can implement this yourself, Azure API Management provides a way to publish an API securely, while also being able to monitor, throttle and analyze it.

Securing data on the device


A third place where you need to pay attention to app security is when the data arrives on the device. Storing data securely on the device is something Windows and its app model already helps you with. By default, UWP apps are isolated in their own container, so their data won’t be accessible by other UWP apps. This benefits both reliability and security, as there is no risk of any UWP apps locking, accessing or modifying data, other than the app itself.

While securing data on the device by ways of encryption is usually a good practice, for example with BitLocker, it doesn’t prevent data from being shared to unauthorized third parties by users. That’s why Windows 10 introduces a new capability for enterprises that prevent data leaks by encrypting and classifying data as business data, so it can no longer be accidentally shared outside of a company. This not only protects data at rest on the device, but also data in flight and in use. To implement this capability in your internal apps, you first need to enable the enterpriseDataPolicy capability in your app’s manifest:


<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:rescap= "http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
IgnorableNamespaces="uap mp rescap">
<Capabilities>
<rescap:Capability Name="enterpriseDataPolicy"/>
</Capabilities>
</Package>


Be aware that this is a restricted capability, which means your app will not be eligible for Windows Store publication unless your organization has been specifically approved for it. This does not prevent you from using the capability internally within an organization or when sideloading.

This enables a number of data protection scenarios, including file protection, and application sharing restrictions, that lets work and personal data be used safely in the same application. For example, if you want to show the user some non-corporate data while the application places some enterprise-owned text on the clipboard, and restrict that text to be pasted only in corporate apps that are also allowed access to enterprise data, you’d use the following code:


var dataPackage = new Windows.ApplicationModel.DataTransfer.DataPackage();
dataPackage.SetText(MyTextBox.Text);
dataPackage.Properties.EnterpriseId = yourEnterpriseID;

Windows.ApplicationModel.DataTransfer.Clipboard.SetContent(dataPackage);


In the above example, we create a DataPackage instance, which contains an EnterpriseId property. We can then use the ProtectionPolicyManager to verify if the app is allowed to access the content it’s trying to retrieve from the Clipboard using the Clipboard.GetContent method:


var dataPackageView = Clipboard.GetContent();
if (dataPackageView.Contains(StandardDataFormats.Text))
{
var response = await dataPackageView.RequestAccessAsync();
if (response == ProtectionPolicyEvaluationResult.Allowed)
{
// Allowed access to clipboard
}
else
{
// Blocked access to clipboard
}
}


For more scenarios, take a look at the Enterprise Data Protection sample on GitHub.

Wrapping up


While security remains a complex topic, we’re hoping the description of these new features in Windows 10 give you some ideas on how to harden your UWP apps without having to write large amounts of code. Relying on these Windows 10 features will allow you to focus on the things your app does best, without having to compromise on security.

That brings us to the end of our Windows 10 by 10 development series. We thank you for diving into the 10 compelling Windows platform capabilities over the last 10 weeks and hope the information has inspired you to create great new apps.

The “Know Your Options When it Comes to Storage, Backup and Roaming” quiz is now available on DVLUP to get points and XP for getting up to speed on this week’s topic. Let us know what you think about the series and this week’s topic via @WindowsDev on Twitter using #Win10x10.

Resources


Continue reading...
 
Back
Top