HarmonyOS 鸿蒙Next网络编程系列28-服务端证书锁定防范中间人攻击示例
HarmonyOS 鸿蒙Next网络编程系列28-服务端证书锁定防范中间人攻击示例
1. TLS通讯中间人攻击及防范简介
TLS安全通讯的基础是基于对操作系统或者浏览器根证书的信任,如果CA证书签发机构被入侵,或者设备内置证书被篡改,都会导致TLS握手环节面临中间人攻击的风险。其实,这种风险被善意利用的情况还是很常见的,比如著名的HTTPS调试工具Fiddler,就是利用了这一点,通过让使用者信任自己签发的证书,达到替换服务端证书的目的,最终可以实现对HTTPS通讯的监听。
那么,如何防范这种风险呢?HttpRequest的请求参数配置HttpRequestOptions提供了certificatePinning属性:
certificatePinning?: CertificatePinning | CertificatePinning[]
<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>
该属性接收一个或者多个证书的PIN码;在和服务端通讯前,配置服务端证书的PIN码到此属性中,在和服务端通讯时,HttpRequest请求会自动检查服务端证书的PIN码是否匹配该属性,如果不匹配就拒绝连接,从而达到只信任指定的服务端证书的目的,这样,即使中间人攻击得逞,应用也能拒绝和服务端通讯,从而避免了通讯被监听和破解。
2.服务端证书锁定演示
本示例以百度网站首页为例来演示服务端证书的锁定,需要先获取百度的服务端证书并保存到模拟器或者手机上。
本示例运行后的界面如下图所示。
单击“选择”按钮,在弹出的文件选择窗口里选择一个其他的证书,然后单击“请求”按钮,响应如下图所示,可以看到错误信息为公钥不匹配,请求失败。
然后继续单击“选择”按钮,这次选择本文开始时导出的百度证书,然后单击“请求”按钮,如下图所示,这次响应是正确的。
通过在应用中内置指定服务端证书的方式,达到了只信任特定证书的目的,从而可以有效防范中间人的攻击。
3.服务端证书锁定示例编写
下面详细介绍创建该示例的步骤。
步骤1:创建Empty Ability项目。
步骤2:在module.json5配置文件加上对权限的声明:
“requestPermissions”: [
{
“name”: “ohos.permission.INTERNET”
}
]
<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>
这里添加了访问互联网的权限。
步骤3:在Index.ets文件里添加如下的代码:
import picker from ‘@ohos.file.picker’;
import fs from ‘@ohos.file.fs’;
import { BusinessError } from ‘@kit.BasicServicesKit’;
import { http } from ‘@kit.NetworkKit’;
import { cert } from ‘@kit.DeviceCertificateKit’;
import { cryptoFramework } from ‘@kit.CryptoArchitectureKit’;
import { util } from ‘@kit.ArkTS’;
@Entry
@Component
struct Index {
@State title: string = ‘服务端证书锁定防范中间人攻击示例’;
//连接、通讯历史记录
@State msgHistory: string = ‘’
//请求的HTTPS地址
@State httpsUrl: string = “https://www.baidu.com/”
//是否锁定服务端证书
@State isServerCertFixed: boolean = true
//选择的锁定的证书文件
@State fixedCertFileUri: string = ‘’
//锁定证书的公钥哈希
@State fixedCertPubKeyHash: string = “”
scroller: Scroller = new Scroller()
build() {
Row() {
Column() {
Text(this.title)
.fontSize(14)
.fontWeight(FontWeight.Bold)
.width(‘100%’)
.textAlign(TextAlign.Center)
.padding(10)
Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
Column() {
Text(<span class="hljs-string"><span class="hljs-string">"是否锁定服务端证书"</span></span>)
.fontSize(<span class="hljs-number"><span class="hljs-number">14</span></span>)
.width(<span class="hljs-number"><span class="hljs-number">150</span></span>)
}
Column() {
Text(<span class="hljs-string"><span class="hljs-string">'不锁定'</span></span>).fontSize(<span class="hljs-number"><span class="hljs-number">14</span></span>)
Radio({ value: <span class="hljs-string"><span class="hljs-string">'0'</span></span>, group: <span class="hljs-string"><span class="hljs-string">'rgFixed'</span></span> }).checked(!<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.isServerCertFixed)
.height(<span class="hljs-number"><span class="hljs-number">30</span></span>)
.width(<span class="hljs-number"><span class="hljs-number">30</span></span>)
.onChange((isChecked: boolean) => {
<span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (isChecked) {
<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.isServerCertFixed = <span class="hljs-literal"><span class="hljs-literal">false</span></span>
}
})
}.width(<span class="hljs-number"><span class="hljs-number">100</span></span>)
Column() {
Text(<span class="hljs-string"><span class="hljs-string">'锁定'</span></span>).fontSize(<span class="hljs-number"><span class="hljs-number">14</span></span>)
Radio({ value: <span class="hljs-string"><span class="hljs-string">'1'</span></span>, group: <span class="hljs-string"><span class="hljs-string">'rgFixed'</span></span> }).checked(<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.isServerCertFixed)
.height(<span class="hljs-number"><span class="hljs-number">30</span></span>)
.width(<span class="hljs-number"><span class="hljs-number">30</span></span>)
.onChange((isChecked: boolean) => {
<span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (isChecked) {
<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.isServerCertFixed = <span class="hljs-literal"><span class="hljs-literal">true</span></span>
}
})
}.width(<span class="hljs-number"><span class="hljs-number">100</span></span>)
}
.width(<span class="hljs-string"><span class="hljs-string">'100%'</span></span>)
.padding(<span class="hljs-number"><span class="hljs-number">10</span></span>)
Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
Text(<span class="hljs-string"><span class="hljs-string">"锁定的服务端证书"</span></span>)
.fontSize(<span class="hljs-number"><span class="hljs-number">14</span></span>)
.width(<span class="hljs-number"><span class="hljs-number">90</span></span>)
.flexGrow(<span class="hljs-number"><span class="hljs-number">1</span></span>)
Button(<span class="hljs-string"><span class="hljs-string">"选择"</span></span>)
.onClick(async () => {
<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.fixedCertFileUri = await <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.selectFile()
<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.fixedCertPubKeyHash = await <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.getPubKeyHash(<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.fixedCertFileUri)
})
.width(<span class="hljs-number"><span class="hljs-number">70</span></span>)
.fontSize(<span class="hljs-number"><span class="hljs-number">14</span></span>)
}
.width(<span class="hljs-string"><span class="hljs-string">'100%'</span></span>)
.padding(<span class="hljs-number"><span class="hljs-number">10</span></span>)
.visibility(<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.isServerCertFixed ? Visibility.Visible : Visibility.None)
Text(<span class="hljs-string"><span class="hljs-string">"服务端证书公钥SHA256摘要:"</span></span>)
.width(<span class="hljs-string"><span class="hljs-string">'100%'</span></span>)
.fontSize(<span class="hljs-number"><span class="hljs-number">14</span></span>)
.padding(<span class="hljs-number"><span class="hljs-number">10</span></span>)
.visibility(<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.isServerCertFixed ? Visibility.Visible : Visibility.None)
Text(<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.fixedCertPubKeyHash)
.width(<span class="hljs-string"><span class="hljs-string">'100%'</span></span>)
.fontSize(<span class="hljs-number"><span class="hljs-number">14</span></span>)
.padding(<span class="hljs-number"><span class="hljs-number">10</span></span>)
.visibility(<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.isServerCertFixed ? Visibility.Visible : Visibility.None)
Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
Text(<span class="hljs-string"><span class="hljs-string">"请求地址:"</span></span>)
.fontSize(<span class="hljs-number"><span class="hljs-number">14</span></span>)
.width(<span class="hljs-number"><span class="hljs-number">80</span></span>)
TextInput({ text: <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.httpsUrl })
.onChange((value) => {
<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.httpsUrl = value
})
.width(<span class="hljs-number"><span class="hljs-number">110</span></span>)
.fontSize(<span class="hljs-number"><span class="hljs-number">12</span></span>)
.flexGrow(<span class="hljs-number"><span class="hljs-number">1</span></span>)
Button(<span class="hljs-string"><span class="hljs-string">"请求"</span></span>)
.onClick(() => {
<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.doHttpRequest()
})
.width(<span class="hljs-number"><span class="hljs-number">60</span></span>)
.fontSize(<span class="hljs-number"><span class="hljs-number">14</span></span>)
}
.width(<span class="hljs-string"><span class="hljs-string">'100%'</span></span>)
.padding(<span class="hljs-number"><span class="hljs-number">10</span></span>)
Scroll(<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.scroller) {
Text(<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.msgHistory)
.textAlign(TextAlign.Start)
.padding(<span class="hljs-number"><span class="hljs-number">10</span></span>)
.width(<span class="hljs-string"><span class="hljs-string">'100%'</span></span>)
.backgroundColor(<span class="hljs-number"><span class="hljs-number">0xeeeeee</span></span>)
}
.align(Alignment.Top)
.backgroundColor(<span class="hljs-number"><span class="hljs-number">0xeeeeee</span></span>)
.height(<span class="hljs-number"><span class="hljs-number">300</span></span>)
.flexGrow(<span class="hljs-number"><span class="hljs-number">1</span></span>)
.scrollable(ScrollDirection.Vertical)
.scrollBar(BarState.On)
.scrollBarWidth(<span class="hljs-number"><span class="hljs-number">20</span></span>)
}
.width(<span class="hljs-string"><span class="hljs-string">'100%'</span></span>)
.justifyContent(FlexAlign.Start)
.height(<span class="hljs-string"><span class="hljs-string">'100%'</span></span>)
}
.height(<span class="hljs-string"><span class="hljs-string">'100%'</span></span>)
}
//发起http请求
doHttpRequest() {
//http请求对象
let httpRequest = http.createHttp();
<span class="hljs-keyword"><span class="hljs-keyword">let</span></span> opt: http.HttpRequestOptions = {
method: http.RequestMethod.GET,
expectDataType: http.HttpDataType.STRING
}
<span class="hljs-comment"><span class="hljs-comment">//配置服务端证书PIN码</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.isServerCertFixed) {
<span class="hljs-keyword"><span class="hljs-keyword">let</span></span> certPinning: http.CertificatePinning = { publicKeyHash: <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.fixedCertPubKeyHash, hashAlgorithm: <span class="hljs-string"><span class="hljs-string">"SHA-256"</span></span> }
opt.certificatePinning = certPinning
}
httpRequest.request(<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.httpsUrl, opt)
.then((resp) => {
<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.msgHistory += <span class="hljs-string"><span class="hljs-string">"响应码:"</span></span> + resp.responseCode + <span class="hljs-string"><span class="hljs-string">"\r\n"</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.msgHistory += <span class="hljs-string"><span class="hljs-string">'请求响应信息: '</span></span> + resp.result + <span class="hljs-string"><span class="hljs-string">"\r\n"</span></span>;
})
.catch((err: BusinessError) => {
<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.msgHistory += `请求失败:err code is ${err.code}, err message is ${<span class="hljs-built_in"><span class="hljs-built_in">JSON</span></span>.stringify(err)}\r\n`;
})
}
//选择文件
async selectFile() {
let selectFile = “”
let documentPicker = new picker.DocumentViewPicker();
await documentPicker.select().then((result) => {
if (result.length > 0) {
selectFile = result[0]
this.msgHistory += "select file: " + selectFile + “\r\n”;
}
}).catch((err: BusinessError) => {
this.msgHistory += 选择文件失败:err code is ${err.code}, err message is ${<span class="hljs-built_in"><span class="hljs-built_in">JSON</span></span>.stringify(err)}\r\n
;
});
return selectFile
}
//加载文件内容
getContent(filePath: string): ArrayBuffer | undefined {
let content: ArrayBuffer | undefined = undefined
try {
let buf = new ArrayBuffer(1024 * 64);
let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
let readLen = fs.readSync(file.fd, buf, { offset: 0 });
content = buf.slice(0, readLen)
fs.closeSync(file);
} catch (e) {
this.msgHistory += '读取文件内容失败 ’ + e.message + “\r\n”;
}
return content
}
//获取证书文件对应的公钥SHA256摘要
async getPubKeyHash(filePath: string) {
let result = “”
if (filePath != “”) {
let fixedCert = await this.getCertFromFile(filePath)
if (fixedCert) {
try {
//获取公钥
let pubKey = fixedCert.getItem(cert.CertItemType.CERT_ITEM_TYPE_PUBLIC_KEY);
let mdSHA256 = cryptoFramework.createMd(“SHA256”)
mdSHA256.updateSync({ data: pubKey.data });
//公钥摘要计算结果
let mdResult = mdSHA256.digestSync();
let tool = new util.Base64Helper()
//公钥摘要转换为base64编码字符串
result = tool.encodeToStringSync(mdResult.data)
} catch (e) {
this.msgHistory += '获取公钥摘要失败 ’ + e.message + “\r\n”;
}
}
}
return result
}
//从文件获取X509证书
async getCertFromFile(filePath: string): Promise<cert.X509Cert | undefined> {
let newCert: cert.X509Cert | undefined = undefined
let certData = this.getContent(filePath);
if (certData) {
let encodingBlob: cert.EncodingBlob = {
data: new Uint8Array(certData),
encodingFormat: cert.EncodingFormat.FORMAT_PEM
};
await cert.createX509Cert(encodingBlob)
.then((x509Cert: cert.X509Cert) => {
newCert = x509Cert
})
.catch((err: BusinessError) => {
<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.msgHistory += `创建X509证书失败:err code is ${err.code}, err message is ${<span class="hljs-built_in"><span class="hljs-built_in">JSON</span></span>.stringify(err)}\r\n`;
})
}
<span class="hljs-keyword"><span class="hljs-keyword">return</span></span> newCert
}
}
<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>
步骤4:编译运行,可以使用模拟器或者真机。
步骤5:按照本节第2部分“服务端证书锁定演示”操作即可。
4.代码分析
本示例的关键点有三处,第一处是根据选择的证书文件生成X509证书,方法为getCertFromFile,其中使用getContent方法读取文件内容;第二处为生成证书公钥的摘要,方法为getPubKeyHash,这里特别注意的是获取公钥内容的方法,不能使用X509Cert接口的getPublicKey方法,而是使用getItem方法,生成摘要时要使用SHA256算法,摘要结果要通过Base64编码后作为字符串使;第三处是设置请求属性的PIN码,这里只设置了一个PIN码,如果信任多个证书,可以设置多个。
(本文作者原创,除非明确授权禁止转载)
本文源码地址:
https://gitee.com/zl3624/harmonyos_network_samples/tree/master/code/http/CertificatePinningDemo
本系列源码地址:
https://gitee.com/zl3624/harmonyos_network_samples
其他鸿蒙网络编程文章:
鸿蒙网络编程系列10-使用HttpRequest下载文件到本地示例
鸿蒙网络编程系列11-使用HttpRequest上传文件到服务端示例
鸿蒙网络编程系列12-使用Request部件下载文件到本地示例
鸿蒙网络编程系列13-使用Request部件上传文件到服务端示例
鸿蒙网络编程系列19-获取网络连接信息并选择一种绑定到应用示例
鸿蒙网络编程系列21-使用HttpRequest上传任意文件到服务端示例
关于HarmonyOS 鸿蒙Next网络编程系列28-服务端证书锁定防范中间人攻击示例的问题,您也可以访问:https://www.itying.com/category-93-b0.html 联系官网客服。