安全框架:配置管理 | 缓解措施Security Frame: Configuration Management | Mitigations
实施内容安全策略 (CSP) 并禁用内联 JavaScriptImplement Content Security Policy (CSP), and disable inline javascript
标题Title | 详细信息Details |
---|---|
组件Component | Web 应用程序Web Application |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 内容安全策略参考、安全功能、内容安全策略简介、是否可以使用 CSP?Content Security Policy Reference, Security features, Introduction to content security policy, Can I use CSP? |
步骤Steps | 内容安全策略 (CSP) 是一种深度防护安全机制,也是一项 W3C 标准,可让 Web 应用程序所有者控制其站点中嵌入的内容。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 以 HTTP 响应标头的形式添加在 Web 服务器上,由浏览器在客户端实施。CSP is added as an HTTP response header on the web server and is enforced on the client side by browsers. 它是基于允许列表的策略 - 网站可以声明一组受信任的域,通过这些域可以加载 JavaScript 之类的活动内容。It is a allowed list-based policy - a website can declare a set of trusted domains from which active content such as JavaScript can be loaded. CSP 提供以下安全优势:CSP provides the following security benefits:
|
示例Example
示例策略:Example policy:
Content-Security-Policy: default-src 'self'; script-src 'self' www.google-analytics.com
此策略只允许从 Web 应用程序的服务器和 google 分析服务器加载脚本。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. 在网站上启用 CSP 后,以下功能会自动禁用以缓解 XSS 攻击。When CSP is enabled on a website, the following features are automatically disabled to mitigate XSS attacks.
示例Example
内联脚本不会执行。Inline scripts will not execute. 下面是内联脚本的示例Following are examples of inline scripts
<script> some Javascript code </script>
Event handling attributes of HTML tags (e.g., <button onclick="function(){}">
javascript:alert(1);
示例Example
不会将字符串作为代码评估。Strings will not be evaluated as code.
Example: var str="alert(1)"; eval(str);
启用浏览器的 XSS 筛选器Enable browser's XSS filter
标题Title | 详细信息Details |
---|---|
组件Component | Web 应用程序Web Application |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | XSS 保护筛选器XSS Protection Filter |
步骤Steps | X-XSS-Protection 响应标头配置控制浏览器的跨站点脚本筛选器。X-XSS-Protection response header configuration controls the browser's cross site script filter. 此响应标头可使用以下值:This response header can have following values:
这是一个 Chromium 函数,它利用 CSP 违规报告将详细信息发送到所选的 URI。This is a Chromium function utilizing CSP violation reports to send details to a URI of your choice. 最后 2 个选项被视为安全值。The last 2 options are considered safe values. |
ASP.NET 应用程序在部署之前必须禁用跟踪和调试ASP.NET applications must disable tracing and debugging prior to deployment
标题Title | 详细信息Details |
---|---|
组件Component | Web 应用程序Web Application |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | ASP.NET 调试概览、ASP.NET 跟踪概览、如何:启用 ASP.NET 应用程序跟踪、如何:启用 ASP.NET 应用程序调试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. |
仅从受信任源访问第三方 JavaScriptAccess third-party javascripts from trusted sources only
标题Title | 详细信息Details |
---|---|
组件Component | Web 应用程序Web Application |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 空值N/A |
步骤Steps | 只应从受信任源引用第三方 JavaScript。third-party JavaScripts should be referenced only from trusted sources. 引用终结点应始终在 TLS 连接中。The reference endpoints should always be on TLS. |
确保在经过身份验证的 ASP.NET 页面中整合 UI 伪装或点击劫持防御机制Ensure that authenticated ASP.NET pages incorporate UI Redressing or click-jacking defenses
标题Title | 详细信息Details |
---|---|
组件Component | Web 应用程序Web Application |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | OWASP 点击劫持防御速查表、IE 内部 - 使用 X-Frame-Options 阻击点击劫持OWASP click-jacking Defense Cheat Sheet, IE Internals - Combating click-jacking With X-Frame-Options |
步骤Steps | 点击劫持也称“UI 伪装攻击”,是指攻击者使用多个透明或不透明的层,在用户想要点击顶层页面时,诱使用户点击另一个页面上的按钮或链接。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. 这种分层是通过编写使用 iframe 的恶意页面,加载受害者的页面来实现的。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. 若要阻止点击劫持攻击,请设置适当的 X-Frame-Options HTTP 响应标头,指示浏览器不要允许来自其他域的框架设计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 |
示例Example
可以通过 IIS web.config 设置 X-FRAME-OPTIONS 标头。永远不应设计框架的站点 Web.config 代码片段: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>
示例Example
只应由同一域中的页面设计框架的站点 Web.config 代码: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>
确保已在 ASP.NET Web 应用程序中启用 CORS 的情况下只允许受信任的来源Ensure that only trusted origins are allowed if CORS is enabled on ASP.NET Web Applications
标题Title | 详细信息Details |
---|---|
组件Component | Web 应用程序Web Application |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | Web 窗体、MVC5Web Forms, MVC5 |
属性Attributes | 空值N/A |
参考References | 空值N/A |
步骤Steps | 浏览器安全性将阻止网页向另一个域发出 AJAX 请求。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. 但是,有时可能需要安全公开可由其他站点使用的 API。However, sometimes it might be required to expose APIs securely which other sites can consume. 跨域资源共享 (CORS) 是一项 W3C 标准,可让服务器放宽同域策略。Cross Origin Resource Sharing (CORS) is a W3C standard that allows a server to relax the same-origin policy. 使用 CORS,服务器可以显式允许某些跨域请求,同时拒绝另一些跨域请求。Using CORS, a server can explicitly allow some cross-origin requests while rejecting others. 与 JSONP 等早期技术相比,CORS 更安全且更灵活。CORS is safer and more flexible than earlier techniques such as JSONP. 从核心上讲,启用 CORS 就相当于在 Web 应用程序中添加了一些 HTTP 响应标头 (Access-Control-*),这可以通过多种方式来实现。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. |
示例Example
如果可以访问 Web.config,则可通过以下代码添加 CORS: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>
示例Example
如果无法访问 Web.config,则可通过添加以下 CSharp 代码来配置 CORS:If access to web.config is not available, then CORS can be configured by adding the following CSharp code:
HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", "https://example.com")
请注意,务必将“Access-Control-Allow-Origin”属性中的来源列表设置为一组有限的受信任来源。Please 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. 不当地配置此列表(例如,将值设置为“*”)会使得恶意站点能够毫无限制地向 Web 应用程序触发跨域请求,从而使应用程序易于遭受 CSRF 攻击。Failing to configure this inappropriately (e.g., 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.
在 ASP.NET 页面中启用 ValidateRequest 属性Enable ValidateRequest attribute on ASP.NET Pages
标题Title | 详细信息Details |
---|---|
组件Component | Web 应用程序Web Application |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | Web 窗体、MVC5Web Forms, MVC5 |
属性Attributes | 空值N/A |
参考References | 请求验证 - 阻止脚本攻击Request Validation - Preventing Script Attacks |
步骤Steps | 请求验证是 ASP.NET 版本 1.1 中的一项功能,可阻止服务器接受包含未编码 HTML 的内容。Request validation, a feature of ASP.NET since version 1.1, prevents the server from accepting content containing un-encoded HTML. 此功能旨在帮助阻止某些脚本注入攻击,避免在不知情的情况下将客户端脚本代码或 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. 尽管如此,我们仍旧强烈建议验证所有输入数据和 HTML,并在适当的情况下将其编码。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. 如果出现匹配项,ASP.NET 将引发 |
示例Example
但是,可在页面级别禁用此功能: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>
请注意,MVC6 管道不支持且不包括请求验证功能。Please note that Request Validation feature is not supported, and is not part of MVC6 pipeline.
使用本地托管的最新版本的 JavaScript 库Use locally-hosted latest versions of JavaScript libraries
标题Title | 详细信息Details |
---|---|
组件Component | Web 应用程序Web Application |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 空值N/A |
步骤Steps | 使用 JQuery 等标准 JavaScript 库的开发人员必须使用不包含已知安全漏洞的、批准的通用 JavaScript 库版本。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:
切勿从外部站点(例如公共 CDN)加载任何 JavaScript 库Never load any JavaScript library from external sites such as public CDNs |
禁用自动 MIME 探查Disable automatic MIME sniffing
标题Title | 详细信息Details |
---|---|
组件Component | Web 应用程序Web Application |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | IE8 安全性第五部分:全面保护、MIME 类型IE8 Security Part V: Comprehensive Protection, MIME type |
步骤Steps | X-Content-Type-Options 标头是一个 HTTP 标头,可让开发人员指定不应该对其内容使用 MIME 探查。The X-Content-Type-Options header is an HTTP header that allows developers to specify that their content should not be MIME-sniffed. 此标头旨在缓解 MIME 探查攻击。This header is designed to mitigate MIME-Sniffing attacks. 对于可能包含用户可控内容的每个页面,必须使用 HTTP 标头 X-Content-Type-Options:nosniff。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 |
示例Example
如果应用程序由 Internet Information Services (IIS) 7 及更高版本托管,请在 web.config 文件中添加该标头。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>
示例Example
通过全局 Application_BeginRequest 添加该标头Add the header through the global Application_BeginRequest
void Application_BeginRequest(object sender, EventArgs e)
{
this.Response.Headers["X-Content-Type-Options"] = "nosniff";
}
示例Example
实现自定义的 HTTP 模块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");
}
}
示例Example
对于特定的页面,只能通过将所需的标头添加到单个响应来启用该标头:You can enable the required header only for specific pages by adding it to individual responses:
this.Response.Headers["X-Content-Type-Options"] = "nosniff";
在 Windows Azure 网站中删除标准服务器标头避免留下指纹Remove standard server headers on Windows Azure Web Sites to avoid fingerprinting
标题Title | 详细信息Details |
---|---|
组件Component | Web 应用程序Web Application |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | EnvironmentType - AzureEnvironmentType - Azure |
参考References | 在 Windows Azure 网站中删除标准服务器标头Removing standard server headers on Windows Azure Web Sites |
步骤Steps | Server、X-Powered-By、X-AspNet-Version 等标头会透露有关服务器和底层技术的信息。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 |
为数据库引擎访问配置 Windows 防火墙Configure a Windows Firewall for Database Engine Access
标题Title | 详细信息Details |
---|---|
组件Component | 数据库Database |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | SQL Azure、OnPremSQL Azure, OnPrem |
属性Attributes | 不适用,SQL 版本 - V12N/A, SQL Version - V12 |
参考References | 如何配置 Azure SQL 数据库防火墙、为数据库引擎访问配置 Windows 防火墙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. 要通过防火墙访问 SQL Server 数据库引擎的实例,必须将运行 SQL Server 的计算机上的防火墙配置为允许这种访问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 |
确保已在 ASP.NET Web API 中启用 CORS 的情况下只允许受信任的来源Ensure that only trusted origins are allowed if CORS is enabled on ASP.NET Web API
标题Title | 详细信息Details |
---|---|
组件Component | Web APIWeb API |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | MVC 5MVC 5 |
属性Attributes | 空值N/A |
参考References | 在 ASP.NET Web API 2 中启用跨域请求、ASP.NET Web API - ASP.NET Web API 2 中的 CORS 支持Enabling Cross-Origin Requests in ASP.NET Web API 2, ASP.NET Web API - CORS Support in ASP.NET Web API 2 |
步骤Steps | 浏览器安全性将阻止网页向另一个域发出 AJAX 请求。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. 但是,有时可能需要安全公开可由其他站点使用的 API。However, sometimes it might be required to expose APIs securely which other sites can consume. 跨域资源共享 (CORS) 是一项 W3C 标准,可让服务器放宽同域策略。Cross Origin Resource Sharing (CORS) is a W3C standard that allows a server to relax the same-origin policy. 使用 CORS,服务器可以显式允许某些跨域请求,同时拒绝另一些跨域请求。Using CORS, a server can explicitly allow some cross-origin requests while rejecting others. 与 JSONP 等早期技术相比,CORS 更安全且更灵活。CORS is safer and more flexible than earlier techniques such as JSONP. |
示例Example
在 App_Start/WebApiConfig.cs 中,将以下代码添加到 WebApiConfig.Register 方法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 }
);
}
}
}
示例Example
可按如下所示,将 EnableCors 特性应用到控制器中的操作方法: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);
}
}
请注意,务必将 EnableCors 特性中的来源列表设置为一组有限的受信任来源。Please 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. 不当地配置此列表(例如,将值设置为“*”)会使得恶意站点能够毫无限制地向 API 触发跨域请求,从而使 API 易于遭受 CSRF 攻击。Failing to configure this inappropriately (e.g., 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。EnableCors can be decorated at controller level.
示例Example
若要对类中的特定方法禁用 CORS,可按如下所示使用 DisableCors 特性: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 APIWeb API |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | MVC 6MVC 6 |
属性Attributes | 空值N/A |
参考References | 在 ASP.NET Core 1.0 中启用跨域请求 (CORS)Enabling Cross-Origin Requests (CORS) in ASP.NET Core 1.0 |
步骤Steps | 在 ASP.NET Core 1.0 中,可以使用中间件或 MVC 启用 CORS。In ASP.NET Core 1.0, CORS can be enabled either using middleware or using MVC. 使用 MVC 启用 CORS 时,将使用相同的 CORS 服务,但使用 CORS 中间件启用 CORS 时则不是这样。When using MVC to enable CORS the same CORS services are used, but the CORS middleware is not. |
方式 1 使用中间件启用 CORS:要为整个应用程序启用 CORS,请使用 UseCors 扩展方法将 CORS 中间件添加到请求管道。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. 使用 CorsPolicyBuilder 类添加 CORS 中间件时,可以指定跨域策略。A cross-origin policy can be specified when adding the CORS middleware using the CorsPolicyBuilder class. 可通过两种方式实现此目的:There are two ways to do this:
示例Example
第一种方式是使用 lambda 调用 UseCors。The first is to call UseCors with a lambda. lambda 使用一个 CorsPolicyBuilder 对象: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"));
}
示例Example
第二种方式是定义一个或多个命名的 CORS 策略,并在运行时按名称选择策略。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!");
});
}
方式 2 在 MVC 中启用 CORS:开发人员也可以使用 MVC 按操作、按控制器或者针对所有控制器全局应用特定的 CORS。Approach-2 Enabling CORS in MVC: Developers can alternatively use MVC to apply specific CORS per action, per controller, or globally for all controllers.
示例Example
按操作:要为特定的操作指定 CORS 策略,请将 [EnableCors] 特性添加到该操作。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();
}
示例Example
按控制器:Per controller:
[EnableCors("AllowSpecificOrigin")]
public class HomeController : Controller
{
示例Example
全局:Globally:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
});
}
请注意,务必将 EnableCors 特性中的来源列表设置为一组有限的受信任来源。Please 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. 不当地配置此列表(例如,将值设置为“*”)会使得恶意站点能够毫无限制地向 API 触发跨域请求,从而使 API 易于遭受 CSRF 攻击。Failing to configure this inappropriately (e.g., 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.
示例Example
若要为控制器或操作禁用 CORS,请使用 [DisableCors] 特性。To disable CORS for a controller or action, use the [DisableCors] attribute.
[DisableCors]
public IActionResult About()
{
return View();
}
加密 Web API 配置文件中包含敏感数据的部分Encrypt sections of Web API's configuration files that contain sensitive data
标题Title | 详细信息Details |
---|---|
组件Component | Web APIWeb API |
SDL 阶段SDL Phase | 部署Deployment |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 如何:使用 DPAPI 加密 ASP.NET 2.0 中的配置部分、指定受保护的配置提供程序、使用 Azure Key Vault 保护应用程序机密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 | Web.config、appsettings.json 等配置文件通常用于保存敏感信息,包括用户名、密码、数据库连接字符串和加密密钥。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. 请根据部署类型 (azure/on-prem),使用 DPAPI 或 Azure Key Vault 等服务来加密配置文件的敏感部分。Based on the deployment type (azure/on-prem), encrypt the sensitive sections of config files using DPAPI or services like Azure Key Vault. |
确保使用强凭据保护所有管理界面Ensure that all admin interfaces are secured with strong credentials
标题Title | 详细信息Details |
---|---|
组件Component | IoT 设备IoT Device |
SDL 阶段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. 此外,应使用强凭据保护 WiFi、SSH、文件共享、FTP 等其他任何公开的接口。Also, any other exposed interfaces like WiFi, SSH, File shares, FTP should be secured with strong credentials. 不应使用默认的弱密码。Default weak passwords should not be used. |
确保未知的代码无法在设备上执行Ensure that unknown code cannot execute on devices
标题Title | 详细信息Details |
---|---|
组件Component | IoT 设备IoT Device |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 在 Windows 10 IoT Core 上启用安全启动和 bit-locker 设备加密Enabling Secure Boot and bit-locker Device Encryption on Windows 10 IoT Core |
步骤Steps | UEFI 安全启动会将系统限制为只允许执行指定的颁发机构签名的二进制文件。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. 启用 UEFI 安全启动,并限制受信任的、可为代码签名的证书颁发机构列表。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. |
使用 bit-locker 加密 IoT 设备的 OS 和其他分区Encrypt OS and additional partitions of IoT Device with bit-locker
标题Title | 详细信息Details |
---|---|
组件Component | IoT 设备IoT Device |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 空值N/A |
步骤Steps | Windows 10 IoT Core 实现轻量版本的 bit-locker 设备加密,该版本在很大程度上依赖于平台上的 TPM,包括需要在 UEFI 中安装必要的 preOS 协议用于执行必要的度量。Windows 10 IoT Core implements a lightweight version of bit-locker 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. 这些 preOS 度量可确保 OS 今后拥有一份有关 OS 启动方式的明确记录。使用 bit-locker 加密 OS 分区,如果其他任何分区中存储了任何敏感数据,也应该加密这些分区。These preOS measurements ensure that the OS later has a definitive record of how the OS was launched.Encrypt OS partitions using bit-locker and any additional partitions also in case they store any sensitive data. |
确保只在设备上启用少量的服务/功能Ensure that only the minimum services/features are enabled on devices
标题Title | 详细信息Details |
---|---|
组件Component | IoT 设备IoT Device |
SDL 阶段SDL Phase | 部署Deployment |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 空值N/A |
步骤Steps | 不要在 OS 中启用或者请关闭运行解决方案所不需要的任何功能或服务。Do not enable or turn off any features or services in the OS that is not required for the functioning of the solution. 例如,如果设备不需要部署 UI,请在无外设模式下安装 Windows IoT Core。For e.g. if the device does not require a UI to be deployed, install Windows IoT Core in headless mode. |
使用 bit-locker 加密 IoT 现场网关的 OS 和其他分区Encrypt OS and additional partitions of IoT Field Gateway with bit-locker
标题Title | 详细信息Details |
---|---|
组件Component | IoT 现场网关IoT Field Gateway |
SDL 阶段SDL Phase | 部署Deployment |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 空值N/A |
步骤Steps | Windows 10 IoT Core 实现轻量版本的 bit-locker 设备加密,该版本在很大程度上依赖于平台上的 TPM,包括需要在 UEFI 中安装必要的 preOS 协议用于执行必要的度量。Windows 10 IoT Core implements a lightweight version of bit-locker 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. 这些 preOS 度量可确保 OS 今后拥有一份有关 OS 启动方式的明确记录。使用 bit-locker 加密 OS 分区,如果其他任何分区中存储了任何敏感数据,也应该加密这些分区。These preOS measurements ensure that the OS later has a definitive record of how the OS was launched.Encrypt OS partitions using bit-locker and any additional partitions also in case they store any sensitive data. |
确保在安装期间更改现场网关的默认登录凭据Ensure that the default login credentials of the field gateway are changed during installation
标题Title | 详细信息Details |
---|---|
组件Component | IoT 现场网关IoT Field Gateway |
SDL 阶段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 云网关IoT Cloud Gateway |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 网关选项 - Azure IoT 中心Gateway choice - Azure IoT Hub |
参考References | IoT 中心设备管理概述、如何更新设备固件IoT Hub Device Management Overview, How to update Device Firmware |
步骤Steps | LWM2M 是开放移动联盟为 IoT 设备管理提供的协议。LWM2M is a protocol from the Open Mobile Alliance for IoT Device Management. 借助 Azure IoT 设备管理可以使用设备作业来与物理设备交互。Azure IoT device management allows to interact with physical devices using device jobs. 请确保云网关实施相应的过程,定期使用 Azure IoT 中心设备管理将设备和其他配置数据保持最新状态。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. |
确保根据组织的策略在设备上配置终结点安全控制Ensure that devices have end-point security controls configured as per organizational policies
标题Title | 详细信息Details |
---|---|
组件Component | 计算机信任边界Machine Trust Boundary |
SDL 阶段SDL Phase | 部署Deployment |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 空值N/A |
步骤Steps | 确保根据组织的安全策略,在设备中配置终结点安全控制机制,例如,用于磁盘级加密的 bitlocker、包含更新病毒特征的防病毒软件、基于主机的防火墙,OS 升级、组策略等。Ensure that devices have end-point security controls such as bit-locker for disk-level encryption, anti-virus with updated signatures, host based firewall, OS upgrades, group policies etc. are configured as per organizational security policies. |
确保对 Azure 存储访问密钥进行安全管理Ensure secure management of Azure storage access keys
标题Title | 详细信息Details |
---|---|
组件Component | Azure 存储Azure Storage |
SDL 阶段SDL Phase | 部署Deployment |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | Azure 存储安全指南 - 管理存储帐户密钥Azure Storage security guide - Managing Your Storage Account Keys |
步骤Steps | 密钥存储:建议将 Azure 存储访问密钥以机密的形式存储在 Azure Key Vault 中,并让应用程序从 Key Vault 中检索密钥。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:
|
确保已在 Azure 存储中启用 CORS 的情况下只允许受信任的来源Ensure that only trusted origins are allowed if CORS is enabled on Azure storage
标题Title | 详细信息Details |
---|---|
组件Component | Azure 存储Azure Storage |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | Azure 存储服务的 CORS 支持CORS Support for the Azure Storage Services |
步骤Steps | Azure 存储允许启用 CORS – 跨域资源共享。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. 默认情况下,对所有服务禁用了 CORS。By default, CORS is disabled on all services. 可以使用 REST API 或存储客户端库调用某个方法来设置服务策略,以启用 CORS。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. |
启用 WCF 的服务限制功能Enable WCF's service throttling feature
标题Title | 详细信息Details |
---|---|
组件Component | WCFWCF |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | .NET Framework 3.NET Framework 3 |
属性Attributes | 空值N/A |
参考References | MSDN、巩固王国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.
|
示例Example
下面是启用了限制的示例配置: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>
WCF - 通过元数据透露信息WCF-Information disclosure through metadata
标题Title | 详细信息Details |
---|---|
组件Component | WCFWCF |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | .NET Framework 3.NET Framework 3 |
属性Attributes | 空值N/A |
参考References | MSDN、巩固王国MSDN, Fortify Kingdom |
步骤Steps | 元数据可帮助攻击者了解系统并规划攻击形式。Metadata can help attackers learn about the system and plan a form of attack. WCF 服务可能会配置为公开元数据。WCF services can be configured to expose metadata. 元数据提供详细的服务说明信息,不应在生产环境中广播。Metadata gives detailed service description information and should not be broadcast in production environments. ServiceMetaData 类的 HttpGetEnabled / HttpsGetEnabled 属性定义服务是否要公开元数据The HttpGetEnabled / HttpsGetEnabled properties of the ServiceMetaData class defines whether a service will expose the metadata |
示例Example
以下代码指示 WCF 广播服务的元数据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. 将 ServiceMetaData 类的 HttpGetEnabled/HttpsGetEnabled 属性设置为 false。Set the HttpGetEnabled / HttpsGetEnabled properties of the ServiceMetaData class to false.
示例Example
以下代码指示 WCF 不要广播服务的元数据。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);