安全框架:身份验证 | 缓解措施Security Frame: Authentication | Mitigations
考虑使用标准身份验证机制向 Web 应用程序进行身份验证Consider using a standard authentication mechanism to authenticate to Web Application
标题Title | 详细信息Details |
---|---|
组件Component | Web 应用程序Web Application |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 空值N/A |
详细信息Details | 身份验证是某个实体证明其身份的过程,这通常是通过用户名和密码等凭据完成的。Authentication is the process where an entity proves its identity, typically through credentials, such as a user name and password. 可以考虑使用多种身份验证协议。There are multiple authentication protocols available which may be considered. 下面列出了其中一些协议:Some of them are listed below:
考虑使用标准身份验证机制来识别源进程Consider using a standard authentication mechanism to identify the source process |
应用程序必须安全处理失败的身份验证方案Applications must handle failed authentication scenarios securely
标题Title | 详细信息Details |
---|---|
组件Component | Web 应用程序Web Application |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 空值N/A |
详细信息Details | 显式执行用户身份验证的应用程序必须安全处理失败的身份验证方案。身份验证机制必须:Applications that explicitly authenticate users must handle failed authentication scenarios securely.The authentication mechanism must:
测试:Test for:
|
启用升级或自适应身份验证Enable step up or adaptive authentication
标题Title | 详细信息Details |
---|---|
组件Component | Web 应用程序Web Application |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 空值N/A |
详细信息Details | 验证应用程序是否有附加的授权(例如,通过多重身份验证(在短信中发送 OTP,等等)执行升级或自适应的身份验证,或者提示重新身份验证),以便在向用户授予对敏感信息的访问权限之前向其提出质询。Verify the application has additional authorization (such as step up or adaptive authentication, via multi-factor authentication such as sending OTP in SMS, email etc. or prompting for re-authentication) so the user is challenged before being granted access to sensitive information. 对帐户或操作进行重大更改时,也可以应用此规则This rule also applies for making critical changes to an account or action 这也意味着,必须以适当的方式实施身份验证的调适,以便应用程序能够正确实施区分上下文的授权,阻止通过参数篡改等方式执行未经授权的操作This also means that the adaptation of authentication has to be implemented in such a manner that the application correctly enforces context-sensitive authorization so as to not allow unauthorized manipulation by means of in example, parameter tampering |
确保适当锁定管理界面Ensure that administrative interfaces are appropriately locked down
标题Title | 详细信息Details |
---|---|
组件Component | Web 应用程序Web Application |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 空值N/A |
详细信息Details | 第一种解决方案是仅授予从某个源 IP 范围到管理界面的访问权限。The first solution is to grant access only from a certain source IP range to the administrative interface. 如果该解决方案不可行,我们始终建议针对管理界面的登录实施升级或自适应的身份验证If that solution would not be possible than it is always recommended to enforce a step-up or adaptive authentication for logging in into the administrative interface |
安全实施忘记密码功能Implement forgot password functionalities securely
标题Title | 详细信息Details |
---|---|
组件Component | Web 应用程序Web Application |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 空值N/A |
详细信息Details | 首先,验证“忘记密码”和其他恢复路径是否发送包含限时激活令牌而不是密码本身的链接。The first thing is to verify that forgot password and other recovery paths send a link including a time-limited activation token rather than the password itself. 在发送链接之前,还可能需要实施基于软令牌(例如 SMS 令牌、本机移动应用程序等)的其他身份验证。Additional authentication based on soft-tokens (e.g. SMS token, native mobile applications, etc.) can be required as well before the link is sent over. 第二,在获取新密码的过程正在进行时,不应锁定用户帐户。Second, you should not lock out the users account whilst the process of getting a new password is in progress. 否则,每当攻击者决定使用自动攻击来有意锁定用户时,可能会导致拒绝服务攻击。This could lead to a Denial of service attack whenever an attacker decides to intentionally lock out the users with an automated attack. 第三,在新密码请求正在设置时,显示的消息应该普通化,防止用户名枚举。Third, whenever the new password request was set in progress, the message you display should be generalized in order to prevent username enumeration. 第四,始终禁止使用旧密码并实施强密码策略。Fourth, always disallow the use of old passwords and implement a strong password policy. |
确保实施密码和帐户策略Ensure that password and account policy are implemented
标题Title | 详细信息Details |
---|---|
组件Component | Web 应用程序Web Application |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 空值N/A |
详细信息Details | 应该实施与组织策略和最佳做法相符的密码与帐户策略。Password and account policy in compliance with organizational policy and best practices should be implemented. 为了防范暴力破解和基于字典的猜测:必须实现强密码策略,确保用户创建复杂密码(例如,最小长度为 12 个字符,必须包含字母数字和特殊字符)。To defend against brute-force and dictionary based guessing: Strong password policy must be implemented to ensure that users create complex password (e.g., 12 characters minimum length, alphanumeric and special characters). 可按以下方式实施帐户锁定策略:Account lockout policies may be implemented in the following manner:
为了防范针对默认与可预测帐户的攻击,请验证所有密钥和密码是否可替换,并且是否是在安装后生成或替换的。To defend against attacks on default and predictable accounts, verify that all keys and passwords are replaceable, and are generated or replaced after installation time. 如果应用程序必须自动生成密码,请确保生成的密码是随机的并具有高熵。If the application has to auto-generate passwords, ensure that the generated passwords are random and have high entropy. |
实施控制来防止用户名枚举Implement controls to prevent username enumeration
标题Title | 详细信息Details |
---|---|
组件Component | Web 应用程序Web Application |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 空值N/A |
步骤Steps | 所有错误消息应该普通化,以防止用户名枚举。All error messages should be generalized in order to prevent username enumeration. 此外,在注册页等功能中,有时无法避免信息泄露。Also sometimes you cannot avoid information leaking in functionalities such as a registration page. 在这种情况下,需要使用 CAPTCHA 等频率限制方法来防止攻击者的自动攻击。Here you need to use rate-limiting methods like CAPTCHA to prevent an automated attack by an attacker. |
尽可能使用 Windows 身份验证连接到 SQL ServerWhen possible, use Windows Authentication for connecting to SQL Server
标题Title | 详细信息Details |
---|---|
组件Component | 数据库Database |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | OnPremOnPrem |
属性Attributes | SQL 版本 - 所有SQL Version - All |
参考References | SQL Server - 选择身份验证模式SQL Server - Choose an Authentication Mode |
步骤Steps | Windows 身份验证使用 Kerberos 安全协议,提供有关强密码复杂性验证的密码策略强制,还提供帐户锁定支持,并且支持密码过期。Windows Authentication uses Kerberos security protocol, provides password policy enforcement with regard to complexity validation for strong passwords, provides support for account lockout, and supports password expiration. |
尽可能使用 Azure Active Directory 身份验证连接到 SQL 数据库When possible use Azure Active Directory Authentication for Connecting to SQL Database
标题Title | 详细信息Details |
---|---|
组件Component | 数据库Database |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | SQL AzureSQL Azure |
属性Attributes | SQL 版本 - V12SQL Version - V12 |
参考References | 使用 Azure Active Directory 身份验证连接到 SQL 数据库Connecting to SQL Database By Using Azure Active Directory Authentication |
步骤Steps | 最低版本: 需要安装 Azure SQL 数据库 V12 才能允许 Azure SQL 数据库针对 Microsoft 目录使用 AAD 身份验证Minimum version: Azure SQL Database V12 required to allow Azure SQL Database to use AAD Authentication against the Microsoft Directory |
使用 SQL 身份验证模式时,确保对 SQL Server 实施帐户和密码策略When SQL authentication mode is used, ensure that account and password policy are enforced on SQL server
标题Title | 详细信息Details |
---|---|
组件Component | 数据库Database |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | SQL Server 密码策略SQL Server password policy |
步骤Steps | 使用 SQL Server 身份验证时,登录名是在不基于 Windows 用户帐户的 SQL Server 中创建的。When using SQL Server Authentication, logins are created in SQL Server that are not based on Windows user accounts. 用户名和密码是使用 SQL Server 创建的,存储在 SQL Server 中。Both the user name and the password are created by using SQL Server and stored in SQL Server. SQL Server 可以使用 Windows 密码策略机制。SQL Server can use Windows password policy mechanisms. 对于在 SQL Server 中使用的密码,它可以应用 Windows 中所用的相同复杂性与过期策略。It can apply the same complexity and expiration policies used in Windows to passwords used inside SQL Server. |
不要在包含的数据库中使用 SQL 身份验证Do not use SQL Authentication in contained databases
标题Title | 详细信息Details |
---|---|
组件Component | 数据库Database |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | OnPrem、SQL AzureOnPrem, SQL Azure |
属性Attributes | SQL 版本 - MSSQL2012,SQL 版本 - V12SQL Version - MSSQL2012, SQL Version - V12 |
参考References | 针对包含的数据库的安全最佳做法Security Best Practices with Contained Databases |
步骤Steps | 缺少强制密码策略可能会增大在包含的数据库中建立弱凭据的可能性。The absence of an enforced password policy may increase the likelihood of a weak credential being established in a contained database. 利用 Windows 身份验证Leverage Windows Authentication. |
结合 SaS 令牌使用每个设备的身份验证凭据Use per device authentication credentials using SaS tokens
标题Title | 详细信息Details |
---|---|
组件Component | Azure 事件中心Azure Event Hub |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 事件中心身份验证和安全模型概述Event Hubs authentication and security model overview |
步骤Steps | 事件中心安全模型基于共享访问签名 (SAS) 令牌与事件发布者的组合。The Event Hubs security model is based on a combination of Shared Access Signature (SAS) tokens and event publishers. 发布者名称表示接收令牌的 DeviceID。The publisher name represents the DeviceID that receives the token. 它可以帮助将生成的令牌与相应的设备相关联。This would help associate the tokens generated with the respective devices. 所有消息在服务端标记为发起方,用于检测有效负载中原点欺骗的企图。All messages are tagged with originator on service side allowing detection of in-payload origin spoofing attempts. 对设备进行身份验证时,将生成一个对应于唯一发布者的基于设备的 SaS 令牌。When authenticating devices, generate a per device SaS token scoped to a unique publisher. |
为 Azure 管理员启用 Azure AD 多重身份验证Enable Azure AD Multi-Factor Authentication for Azure Administrators
标题Title | 详细信息Details |
---|---|
组件Component | Azure 信任边界Azure Trust Boundary |
SDL 阶段SDL Phase | 部署Deployment |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 什么是 Azure AD 多重身份验证?What is Azure AD Multi-Factor Authentication? |
步骤Steps | 多重身份验证 (MFA) 是要求使用多种验证方法的身份验证方法,为用户登录和事务额外提供一层重要的安全保障。Multi-factor authentication (MFA) is a method of authentication that requires more than one verification method and adds a critical second layer of security to user sign-ins and transactions. 它的工作原理是需要以下两种或多种验证方法:It works by requiring any two or more of the following verification methods:
|
限制对 Service Fabric 群集的匿名访问Restrict anonymous access to Service Fabric Cluster
标题Title | 详细信息Details |
---|---|
组件Component | Service Fabric 信任边界Service Fabric Trust Boundary |
SDL 阶段SDL Phase | 部署Deployment |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 环境 - AzureEnvironment - Azure |
参考References | Service Fabric 群集安全方案Service Fabric cluster security scenarios |
步骤Steps | 始终都应该保护群集,防止未经授权的用户连接到群集,特别是群集上正在运行生产工作负荷时。Clusters should always be secured to prevent unauthorized users from connecting to your cluster, especially when it has production workloads running on it. 创建 Service Fabric 群集时,请确保安全模式设置为“安全”,并配置所需的 X.509 服务器证书。While creating a service fabric cluster, ensure that the security mode is set to "secure" and configure the required X.509 server certificate. 如果创建“不安全”的群集,当这种群集在公共 Internet 上公开管理终结点时,任何匿名用户都可与它建立连接。Creating an "insecure" cluster will allow any anonymous user to connect to it if it exposes management endpoints to the public Internet. |
确保 Service Fabric 的客户端到节点证书不同于节点到节点证书Ensure that Service Fabric client-to-node certificate is different from node-to-node certificate
标题Title | 详细信息Details |
---|---|
组件Component | Service Fabric 信任边界Service Fabric Trust Boundary |
SDL 阶段SDL Phase | 部署Deployment |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 环境 - Azure,环境 - 独立Environment - Azure, Environment - Stand alone |
参考References | Service Fabric 客户端到节点的证书安全性、使用客户端证书连接到安全群集Service Fabric Client-to-node certificate security, Connect to a secure cluster using client certificate |
步骤Steps | 客户端到节点的证书安全性通过指定管理员客户端证书和/或用户客户端证书在使用 Azure 门户、Resource Manager 模板或独立的 JSON 模板创建群集时配置。Client-to-node certificate security is configured while creating the cluster either through the Azure portal, Resource Manager templates or a standalone JSON template by specifying an admin client certificate and/or a user client certificate. 指定的管理员客户端证书和用户客户端证书应该不同于为节点到节点安全性指定的主证书和辅助证书。The admin client and user client certificates you specify should be different than the primary and secondary certificates you specify for Node-to-node security. |
使用 AAD 向 Service Fabric 群集进行客户端身份验证Use AAD to authenticate clients to service fabric clusters
标题Title | 详细信息Details |
---|---|
组件Component | Service Fabric 信任边界Service Fabric Trust Boundary |
SDL 阶段SDL Phase | 部署Deployment |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 环境 - AzureEnvironment - Azure |
参考References | 群集安全方案 - 安全建议Cluster security scenarios - Security Recommendations |
步骤Steps | 在 Azure 上运行的群集除了使用客户端证书以外,还可使用 Azure Active Directory (AAD) 来保护对管理终结点的访问。Clusters running on Azure can also secure access to the management endpoints using Azure Active Directory (AAD), apart from client certificates. 对于 Azure 群集,建议针对节点到节点安全性,使用 AAD 安全性验证客户端和证书。For Azure clusters, it is recommended that you use AAD security to authenticate clients and certificates for node-to-node security. |
确保从批准的证书颁发机构 (CA) 获取 Service Fabric 证书Ensure that service fabric certificates are obtained from an approved Certificate Authority (CA)
标题Title | 详细信息Details |
---|---|
组件Component | Service Fabric 信任边界Service Fabric Trust Boundary |
SDL 阶段SDL Phase | 部署Deployment |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 环境 - AzureEnvironment - Azure |
参考References | X.509 证书和 Service FabricX.509 certificates and Service Fabric |
步骤Steps | Service Fabric 使用 X.509 服务器证书对节点和客户端进行身份验证。Service Fabric uses X.509 server certificates for authenticating nodes and clients. 在 Service Fabric 中使用证书时,需考虑一些重要事项:Some important things to consider while using certificates in service fabrics:
|
使用标识服务器支持的标准身份验证方案Use standard authentication scenarios supported by Identity Server
标题Title | 详细信息Details |
---|---|
组件Component | 标识服务器Identity Server |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | IdentityServer3 - 大图IdentityServer3 - The Big Picture |
步骤Steps | 下面是标识服务器支持的典型交互:Below are the typical interactions supported by Identity Server:
|
使用可缩放的替代方案覆盖默认的标识服务器令牌缓存Override the default Identity Server token cache with a scalable alternative
标题Title | 详细信息Details |
---|---|
组件Component | 标识服务器Identity Server |
SDL 阶段SDL Phase | 部署Deployment |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 标识服务器部署 - 缓存Identity Server Deployment - Caching |
步骤Steps | IdentityServer 具有简单的内置内存中缓存。IdentityServer has a simple built-in in-memory cache. 尽管对于小规模本机应用而言这很合适,但是,出于以下原因,它无法根据中间层和后端应用程序缩放:While this is good for small scale native apps, it does not scale for mid tier and backend applications for the following reasons:
|
确保部署的应用程序的二进制文件经过数字签名Ensure that deployed application's binaries are digitally signed
标题Title | 详细信息Details |
---|---|
组件Component | 计算机信任边界Machine Trust Boundary |
SDL 阶段SDL Phase | 部署Deployment |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 空值N/A |
步骤Steps | 确保部署的应用程序的二进制文件经过数字签名,以便能够验证二进制文件的完整性Ensure that deployed application's binaries are digitally signed so that the integrity of the binaries can be verified |
连接到 WCF 中的 MSMQ 队列时启用身份验证Enable authentication when connecting to MSMQ queues in WCF
标题Title | 详细信息Details |
---|---|
组件Component | WCFWCF |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型、NET Framework 3Generic, NET Framework 3 |
属性Attributes | 空值N/A |
参考References | MSDNMSDN |
步骤Steps | 如果程序在连接到 MSMQ 队列时无法启用身份验证,攻击者可能会以匿名方式将消息提交到队列进行处理。Program fails to enable authentication when connecting to MSMQ queues, an attacker can anonymously submit messages to the queue for processing. 如果不使用身份验证连接到用于向另一程序传送消息的 MSMQ 队列,攻击者可能会提交恶意的匿名消息。If authentication is not used to connect to an MSMQ queue used to deliver a message to another program, an attacker could submit an anonymous message that is malicious. |
示例Example
以下 WCF 配置文件中的 <netMsmqBinding/>
元素指示 WCF 在连接到用于消息传送的 MSMQ 队列时禁用身份验证。The <netMsmqBinding/>
element of the WCF configuration file below instructs WCF to disable authentication when connecting to an MSMQ queue for message delivery.
<bindings>
<netMsmqBinding>
<binding>
<security>
<transport msmqAuthenticationMode=""None"" />
</security>
</binding>
</netMsmqBinding>
</bindings>
请将 MSMQ 配置为要求随时针对任何传入或传出的消息执行 Windows 域或证书身份验证。Configure MSMQ to require Windows Domain or Certificate authentication at all times for any incoming or outgoing messages.
示例Example
以下 WCF 配置文件中的 <netMsmqBinding/>
元素指示 WCF 在连接到 MSMQ 队列时启用证书身份验证。The <netMsmqBinding/>
element of the WCF configuration file below instructs WCF to enable certificate authentication when connecting to an MSMQ queue. 客户端使用 X.509 证书进行身份验证。The client is authenticated using X.509 certificates. 客户端证书必须在服务器的证书存储中存在。The client certificate must be present in the certificate store of the server.
<bindings>
<netMsmqBinding>
<binding>
<security>
<transport msmqAuthenticationMode=""Certificate"" />
</security>
</binding>
</netMsmqBinding>
</bindings>
WCF - 不要将消息 clientCredentialType 设置为 noneWCF-Do not set Message clientCredentialType to none
标题Title | 详细信息Details |
---|---|
组件Component | WCFWCF |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | .NET Framework 3.NET Framework 3 |
属性Attributes | 客户端凭据类型 - NoneClient Credential Type - None |
参考References | MSDN、FortifyMSDN, Fortify |
步骤Steps | 缺少身份验证意味着每个人都能访问此服务。The absence of authentication means everyone is able to access this service. 不对其客户端进行身份验证的服务允许所有用户访问。A service that does not authenticate its clients allows access to all users. 将应用程序配置为对客户端凭据进行身份验证。Configure the application to authenticate against client credentials. 为此,可将消息 clientCredentialType 设置为 Windows 或 Certificate。This can be done by setting the message clientCredentialType to Windows or Certificate. |
示例Example
<message clientCredentialType=""Certificate""/>
WCF - 不要将传输 clientCredentialType 设置为 noneWCF-Do not set Transport clientCredentialType to none
标题Title | 详细信息Details |
---|---|
组件Component | WCFWCF |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型、.NET Framework 3Generic, .NET Framework 3 |
属性Attributes | 客户端凭据类型 - NoneClient Credential Type - None |
参考References | MSDN、FortifyMSDN, Fortify |
步骤Steps | 缺少身份验证意味着每个人都能访问此服务。The absence of authentication means everyone is able to access this service. 不对其客户端进行身份验证的服务允许所有用户访问其功能。A service that does not authenticate its clients allows all users to access its functionality. 将应用程序配置为对客户端凭据进行身份验证。Configure the application to authenticate against client credentials. 为此,可将传输 clientCredentialType 设置为 Windows 或 Certificate。This can be done by setting the transport clientCredentialType to Windows or Certificate. |
示例Example
<transport clientCredentialType=""Certificate""/>
确保使用标准身份验证技术保护 Web APIEnsure that standard authentication techniques are used to secure Web APIs
标题Title | 详细信息Details |
---|---|
组件Component | Web APIWeb API |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | ASP.NET Web API 中的身份验证和授权、使用 ASP.NET Web API 的外部身份验证服务 (C#)Authentication and Authorization in ASP.NET Web API, External Authentication Services with ASP.NET Web API (C#) |
步骤Steps | 身份验证是某个实体证明其身份的过程,这通常是通过用户名和密码等凭据完成的。Authentication is the process where an entity proves its identity, typically through credentials, such as a user name and password. 可以考虑使用多种身份验证协议。There are multiple authentication protocols available which may be considered. 下面列出了其中一些协议:Some of them are listed below:
参考部分中的链接提供了有关如何实施每种身份验证方案来保护 Web API 的低级别详细信息。Links in the references section provide low-level details on how each of the authentication schemes can be implemented to secure a Web API. |
使用 Azure Active Directory 支持的标准身份验证方案Use standard authentication scenarios supported by Azure Active Directory
标题Title | 详细信息Details |
---|---|
组件Component | Azure ADAzure AD |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | Azure AD 的身份验证方案、Azure Active Directory 代码示例、Azure Active Directory 开发人员指南Authentication Scenarios for Azure AD, Azure Active Directory Code Samples, Azure Active Directory developer's guide |
步骤Steps | Azure Active Directory (Azure AD) 通过提供标识即服务并支持 OAuth 2.0 和 OpenID Connect 等行业标准协议,简化了对开发人员的身份验证。Azure Active Directory (Azure AD) simplifies authentication for developers by providing identity as a service, with support for industry-standard protocols such as OAuth 2.0 and OpenID Connect. 下面是 Azure AD 支持的五种主要应用程序方案:Below are the five primary application scenarios supported by Azure AD:
请参阅参考部分中的链接,了解低级别实施详细信息Please refer to the links in the references section for low-level implementation details |
使用可缩放的替代方案覆盖默认的 ADAL 令牌缓存Override the default ADAL token cache with a scalable alternative
标题Title | 详细信息Details |
---|---|
组件Component | Azure ADAzure AD |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 使用 Azure Active Directory 对 Web 应用程序执行新式身份验证、使用 Redis 作为 ADAL 令牌缓存Modern Authentication with Azure Active Directory for Web Applications, Using Redis as ADAL token cache |
步骤Steps | ADAL(Active Directory 身份验证库)使用的默认缓存是依赖于静态存储、可在进程范围内使用的内存中缓存。The default cache that ADAL (Active Directory Authentication Library) uses is an in-memory cache that relies on a static store, available process-wide. 尽管这很适合用于本机应用程序,但是,出于以下原因,它无法根据中间层和后端应用程序缩放:While this works for native applications, it does not scale for mid tier and backend applications for the following reasons:
出于上述所有原因,在实施 Web 应用程序时,建议使用 Azure Redis 缓存等可缩放的替代方案来覆盖默认的 ADAL 令牌缓存。For all the above reasons, while implementing web apps, it is recommended to override the default ADAL token cache with a scalable alternative such as Azure Cache for Redis. |
确保使用 TokenReplayCache 防止 ADAL 身份验证令牌重放Ensure that TokenReplayCache is used to prevent the replay of ADAL authentication tokens
标题Title | 详细信息Details |
---|---|
组件Component | Azure ADAzure AD |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 使用 Azure Active Directory 对 Web 应用程序执行新式身份验证Modern Authentication with Azure Active Directory for Web Applications |
步骤Steps | 开发人员可以使用 TokenReplayCache 属性来定义令牌重放缓存,这是一个可以用来保存令牌的存储,用途是验证没有多次使用某个令牌。The TokenReplayCache property allows developers to define a token replay cache, a store that can be used for saving tokens for the purpose of verifying that no token can be used more than once. 这是针对一种所谓的令牌重放攻击的常见攻击采取的措施:截获登录时发送的令牌的攻击者可能会尝试再次将该令牌发送到应用(“重放”它),以求建立新的会话。This is a measure against a common attack, the aptly called token replay attack: an attacker intercepting the token sent at sign-in might try to send it to the app again (“replay” it) for establishing a new session. 例如,在 OIDC 代码授予流中,用户身份验证成功后,向信赖方的“/signin-oidc”终结点发出的请求包含“id_token”、“code”和“state”参数。E.g., In OIDC code-grant flow, after successful user authentication, a request to "/signin-oidc" endpoint of the relying party is made with "id_token", "code" and "state" parameters. 信赖方会验证此请求并建立新的会话。The relying party validates this request and establishes a new session. 如果攻击者捕获到此请求并重放它,就可以建立成功的会话并欺骗用户。If an adversary captures this request and replays it, he/she can establish a successful session and spoof the user. 在 OpenID Connect 中使用 nonce 可以限制但不能完全消除攻击成功得手的结果。The presence of the nonce in OpenID Connect can limit but not fully eliminate the circumstances in which the attack can be successfully enacted. 为了保护应用程序,开发人员可以提供 ITokenReplayCache 的实现,并向 TokenReplayCache 分配一个实例。To protect their applications, developers can provide an implementation of ITokenReplayCache and assign an instance to TokenReplayCache. |
示例Example
// ITokenReplayCache defined in ADAL
public interface ITokenReplayCache
{
bool TryAdd(string securityToken, DateTime expiresOn);
bool TryFind(string securityToken);
}
示例Example
下面是 ITokenReplayCache 接口的示例实现。Here is a sample implementation of the ITokenReplayCache interface. (请自定义并实现自己的特定于项目的缓存框架)(Please customize and implement your project-specific caching framework)
public class TokenReplayCache : ITokenReplayCache
{
private readonly ICacheProvider cache; // Your project-specific cache provider
public TokenReplayCache(ICacheProvider cache)
{
this.cache = cache;
}
public bool TryAdd(string securityToken, DateTime expiresOn)
{
if (this.cache.Get<string>(securityToken) == null)
{
this.cache.Set(securityToken, securityToken);
return true;
}
return false;
}
public bool TryFind(string securityToken)
{
return this.cache.Get<string>(securityToken) != null;
}
}
必须通过“TokenValidationParameters”属性在 OIDC 选项中引用实现的缓存,如下所示。The implemented cache has to be referenced in OIDC options via the "TokenValidationParameters" property as follows.
OpenIdConnectOptions openIdConnectOptions = new OpenIdConnectOptions
{
AutomaticAuthenticate = true,
... // other configuration properties follow..
TokenValidationParameters = new TokenValidationParameters
{
TokenReplayCache = new TokenReplayCache(/*Inject your cache provider*/);
}
}
请注意,若要测试此配置的有效性,请登录到受 OIDC 保护的本地应用程序,并在 Fiddler 中捕获向 "/signin-oidc"
终结点发出的请求。Please note that to test the effectiveness of this configuration, login into your local OIDC-protected application and capture the request to "/signin-oidc"
endpoint in fiddler. 如果未实施保护,在 Fiddler 中重放此请求会设置一个新的会话 Cookie。When the protection is not in place, replaying this request in fiddler will set a new session cookie. 添加 TokenReplayCache 保护后重放请求时,应用程序将引发异常,如下所示:SecurityTokenReplayDetectedException: IDX10228: The securityToken has previously been validated, securityToken: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSIsImtpZCI6Ik1uQ1......
When the request is replayed after the TokenReplayCache protection is added, the application will throw an exception as follows: SecurityTokenReplayDetectedException: IDX10228: The securityToken has previously been validated, securityToken: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSIsImtpZCI6Ik1uQ1......
使用 ADAL 库来管理从 OAuth2 客户端发往 AAD(或本地 AD)的令牌请求Use ADAL libraries to manage token requests from OAuth2 clients to AAD (or on-premises AD)
标题Title | 详细信息Details |
---|---|
组件Component | Azure ADAzure AD |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | ADALADAL |
步骤Steps | 通过 Azure AD 身份验证库 (ADAL),客户端应用程序开发人员能够轻松利用云或本地 Active Directory (AD) 对用户进行身份验证,然后获取访问令牌,进行安全的 API 调用。The Azure AD authentication Library (ADAL) enables client application developers to easily authenticate users to cloud or on-premises Active Directory (AD), and then obtain access tokens for securing API calls. ADAL 提供许多可以方便开发人员进行身份验证的功能,例如,异步支持、用于存储访问令牌和刷新令牌的可配置令牌缓存、访问令牌过期且刷新令牌可用时自动刷新令牌,等等。ADAL has many features that make authentication easier for developers, such as asynchronous support, a configurable token cache that stores access tokens and refresh tokens, automatic token refresh when an access token expires and a refresh token is available, and more. ADAL 可以应对大部分复杂情况,因而可以帮助开发人员集中处理其应用程序中的业务逻辑,并可轻松保护资源而不必成为安全方面的专家。By handling most of the complexity, ADAL can help a developer focus on business logic in their application and easily secure resources without being an expert on security. .NET、JavaScript(客户端和 Node.js)、Python、iOS、Android 和 Java 有单独的库。Separate libraries are available for .NET, JavaScript (client and Node.js), Python, iOS, Android and Java. |
对连接到现场网关的设备进行身份验证Authenticate devices connecting to the Field Gateway
标题Title | 详细信息Details |
---|---|
组件Component | IoT 现场网关IoT Field Gateway |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 空值N/A |
步骤Steps | 确保现场网关在接受每个设备的数据以及帮助上游与云网关通信之前,对每个设备进行身份验证。Ensure that each device is authenticated by the Field Gateway before accepting data from them and before facilitating upstream communications with the Cloud Gateway. 此外,确保设备使用每个设备的凭据建立连接,以便能够唯一标识各个设备。Also, ensure that devices connect with a per device credential so that individual devices can be uniquely identified. |
确保对连接到云网关的设备进行身份验证Ensure that devices connecting to Cloud gateway are authenticated
标题Title | 详细信息Details |
---|---|
组件Component | IoT 云网关IoT Cloud Gateway |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型、C#、Node.JS,Generic, C#, Node.JS, |
属性Attributes | 不适用,网关选项 - Azure IoT 中心N/A, Gateway choice - Azure IoT Hub |
参考References | 不适用,使用 .NET 的 Azure IoT 中心、IoT 中心和 Node JS 入门、使用 SAS 和证书保护 IoT、Git 存储库N/A, Azure IoT hub with .NET, Getting Started with IoT hub and Node JS, Securing IoT with SAS and certificates, Git repository |
步骤Steps |
|
示例Example
static DeviceClient deviceClient;
static string deviceKey = "{device key}";
static string iotHubUri = "{iot hub hostname}";
var messageString = "{message in string format}";
var message = new Message(Encoding.ASCII.GetBytes(messageString));
deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey("myFirstDevice", deviceKey));
await deviceClient.SendEventAsync(message);
示例Example
Node.JS:身份验证Node.JS: Authentication
对称密钥Symmetric key
- 在 Azure 中创建 IoT 中心Create an IoT hub on azure
- 在设备标识注册表中创建条目Create an entry in the device identity registry
var device = new iothub.Device(null); device.deviceId = <DeviceId > registry.create(device, function(err, deviceInfo, res) {})
- 创建模拟设备Create a simulated device
var clientFromConnectionString = require('azure-iot-device-amqp').clientFromConnectionString; var Message = require('azure-iot-device').Message; var connectionString = 'HostName=<HostName>DeviceId=<DeviceId>SharedAccessKey=<SharedAccessKey>'; var client = clientFromConnectionString(connectionString);
SAS 令牌SAS Token
- 使用对称密钥时会在内部生成,但我们也可以显式生成并使用它Gets internally generated when using symmetric key but we can generate and use it explicitly as well
- 定义协议:
var Http = require('azure-iot-device-http').Http;
Define a protocol :var Http = require('azure-iot-device-http').Http;
- 创建 SAS 令牌:Create a sas token :
resourceUri = encodeURIComponent(resourceUri.toLowerCase()).toLowerCase(); var deviceName = "<deviceName >"; var expires = (Date.now() / 1000) + expiresInMins * 60; var toSign = resourceUri + '\n' + expires; // using crypto var decodedPassword = new Buffer(signingKey, 'base64').toString('binary'); const hmac = crypto.createHmac('sha256', decodedPassword); hmac.update(toSign); var base64signature = hmac.digest('base64'); var base64UriEncoded = encodeURIComponent(base64signature); // construct authorization string var token = "SharedAccessSignature sr=" + resourceUri + "%2fdevices%2f"+deviceName+"&sig=" + base64UriEncoded + "&se=" + expires; if (policyName) token += "&skn="+policyName; return token;
- 使用 SAS 令牌建立连接:Connect using sas token:
Client.fromSharedAccessSignature(sas, Http);
证书Certificates
- 使用 OpenSSL 等任何工具生成自签名的 X509 证书,以便生成分别用于存储证书和密钥的 .cert 和 .key 文件Generate a self signed X509 certificate using any tool such as OpenSSL to generate a .cert and .key files to store the certificate and the key respectively
- 使用证书预配接受安全连接的设备。Provision a device that accepts secured connection using certificates.
var connectionString = '<connectionString>'; var registry = iothub.Registry.fromConnectionString(connectionString); var deviceJSON = {deviceId:"<deviceId>", authentication: { x509Thumbprint: { primaryThumbprint: "<PrimaryThumbprint>", secondaryThumbprint: "<SecondaryThumbprint>" } }} var device = deviceJSON; registry.create(device, function (err) {});
- 使用证书连接设备Connect a device using a certificate
var Protocol = require('azure-iot-device-http').Http; var Client = require('azure-iot-device').Client; var connectionString = 'HostName=<HostName>DeviceId=<DeviceId>x509=true'; var client = Client.fromConnectionString(connectionString, Protocol); var options = { key: fs.readFileSync('./key.pem', 'utf8'), cert: fs.readFileSync('./server.crt', 'utf8') }; // Calling setOptions with the x509 certificate and key (and optionally, passphrase) will configure the client //transport to use x509 when connecting to IoT Hub client.setOptions(options); //call fn to execute after the connection is set up client.open(fn);
使用每个设备的身份验证凭据Use per-device authentication credentials
标题Title | 详细信息Details |
---|---|
组件Component | IoT 云网关IoT Cloud Gateway |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 网关选项 - Azure IoT 中心Gateway choice - Azure IoT Hub |
参考References | Azure IoT 中心安全令牌Azure IoT Hub Security Tokens |
步骤Steps | 结合基于 SAS 令牌的设备密钥或客户端证书使用每个设备的身份验证凭据,而不要使用 IoT 中心级别的共享访问策略。Use per device authentication credentials using SaS tokens based on Device key or Client Certificate, instead of IoT Hub-level shared access policies. 这可以防止其他人重复使用一个设备或现场网关的身份验证令牌This prevents the reuse of authentication tokens of one device or field gateway by another |
确保只对所需的容器和 Blob 授予匿名读取访问权限Ensure that only the required containers and blobs are given anonymous read access
标题Title | 详细信息Details |
---|---|
组件Component | Azure 存储Azure Storage |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | StorageType - BlobStorageType - Blob |
参考References | 管理对容器和 Blob 的匿名读取访问、共享访问签名,第 1 部分:了解 SAS 模型Manage anonymous read access to containers and blobs, Shared Access Signatures, Part 1: Understanding the SAS model |
步骤Steps | 默认情况下,仅存储帐户的所有者能够访问容器以及其中的所有 Blob。By default, a container and any blobs within it may be accessed only by the owner of the storage account. 若要授予匿名用户对容器及其 Blob 的读取权限,可以设置容器权限以允许公共访问。To give anonymous users read permissions to a container and its blobs, one can set the container permissions to allow public access. 匿名用户可以读取可公开访问的容器中的 Blob,而无需对请求进行身份验证。Anonymous users can read blobs within a publicly accessible container without authenticating the request. 容器提供了下列用于管理容器访问的选项:Containers provide the following options for managing container access:
如果想要始终允许对某些 Blob 进行匿名读取访问,最好是启用匿名访问。Anonymous access is best for scenarios where certain blobs should always be available for anonymous read access. 若要进行更精细的控制,可以创建一个共享访问签名,这样便可使用不同的权限在指定时间间隔内委派受限访问。For finer-grained control, one can create a shared access signature, which enables to delegate restricted access using different permissions and over a specified time interval. 确保不要意外地授予对可能包含敏感数据的容器和 Blob 的匿名访问权限Ensure that containers and blobs, which may potentially contain sensitive data, are not given anonymous access accidentally |
使用 SAS 或 SAP 授予对 Azure 存储中的对象的受限访问权限Grant limited access to objects in Azure storage using SAS or SAP
标题Title | 详细信息Details |
---|---|
组件Component | Azure 存储Azure Storage |
SDL 阶段SDL Phase | 构建Build |
适用的技术Applicable Technologies | 泛型Generic |
属性Attributes | 空值N/A |
参考References | 共享访问签名,第 1 部分:了解 SAS 模型,共享访问签名,第 2 部分:通过 Blob 存储创建和使用 SAS,如何使用共享访问签名和存储访问策略来委派对帐户中对象的访问权限Shared Access Signatures, Part 1: Understanding the SAS model, Shared Access Signatures, Part 2: Create and use a SAS with Blob storage, How to delegate access to objects in your account using Shared Access Signatures and Stored Access Policies |
步骤Steps | 使用共享访问签名 (SAS) 是将对存储帐户中对象的受限访问权限授予其他客户端且不必公开帐户访问密钥的一种高度有效的方法。Using a shared access signature (SAS) is a powerful way to grant limited access to objects in a storage account to other clients, without having to expose account access key. SAS 是在其查询参数中包含对存储资源进行验证了身份的访问所需的所有信息的 URI。The SAS is a URI that encompasses in its query parameters all of the information necessary for authenticated access to a storage resource. 要使用 SAS 访问存储资源,客户端只需将 SAS 传入到相应的构造函数或方法。To access storage resources with the SAS, the client only needs to pass in the SAS to the appropriate constructor or method. 需要将存储帐户中资源的访问权限提供给不能使用帐户密钥进行信任的客户端时,可以使用 SAS。You can use a SAS when you want to provide access to resources in your storage account to a client that can't be trusted with the account key. 存储帐户密钥包括主密钥和辅助密钥,这两种密钥都授予对帐户以及其中所有资源的管理访问权限。Your storage account keys include both a primary and secondary key, both of which grant administrative access to your account and all of the resources in it. 公开这两种帐户密钥的任何一种都会向可能的恶意或负面使用开放帐户。Exposing either of your account keys opens your account to the possibility of malicious or negligent use. 共享访问签名提供一种安全的方法,允许其他客户端根据你授予的权限读取、写入和删除存储帐户中的数据,而无需帐户密钥。Shared access signatures provide a safe alternative that allows other clients to read, write, and delete data in your storage account according to the permissions you've granted, and without need for the account key. 如果每次都有一组类似的逻辑参数,使用存储访问策略 (SAP) 是个不错的想法。If you have a logical set of parameters that are similar each time, using a Stored Access Policy (SAP) is a better idea. 由于使用派生自存储访问策略的 SAS 可以立即撤销该 SAS,因此建议的最佳做法是尽可能使用存储访问策略。Because using a SAS derived from a Stored Access Policy gives you the ability to revoke that SAS immediately, it is the recommended best practice to always use Stored Access Policies when possible. |