title | titleSuffix | description | services | author | ms.service | ms.subservice | ms.topic | ms.date | ms.author | ms.custom |
---|---|---|---|---|---|---|---|---|---|---|
Configuration management for the Microsoft Threat Modeling Tool |
Azure |
Learn about configuration management for the Threat Modeling Tool. See mitigation information and view code examples. |
security |
jegeib |
security |
security-develop |
article |
02/07/2017 |
jegeib |
devx-track-js, devx-track-csharp |
Title | Details |
---|---|
Component | Web Application |
SDL Phase | Build |
Applicable Technologies | Generic |
Attributes | N/A |
References | An Introduction to Content Security Policy, Content Security Policy Reference, Introduction to content security policy, Can I use CSP? |
Steps | Content Security Policy (CSP) is a defense-in-depth security mechanism, a W3C standard, that enables web application owners to have control on the content embedded in their site. CSP is added as an HTTP response header on the web server and is enforced on the client side by browsers. It is an allowed list-based policy - a website can declare a set of trusted domains from which active content such as JavaScript can be loaded. CSP provides the following security benefits:
|
Example policy:
Content-Security-Policy: default-src 'self'; script-src 'self' www.google-analytics.com
This policy allows scripts to load only from the web application's server and google analytics server. Scripts loaded from any other site will be rejected. When CSP is enabled on a website, the following features are automatically disabled to mitigate XSS attacks.
Inline scripts will not execute. Following are examples of inline scripts
<script> some JavaScript code </script>
Event handling attributes of HTML tags (for example, <button onclick="function(){}">
javascript:alert(1);
Strings will not be evaluated as code.
Example: var str="alert(1)"; eval(str);
Title | Details |
---|---|
Component | Web Application |
SDL Phase | Build |
Applicable Technologies | Generic |
Attributes | N/A |
References | XSS Protection Filter |
Steps | X-XSS-Protection response header configuration controls the browser's cross site script filter. This response header can have following values:
This is a Chromium function utilizing CSP violation reports to send details to a URI of your choice. The last two options are considered safe values. |
Title | Details |
---|---|
Component | Web Application |
SDL Phase | Build |
Applicable Technologies | Generic |
Attributes | N/A |
References | ASP.NET Debugging Overview, ASP.NET Tracing Overview, How to: Enable Tracing for an ASP.NET Application, How to: Enable Debugging for ASP.NET Applications |
Steps | When tracing is enabled for the page, every browser requesting it also obtains the trace information that contains data about internal server state and workflow. That information could be security sensitive. When debugging is enabled for the page, errors happening on the server result in a full stack trace data presented to the browser. That data may expose security-sensitive information about the server's workflow. |
Title | Details |
---|---|
Component | Web Application |
SDL Phase | Build |
Applicable Technologies | Generic |
Attributes | N/A |
References | N/A |
Steps | Third-party JavaScripts should be referenced only from trusted sources. The reference endpoints should always be on TLS. |
Title | Details |
---|---|
Component | Web Application |
SDL Phase | Build |
Applicable Technologies | Generic |
Attributes | N/A |
References | OWASP click-jacking Defense Cheat Sheet, Internet Explorer Internals - Combating click-jacking With X-Frame-Options |
Steps | Click-jacking, also known as a "UI redress attack", is when an attacker uses multiple transparent or opaque layers to trick a user into clicking on a button or link on another page when they were intending to click on the top-level page. This layering is achieved by crafting a malicious page with an iframe, which loads the victim's page. Thus, the attacker is "hijacking" clicks meant for their page and routing them to another page, most likely owned by another application, domain, or both. To prevent click-jacking attacks, set the proper X-Frame-Options HTTP response headers that instruct the browser to not allow framing from other domains |
The X-FRAME-OPTIONS header can be set via IIS web.config. Web.config code snippet for sites that should never be framed:
<system.webServer>
<httpProtocol>
<customHeader>
<add name="X-FRAME-OPTIONS" value="DENY"/>
</customHeaders>
</httpProtocol>
</system.webServer>
Web.config code for sites that should only be framed by pages in the same domain:
<system.webServer>
<httpProtocol>
<customHeader>
<add name="X-FRAME-OPTIONS" value="SAMEORIGIN"/>
</customHeaders>
</httpProtocol>
</system.webServer>
Title | Details |
---|---|
Component | Web Application |
SDL Phase | Build |
Applicable Technologies | Web Forms, MVC5 |
Attributes | N/A |
References | N/A |
Steps | Browser security prevents a web page from making AJAX requests to another domain. This restriction is called the same-origin policy, and prevents a malicious site from reading sensitive data from another site. However, sometimes it might be required to expose APIs securely which other sites can consume. Cross Origin Resource Sharing (CORS) is a W3C standard that allows a server to relax the same-origin policy. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others. CORS is safer and more flexible than earlier techniques such as JSONP. At its core, enabling CORS translates to adding a few HTTP response headers (Access-Control-*) to the web application and this can be done in a couple of ways. |
If access to Web.config is available, then CORS can be added through the following code:
<system.webServer>
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Allow-Origin" value="https://example.com" />
</customHeaders>
</httpProtocol>
If access to web.config is not available, then CORS can be configured by adding the following C# code:
HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", "https://example.com")
Note that it is critical to ensure that the list of origins in "Access-Control-Allow-Origin" attribute is set to a finite and trusted set of origins. Failing to configure this inappropriately (for example, setting the value as '*') will allow malicious sites to trigger cross origin requests to the web application >without any restrictions, thereby making the application vulnerable to CSRF attacks.
Title | Details |
---|---|
Component | Web Application |
SDL Phase | Build |
Applicable Technologies | Web Forms, MVC5 |
Attributes | N/A |
References | Request Validation - Preventing Script Attacks |
Steps | Request validation, a feature of ASP.NET since version 1.1, prevents the server from accepting content containing un-encoded HTML. This feature is designed to help prevent some script-injection attacks whereby client script code or HTML can be unknowingly submitted to a server, stored, and then presented to other users. We still strongly recommend that you validate all input data and HTML encode it when appropriate. Request validation is performed by comparing all input data to a list of potentially dangerous values. If a match occurs, ASP.NET raises an |
However, this feature can be disabled at page level:
<%@ Page validateRequest="false" %>
or, at application level
<configuration>
<system.web>
<pages validateRequest="false" />
</system.web>
</configuration>
Note that Request Validation feature is not supported, and is not part of MVC6 pipeline.
Title | Details |
---|---|
Component | Web Application |
SDL Phase | Build |
Applicable Technologies | Generic |
Attributes | N/A |
References | N/A |
Steps | Developers using standard JavaScript libraries like JQuery must use approved versions of common JavaScript libraries that do not contain known security flaws. A good practice is to use the most latest version of the libraries, since they contain security fixes for known vulnerabilities in their older versions. If the most recent release cannot be used due to compatibility reasons, the below minimum versions should be used. Acceptable minimum versions:
Never load any JavaScript library from external sites such as public CDNs |
Title | Details |
---|---|
Component | Web Application |
SDL Phase | Build |
Applicable Technologies | Generic |
Attributes | N/A |
References | IE8 Security Part V: Comprehensive Protection, MIME type |
Steps | The X-Content-Type-Options header is an HTTP header that allows developers to specify that their content should not be MIME-sniffed. This header is designed to mitigate MIME-Sniffing attacks. For each page that could contain user controllable content, you must use the HTTP Header X-Content-Type-Options:nosniff. To enable the required header globally for all pages in the application, you can do one of the following |
Add the header in the web.config file if the application is hosted by Internet Information Services (IIS) 7 onwards.
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="X-Content-Type-Options" value="nosniff"/>
</customHeaders>
</httpProtocol>
</system.webServer>
Add the header through the global Application_BeginRequest
void Application_BeginRequest(object sender, EventArgs e)
{
this.Response.Headers["X-Content-Type-Options"] = "nosniff";
}
Implement custom HTTP module
public class XContentTypeOptionsModule : IHttpModule
{
#region IHttpModule Members
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.PreSendRequestHeaders += newEventHandler(context_PreSendRequestHeaders);
}
#endregion
void context_PreSendRequestHeaders(object sender, EventArgs e)
{
HttpApplication application = sender as HttpApplication;
if (application == null)
return;
if (application.Response.Headers["X-Content-Type-Options "] != null)
return;
application.Response.Headers.Add("X-Content-Type-Options ", "nosniff");
}
}
You can enable the required header only for specific pages by adding it to individual responses:
this.Response.Headers["X-Content-Type-Options"] = "nosniff";
Title | Details |
---|---|
Component | Web Application |
SDL Phase | Build |
Applicable Technologies | Generic |
Attributes | EnvironmentType - Azure |
References | Removing standard server headers on Windows Azure Web Sites |
Steps | Headers such as Server, X-Powered-By, X-AspNet-Version reveal information about the server and the underlying technologies. It is recommended to suppress these headers thereby preventing fingerprinting the application |
Title | Details |
---|---|
Component | Database |
SDL Phase | Build |
Applicable Technologies | SQL Azure, OnPrem |
Attributes | N/A, SQL Version - V12 |
References | How to configure an Azure SQL Database firewall, Configure a Windows Firewall for Database Engine Access |
Steps | Firewall systems help prevent unauthorized access to computer resources. To access an instance of the SQL Server Database Engine through a firewall, you must configure the firewall on the computer running SQL Server to allow access |
Title | Details |
---|---|
Component | Web API |
SDL Phase | Build |
Applicable Technologies | MVC 5 |
Attributes | N/A |
References | Enabling Cross-Origin Requests in ASP.NET Web API 2, ASP.NET Web API - CORS Support in ASP.NET Web API 2 |
Steps | Browser security prevents a web page from making AJAX requests to another domain. This restriction is called the same-origin policy, and prevents a malicious site from reading sensitive data from another site. However, sometimes it might be required to expose APIs securely which other sites can consume. Cross Origin Resource Sharing (CORS) is a W3C standard that allows a server to relax the same-origin policy. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others. CORS is safer and more flexible than earlier techniques such as JSONP. |
In the App_Start/WebApiConfig.cs, add the following code to the WebApiConfig.Register method
using System.Web.Http;
namespace WebService
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// New code
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
EnableCors attribute can be applied to action methods in a controller as follows:
public class ResourcesController : ApiController
{
[EnableCors("http://localhost:55912", // Origin
null, // Request headers
"GET", // HTTP methods
"bar", // Response headers
SupportsCredentials=true // Allow credentials
)]
public HttpResponseMessage Get(int id)
{
var resp = Request.CreateResponse(HttpStatusCode.NoContent);
resp.Headers.Add("bar", "a bar value");
return resp;
}
[EnableCors("http://localhost:55912", // Origin
"Accept, Origin, Content-Type", // Request headers
"PUT", // HTTP methods
PreflightMaxAge=600 // Preflight cache duration
)]
public HttpResponseMessage Put(Resource data)
{
return Request.CreateResponse(HttpStatusCode.OK, data);
}
[EnableCors("http://localhost:55912", // Origin
"Accept, Origin, Content-Type", // Request headers
"POST", // HTTP methods
PreflightMaxAge=600 // Preflight cache duration
)]
public HttpResponseMessage Post(Resource data)
{
return Request.CreateResponse(HttpStatusCode.OK, data);
}
}
Note that it is critical to ensure that the list of origins in EnableCors attribute is set to a finite and trusted set of origins. Failing to configure this inappropriately (for example, setting the value as '*') will allow malicious sites to trigger cross origin requests to the API without any restrictions, >thereby making the API vulnerable to CSRF attacks. EnableCors can be decorated at controller level.
To disable CORS on a particular method in a class, the DisableCors attribute can be used as shown below:
[EnableCors("https://example.com", "Accept, Origin, Content-Type", "POST")]
public class ResourcesController : ApiController
{
public HttpResponseMessage Put(Resource data)
{
return Request.CreateResponse(HttpStatusCode.OK, data);
}
public HttpResponseMessage Post(Resource data)
{
return Request.CreateResponse(HttpStatusCode.OK, data);
}
// CORS not allowed because of the [DisableCors] attribute
[DisableCors]
public HttpResponseMessage Delete(int id)
{
return Request.CreateResponse(HttpStatusCode.NoContent);
}
}
Title | Details |
---|---|
Component | Web API |
SDL Phase | Build |
Applicable Technologies | MVC 6 |
Attributes | N/A |
References | Enabling Cross-Origin Requests (CORS) in ASP.NET Core 1.0 |
Steps | In ASP.NET Core 1.0, CORS can be enabled either using middleware or using MVC. When using MVC to enable CORS the same CORS services are used, but the CORS middleware is not. |
Approach-1 Enabling CORS with middleware: To enable CORS for the entire application add the CORS middleware to the request pipeline using the UseCors extension method. A cross-origin policy can be specified when adding the CORS middleware using the CorsPolicyBuilder class. There are two ways to do this:
The first is to call UseCors with a lambda. The lambda takes a CorsPolicyBuilder object:
public void Configure(IApplicationBuilder app)
{
app.UseCors(builder =>
builder.WithOrigins("https://example.com")
.WithMethods("GET", "POST", "HEAD")
.WithHeaders("accept", "content-type", "origin", "x-custom-header"));
}
The second is to define one or more named CORS policies, and then select the policy by name at run time.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder.WithOrigins("https://example.com"));
});
}
public void Configure(IApplicationBuilder app)
{
app.UseCors("AllowSpecificOrigin");
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
Approach-2 Enabling CORS in MVC: Developers can alternatively use MVC to apply specific CORS per action, per controller, or globally for all controllers.
Per action: To specify a CORS policy for a specific action add the [EnableCors] attribute to the action. Specify the policy name.
public class HomeController : Controller
{
[EnableCors("AllowSpecificOrigin")]
public IActionResult Index()
{
return View();
}
Per controller:
[EnableCors("AllowSpecificOrigin")]
public class HomeController : Controller
{
Globally:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
});
}
Note that it is critical to ensure that the list of origins in EnableCors attribute is set to a finite and trusted set of origins. Failing to configure this inappropriately (for example, setting the value as '*') will allow malicious sites to trigger cross origin requests to the API without any restrictions, >thereby making the API vulnerable to CSRF attacks.
To disable CORS for a controller or action, use the [DisableCors] attribute.
[DisableCors]
public IActionResult About()
{
return View();
}
Title | Details |
---|---|
Component | Web API |
SDL Phase | Deployment |
Applicable Technologies | Generic |
Attributes | N/A |
References | How To: Encrypt Configuration Sections in ASP.NET 2.0 Using DPAPI, Specifying a Protected Configuration Provider, Using Azure Key Vault to protect application secrets |
Steps | Configuration files such as the Web.config, appsettings.json are often used to hold sensitive information, including user names, passwords, database connection strings, and encryption keys. If you do not protect this information, your application is vulnerable to attackers or malicious users obtaining sensitive information such as account user names and passwords, database names and server names. Based on the deployment type (azure/on-prem), encrypt the sensitive sections of config files using DPAPI or services like Azure Key Vault. |
Title | Details |
---|---|
Component | IoT Device |
SDL Phase | Deployment |
Applicable Technologies | Generic |
Attributes | N/A |
References | N/A |
Steps | Any administrative interfaces that the device or field gateway exposes should be secured using strong credentials. Also, any other exposed interfaces like WiFi, SSH, File shares, FTP should be secured with strong credentials. Default weak passwords should not be used. |
Title | Details |
---|---|
Component | IoT Device |
SDL Phase | Build |
Applicable Technologies | Generic |
Attributes | N/A |
References | Enabling Secure Boot and BitLocker Device Encryption on Windows 10 IoT Core |
Steps | UEFI Secure Boot restricts the system to only allow execution of binaries signed by a specified authority. This feature prevents unknown code from being executed on the platform and potentially weakening the security posture of it. Enable UEFI Secure Boot and restrict the list of certificate authorities that are trusted for signing code. Sign all code that is deployed on the device using one of the trusted authorities. |
Title | Details |
---|---|
Component | IoT Device |
SDL Phase | Build |
Applicable Technologies | Generic |
Attributes | N/A |
References | N/A |
Steps | Windows 10 IoT Core implements a lightweight version of BitLocker Device Encryption, which has a strong dependency on the presence of a TPM on the platform, including the necessary preOS protocol in UEFI that conducts the necessary measurements. These preOS measurements ensure that the OS later has a definitive record of how the OS was launched.Encrypt OS partitions using BitLocker and any other partitions also in case they store any sensitive data. |
Title | Details |
---|---|
Component | IoT Device |
SDL Phase | Deployment |
Applicable Technologies | Generic |
Attributes | N/A |
References | N/A |
Steps | Do not enable or turn off any features or services in the OS that is not required for the functioning of the solution. For example, if the device does not require a UI to be deployed, install Windows IoT Core in headless mode. |
Title | Details |
---|---|
Component | IoT Field Gateway |
SDL Phase | Deployment |
Applicable Technologies | Generic |
Attributes | N/A |
References | N/A |
Steps | Windows 10 IoT Core implements a lightweight version of BitLocker Device Encryption, which has a strong dependency on the presence of a TPM on the platform, including the necessary preOS protocol in UEFI that conducts the necessary measurements. These preOS measurements ensure that the OS later has a definitive record of how the OS was launched.Encrypt OS partitions using BitLocker and any other partitions also in case they store any sensitive data. |
Title | Details |
---|---|
Component | IoT Field Gateway |
SDL Phase | Deployment |
Applicable Technologies | Generic |
Attributes | N/A |
References | N/A |
Steps | Ensure that the default login credentials of the field gateway are changed during installation |
Ensure that the Cloud Gateway implements a process to keep the connected devices firmware up to date
Title | Details |
---|---|
Component | IoT Cloud Gateway |
SDL Phase | Build |
Applicable Technologies | Generic |
Attributes | Gateway choice - Azure IoT Hub |
References | IoT Hub Device Management Overview,Device Update for Azure IoT Hub tutorial using the Raspberry Pi 3 B+ Reference Image. |
Steps | LWM2M is a protocol from the Open Mobile Alliance for IoT Device Management. Azure IoT device management allows to interact with physical devices using device jobs. Ensure that the Cloud Gateway implements a process to routinely keep the device and other configuration data up to date using Azure IoT Hub Device Management. |
Title | Details |
---|---|
Component | Machine Trust Boundary |
SDL Phase | Deployment |
Applicable Technologies | Generic |
Attributes | N/A |
References | N/A |
Steps | Ensure that devices have end-point security controls such as BitLocker for disk-level encryption, anti-virus with updated signatures, host-based firewall, OS upgrades, group policies etc. are configured as per organizational security policies. |
Title | Details |
---|---|
Component | Azure Storage |
SDL Phase | Deployment |
Applicable Technologies | Generic |
Attributes | N/A |
References | Azure Storage security guide - Managing Your Storage Account Keys |
Steps | Key Storage: It is recommended to store the Azure Storage access keys in Azure Key Vault as a secret and have the applications retrieve the key from key vault. This is recommended due to the following reasons:
|
Title | Details |
---|---|
Component | Azure Storage |
SDL Phase | Build |
Applicable Technologies | Generic |
Attributes | N/A |
References | CORS Support for the Azure Storage Services |
Steps | Azure Storage allows you to enable CORS – Cross Origin Resource Sharing. For each storage account, you can specify domains that can access the resources in that storage account. By default, CORS is disabled on all services. You can enable CORS by using the REST API or the storage client library to call one of the methods to set the service policies. |
Title | Details |
---|---|
Component | WCF |
SDL Phase | Build |
Applicable Technologies | .NET Framework 3 |
Attributes | N/A |
References | MSDN, Fortify Kingdom |
Steps | Not placing a limit on the use of system resources could result in resource exhaustion and ultimately a denial of service.
|
The following is an example configuration with throttling enabled:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="Throttled">
<serviceThrottling maxConcurrentCalls="[YOUR SERVICE VALUE]" maxConcurrentSessions="[YOUR SERVICE VALUE]" maxConcurrentInstances="[YOUR SERVICE VALUE]" />
...
</system.serviceModel>
Title | Details |
---|---|
Component | WCF |
SDL Phase | Build |
Applicable Technologies | .NET Framework 3 |
Attributes | N/A |
References | MSDN, Fortify Kingdom |
Steps | Metadata can help attackers learn about the system and plan a form of attack. WCF services can be configured to expose metadata. Metadata gives detailed service description information and should not be broadcast in production environments. The HttpGetEnabled / HttpsGetEnabled properties of the ServiceMetaData class defines whether a service will expose the metadata |
The code below instructs WCF to broadcast a service's metadata
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.HttpGetUrl = new Uri(EndPointAddress);
Host.Description.Behaviors.Add(smb);
Do not broadcast service metadata in a production environment. Set the HttpGetEnabled / HttpsGetEnabled properties of the ServiceMetaData class to false.
The code below instructs WCF to not broadcast a service's metadata.
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = false;
smb.HttpGetUrl = new Uri(EndPointAddress);
Host.Description.Behaviors.Add(smb);