当前位置:网站首页>Ultra-detailed Asp.net uses SSL two-way authentication, one article is enough
Ultra-detailed Asp.net uses SSL two-way authentication, one article is enough
2022-08-03 09:31:00 【A little breeze!】
传统:项目和项目之间https仅通过SSLData transmission is performed after one-way authentication;
本文:Do it from project to projectSSL双向认证,Prevent malicious damage from attackers;About the difference between one-way authentication and two-way authentication:https://cloud.tencent.com/developer/article/1819018
本文一共分为4章节
1章节:A brief description of the server's websiteSSLRole classification in mutual authentication;
2章节:Describes that third parties are visiting usServer API时,We need to configure and verify the client certificate it carries;
3章节:Describes the website on our server accessing a third party as a clientServer APIThe configuration that needs to be done and the configuration and acquisition of the local certificate;
4章节:Reference sources are briefly described;
1 叙述
The current system is aboutSSLTwo-way authentication includes two different roles:
1、The current system acts as a server(When a third party requests our services,Need to carry the client certificate issued to them)
2、The current system acts as a client(When we request third-party services,Need to carry the client certificate issued to us)
3、(Both can be used in combination)
The following chapters deal with the above(1)(2)section is described in detail;
2 The current system acts as a server
2.1 IIS的配置
(1)当只有部分API需要Client Certificate时,勾选“接受”;(本文)
(2)当整个Service都必须Client Certificate时,勾选“要求SSL”–>“必须”;
2.2 相关代码
2.2.1 Code verification snippet
The class in which the code below resides inherits the attribute,重写了基类方法;
var reClient = context.Request.GetClientCertificate();
if (reClient == null)
{
_logService.Error($"Client Certificate is null.");
context.ErrorResult = new AuthenticationFailureResult($"Client Certificate is require.", context.Request, HttpStatusCode.BadRequest);
return;
}
var x509 = new X509Certificate2(reClient);
var chain = new X509Chain(true);
chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;//Use online certificate revocation lists(CRL)Do a revocation check
if (chain.Build(x509))
{
context.ErrorResult = new AuthenticationFailureResult($"Invalid Client Certificate.", context.Request, HttpStatusCode.BadRequest);
_logService.Error("Invalid Client Certificate. chain: " + chain.ToString());
return;
}
List<string> x509IssuerList = WC_X509_IssuerListString.Replace(" ","").Split(';').ToList();//去除空格,WC_X509_IssuerListString变量为Appsetting.configWhich are allowed as configured in the fileCN的证书,分号作为分隔符,可配置多个CN
if (!x509IssuerList.Contains(x509.Issuer.Replace(" ", "")))
{
context.ErrorResult = new AuthenticationFailureResult($"", context.Request, HttpStatusCode.BadRequest);//Not return any message.
_logService.Error("Appsetting.config not exit x509Issuer: " + x509.Issuer.ToString());
return;
}
2.2.2 AppSetting.config设置
ValueUsed to configure which ones are allowedCN进行连接;多个CNseparated by semicolons(自定义);
2.3 Computer Management ConsoleMMC的配置
Win+R --> mmc,打开控制台;如图所示,点击“文件”–>“添加/删除管理单元”;
Select from the items on the left“证书”,点击中间“添加”按钮,如下图所示,选择“我的用户账户”,All other defaults,点击完成;Select the same method“计算机账户”;
(1)对于用户来说,User PC needs to be installed“客户端证书”时,只需要添加“我的用户账户”项;
(2)对于服务器来说,只需要添加“计算机账户”;
.
如下图所示,分别为配置“客户端证书”和“服务器证书”的主界面;
2.3.1 配置客户端证书
2.3.1.1 添加客户端证书
展开“证书 - 当前用户”节点,在“个人”–>“证书”右键,选择“所有任务”–>“导入”,点击“下一步”,选择“客户端.pfx”文件,点击“下一步”–> 输入文件的“密码”后,默认点击“下一步”,直到完成;At this point, the client certificate has been added;
2.3.1.2添加客户端证书CAIssuing Center
在“证书 - 当前用户”节点下,点击“受信任的根证书颁发机构”–>“证书”,右键“所有任务”–>“导入”,点击下一步,选择“.cer”文件,All default click Next,直到完成;At this point the client certificateCAThe issuance center has been added;
注意:If the client certificate and server certificateCAThe issuing center is inconsistent,The server certificate is requiredCAIssue documents(即.cer文件)Upload here;
2.3.2 配置服务器证书
2.3.2.1 Add server certificate
选择“服务器.pfx”文件;与2.3.1.1The operation steps are the same;
2.3.2.2 Add server certificateCAIssuing Center
与3.1.2The operation steps are the same;注意:If the client certificate and server certificateCAThe issuing center is inconsistent,A client certificate is requiredCAIssue documents(即.cer文件)Upload here;
2.4 two-way authenticationIIS的log记录
Log存储位置:C:\inetpub\logs\LogFiles,The last digit of the folder number corresponds toIIS中应用程序的ID列,如图所示;
2.4.1 AWS Log记录示例
Provide the correct client certificate(IIS Log):
Provide a self-signed client certificate(IIS Log):
No client certificate provided(网站Log4net记录)
---->【Client certificates is null】
Relevant certificates are provided,但是未在appsetting.config中配置该CN时(网站Log4net记录)
2.5 注意事项
2.5.1The difference between a website deployed on a local area network and a remote site
2.5.1.1When the website is deployed on a local area network
A website deployed in a local area network,Can be generated from the local computerCA、服务器证书、客户端证书;
The test results are tested by two computers in the local area network:Available on demandSSLTwo-way authentication is required;
2.5.1.2When the website is deployed remotely
(1)部署在远端时,Requires use by a third partyCAThe certificate issued(需要一定的费用),You can also try to search online by yourself“Request a free computer certificate”进行获取;
(2)Self-signed certificates are not trusted at the remote end,所以会被IIS拦截,可IIS的logSee related interceptions in 403记录(可参考4.1);
(3)Load balancing does not pass the certificate to another machine;
2.5.2 PostmanConfigure the request certificate
PostmanConfigure the client certificate as shown in the following figure(This document is provided by a third party)
2.5.3 与http层面的SSLThe difference between a two-way handshake
Because here is the verification of the client certificate through the program,所以在请求API时,The client certificate needs to be submitted at the same time(PostmanNeed to configure client certificate and CA的PEM文件,PEMThe files can be downloaded from the website);
从httpIn terms of level, it is not a two-way authentication in the actual sense,Therefore, only one-way verification can be seen through packet capture,But in a sense, it is a more strict two-way authentication,The reason for this is because of passing“代码 + appsetting.config文件”which are restrictedCN可以通过;而httpLevels do not filter specific onesCN;
3 The current system acts as a client
3.1 必备文件
1、A client certificate provided by a third party.pfx文件;
2、The secret key of the client certificate provided by the third party(明文,Do not expose freely);
3.2 The way the code gets the client certificate
注意:If the certificate expires frequently,可以选择“Get certificate by file path”方式(Within 1 years.),This saves you from passingMMCPerform complex configuration steps such as installation;
3.2.1Get certificate by file path(Not preferred)
注意:如果LogDocumentation hintsIIS无权限,则修改文件的访问权限,Right-click to modify properties.
#region 方式1:通过路径获取Client Certificate方式;
try
{
string certificatePath = @"....\ClientCertificateFile.pfx";//使用相对路径或者绝对路径,
string certPassword = "******"; //The plaintext password corresponding to the client certificate;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3|SecurityProtocolType.Tls| (SecurityProtocolType)768|(SecurityProtocolType)3072|(SecurityProtocolType)0x300|(SecurityProtocolType)0xC00;//根据当前frameworkThe enumeration in the version is set;
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;//获取或设置用于验证服务器证书的回调,根据实际情况true或false;
//clientCerThe object is the client certificate carried in the request
X509Certificate2 clientCer = new X509Certificate2(certificatePath, certPassword, X509KeyStorageFlags.MachineKeySet|X509KeyStorageFlags.PersistKeySet|X509KeyStorageFlags.Exportable);
catch (Exception ex)
{
logger.Error($"Get Client certificate Error : {
ex}.");
return null;
}
#endregion
3.2.2获取通过MMCInstalled certificate(首选)
#region 方式2:通过mmc安装Client Certificate方式
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true; //获取或设置用于验证服务器证书的回调,根据实际情况true或false;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | (SecurityProtocolType)768 | (SecurityProtocolType)3072 | (SecurityProtocolType)0x300 | (SecurityProtocolType)0xC00;
#if !DEBUG
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); //从 "本地计算机" 安装的Client Certificate中进行查找;//不能使用CurrentUser
#else
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);//从 "The current user of the computer" 安装的Client Certificate中进行查找;也可以使用LocalMachine
#endif
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
X509Certificate2 clientCer;
try
{
//var clintCertificatesList = store.Certificates.Cast<X509Certificate2>().Select(c => c.Thumbprint).ToList();
//foreach (var VARIABLE in clintCertificatesList)
//{
//logger.Info($" {VARIABLE}.");//可以通过log4net打印MMC中所有证书的指纹,用于调试使用;
//}
//do not use "store.Certificates.Find()" --> 性能不好
//Find By certificate thumbprint.
//Case must be omitted;
clientCer = store.Certificates.Cast<X509Certificate2>().FirstOrDefault(c => c.Thumbprint.Equals(“***证书指纹***”, StringComparison.OrdinalIgnoreCase)); //linq语法,Obtain the specified certificate based on the certificate fingerprint
if (clientCer == null)
{
logger.Error($"Client certificate is null.");
return null;
}
}
catch (Exception ex)
{
logger.Error($"Get Client certificate Error : {
ex}.");
return null;
}
#endregion
3.3 MMC及IIS的配置
3.3.1 MMCInstall and configure client certificate authority
Testers and implementers:参见本文2.3chapter Installing Client Certificates(Only on the local computer --> Local Machine);
开发人员:参见本文2.3All chapters(Local Machine,Current User);
3.3.2 Configure client certificates with IIS的权限
简介:There are two ways to do it here,Based on website security considerations,建议通过MMCto configure access to client certificates;
3.3.2.1 通过MMCConfigure access rights for client certificates(首选)
Win+R --> mmc,打开控制台;如图所示,点击“文件”–>“添加/删除管理单元”–“证书”–“本地计算机”;如下图所示;
After finding the specified client certificate installed,“右键”–“所有任务”–“管理私钥”–>点击“添加”–>点击“高级”–>点击“立即查找”,As shown in the list below;
选择“IIS_IUSERS”–> 点击确定,–> 点击确定–>“应用”–>“确定”,完成
3.3.2.2 设置IISRole permissions for the program pool(Not preferred)
It is not recommended to use this method to set(About the difference between built-in accounts,在第4Chapters have reference links);
步骤:打开IIS管理器,Find the program pool corresponding to the website–>“高级设置”–“进程模型”–>“标识”–>“Local System”–>“确定”即可;
4 Appendices and References
4.1 Chapter 3 References
1、IISPermission description for the application pool identity
https://blog.csdn.net/u014088408/article/details/98732583
https://www.cnblogs.com/jfzhu/p/4067297.html
https://docs.microsoft.com/zh-cn/troubleshoot/developer/webapps/iis/www-authentication-authorization/understanding-identities
2、IISUnable to read local certificate problem(See answer):Advanced Setting–>Process Model–>Identity IISThe default is lower permissions,可以改成Networkservice即可(Personally, I think it's changed hereLocalSystem是可以的,But it will be insecure due to too high permissions).
https://q.cnblogs.com/q/54675/
Corrections and questions are welcome;
边栏推荐
猜你喜欢
10 minutes to get you started chrome (Google) browser plug-in development
Machine learning (formula derivation and code implementation)--sklearn machine learning library
Chrome F12 keep before request information network
固件工程师到底是干什么?
MySQL-DDL数据定义语言-约束
mysql的union和union all
110道 MySQL面试题及答案 (持续更新)
RSTP(端口角色+端口状态+工作机制)|||| 交换机接口分析
flutter 应用 抓包
慢 SQL 分析与优化
随机推荐
别人都不知道的“好用”网站,让你的效率飞快
Does setting the following sysctl settings require a system reboot?
MySQL-DDL数据定义语言-约束
mysql8安装步骤教程
pytorch安装错误
Oracle 迁移至Mysql
浅析什么是伪类和伪元素?伪类和伪元素的区别解析
When deleting a folder, the error "Error ox80070091: The directory is not empty" is reported. How to solve it?
LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之二:编码实现
Validate floating point input
go中select语句
慢 SQL 分析与优化
Redis和MySQL如何保持数据一致性
好用的插件
qt使用mysql数据库(自学笔记)
多媒体数据处理实验4:LSH索引
分区分表(一)
兔起鹘落全端涵盖,Go lang1.18入门精炼教程,由白丁入鸿儒,全平台(Sublime 4)Go lang开发环境搭建EP00
bihash总结
go泛型使用方法