鴻蒙網(wǎng)絡(luò)編程系列28-服務(wù)端證書(shū)鎖定防范中間人攻擊示例

1. TLS通訊中間人攻擊及防范簡(jiǎn)介

TLS安全通訊的基礎(chǔ)是基于對(duì)操作系統(tǒng)或者瀏覽器根證書(shū)的信任,如果CA證書(shū)簽發(fā)機(jī)構(gòu)被入侵,或者設(shè)備內(nèi)置證書(shū)被篡改,都會(huì)導(dǎo)致TLS握手環(huán)節(jié)面臨中間人攻擊的風(fēng)險(xiǎn)。其實(shí),這種風(fēng)險(xiǎn)被善意利用的情況還是很常見(jiàn)的,比如著名的HTTPS調(diào)試工具Fiddler,就是利用了這一點(diǎn),通過(guò)讓使用者信任自己簽發(fā)的證書(shū),達(dá)到替換服務(wù)端證書(shū)的目的,最終可以實(shí)現(xiàn)對(duì)HTTPS通訊的監(jiān)聽(tīng)。

那么,如何防范這種風(fēng)險(xiǎn)呢?HttpRequest的請(qǐng)求參數(shù)配置HttpRequestOptions提供了certificatePinning屬性:

certificatePinning?: CertificatePinning | CertificatePinning[]

該屬性接收一個(gè)或者多個(gè)證書(shū)的PIN碼;在和服務(wù)端通訊前,配置服務(wù)端證書(shū)的PIN碼到此屬性中,在和服務(wù)端通訊時(shí),HttpRequest請(qǐng)求會(huì)自動(dòng)檢查服務(wù)端證書(shū)的PIN碼是否匹配該屬性,如果不匹配就拒絕連接,從而達(dá)到只信任指定的服務(wù)端證書(shū)的目的,這樣,即使中間人攻擊得逞,應(yīng)用也能拒絕和服務(wù)端通訊,從而避免了通訊被監(jiān)聽(tīng)和破解。

2.服務(wù)端證書(shū)鎖定演示

本示例以百度網(wǎng)站首頁(yè)為例來(lái)演示服務(wù)端證書(shū)的鎖定,需要先獲取百度的服務(wù)端證書(shū)并保存到模擬器或者手機(jī)上。

本示例運(yùn)行后的界面如下圖所示。

image.png

單擊“選擇”按鈕,在彈出的文件選擇窗口里選擇一個(gè)其他的證書(shū),然后單擊“請(qǐng)求”按鈕,響應(yīng)如下圖所示,可以看到錯(cuò)誤信息為公鑰不匹配,請(qǐng)求失敗。

image.png

然后繼續(xù)單擊“選擇”按鈕,這次選擇本文開(kāi)始時(shí)導(dǎo)出的百度證書(shū),然后單擊“請(qǐng)求”按鈕,如下圖所示,這次響應(yīng)是正確的。

image.png

通過(guò)在應(yīng)用中內(nèi)置指定服務(wù)端證書(shū)的方式,達(dá)到了只信任特定證書(shū)的目的,從而可以有效防范中間人的攻擊。

3.服務(wù)端證書(shū)鎖定示例編寫(xiě)

下面詳細(xì)介紹創(chuàng)建該示例的步驟。

步驟1:創(chuàng)建Empty Ability項(xiàng)目。

步驟2:在module.json5配置文件加上對(duì)權(quán)限的聲明:

"requestPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      }
    ]

這里添加了訪問(wèn)互聯(lián)網(wǎng)的權(quán)限。

步驟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 = '服務(wù)端證書(shū)鎖定防范中間人攻擊示例';
  //連接、通訊歷史記錄
  @State msgHistory: string = ''
  //請(qǐng)求的HTTPS地址
  @State httpsUrl: string = "https://www.baidu.com/"
  //是否鎖定服務(wù)端證書(shū)
  @State isServerCertFixed: boolean = true
  //選擇的鎖定的證書(shū)文件
  @State fixedCertFileUri: string = ''
  //鎖定證書(shū)的公鑰哈希
  @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("是否鎖定服務(wù)端證書(shū)")
              .fontSize(14)
              .width(150)
          }

          Column() {
            Text('不鎖定').fontSize(14)
            Radio({ value: '0', group: 'rgFixed' }).checked(!this.isServerCertFixed)
              .height(30)
              .width(30)
              .onChange((isChecked: boolean) => {
                if (isChecked) {
                  this.isServerCertFixed = false
                }
              })
          }.width(100)

          Column() {
            Text('鎖定').fontSize(14)
            Radio({ value: '1', group: 'rgFixed' }).checked(this.isServerCertFixed)
              .height(30)
              .width(30)
              .onChange((isChecked: boolean) => {
                if (isChecked) {
                  this.isServerCertFixed = true
                }
              })
          }.width(100)
        }
        .width('100%')
        .padding(10)

        Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
          Text("鎖定的服務(wù)端證書(shū)")
            .fontSize(14)
            .width(90)
            .flexGrow(1)

          Button("選擇")
            .onClick(async () => {
              this.fixedCertFileUri = await this.selectFile()
              this.fixedCertPubKeyHash = await this.getPubKeyHash(this.fixedCertFileUri)
            })
            .width(70)
            .fontSize(14)
        }
        .width('100%')
        .padding(10)
        .visibility(this.isServerCertFixed ? Visibility.Visible : Visibility.None)

        Text("服務(wù)端證書(shū)公鑰SHA256摘要:")
          .width('100%')
          .fontSize(14)
          .padding(10)
          .visibility(this.isServerCertFixed ? Visibility.Visible : Visibility.None)

        Text(this.fixedCertPubKeyHash)
          .width('100%')
          .fontSize(14)
          .padding(10)
          .visibility(this.isServerCertFixed ? Visibility.Visible : Visibility.None)

        Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
          Text("請(qǐng)求地址:")
            .fontSize(14)
            .width(80)
          TextInput({ text: this.httpsUrl })
            .onChange((value) => {
              this.httpsUrl = value
            })
            .width(110)
            .fontSize(12)
            .flexGrow(1)
          Button("請(qǐng)求")
            .onClick(() => {
              this.doHttpRequest()
            })
            .width(60)
            .fontSize(14)
        }
        .width('100%')
        .padding(10)

        Scroll(this.scroller) {
          Text(this.msgHistory)
            .textAlign(TextAlign.Start)
            .padding(10)
            .width('100%')
            .backgroundColor(0xeeeeee)
        }
        .align(Alignment.Top)
        .backgroundColor(0xeeeeee)
        .height(300)
        .flexGrow(1)
        .scrollable(ScrollDirection.Vertical)
        .scrollBar(BarState.On)
        .scrollBarWidth(20)
      }
      .width('100%')
      .justifyContent(FlexAlign.Start)
      .height('100%')
    }
    .height('100%')
  }

  //發(fā)起http請(qǐng)求
  doHttpRequest() {
    //http請(qǐng)求對(duì)象
    let httpRequest = http.createHttp();

    let opt: http.HttpRequestOptions = {
      method: http.RequestMethod.GET,
      expectDataType: http.HttpDataType.STRING
    }

    //配置服務(wù)端證書(shū)PIN碼
    if (this.isServerCertFixed) {
      let certPinning: http.CertificatePinning = { publicKeyHash: this.fixedCertPubKeyHash, hashAlgorithm: "SHA-256" }
      opt.certificatePinning = certPinning
    }

    httpRequest.request(this.httpsUrl, opt)
      .then((resp) => {
        this.msgHistory += "響應(yīng)碼:" + resp.responseCode + "\r\n"
        this.msgHistory += '請(qǐng)求響應(yīng)信息: ' + resp.result + "\r\n";
      })
      .catch((err: BusinessError) => {
        this.msgHistory += `請(qǐng)求失敗:err code is ${err.code}, err message is ${JSON.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 += `選擇文件失?。篹rr code is ${err.code}, err message is ${JSON.stringify(err)}\r\n`;
    });
    return selectFile
  }

  //加載文件內(nèi)容
  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 += '讀取文件內(nèi)容失敗 ' + e.message + "\r\n";
    }
    return content
  }

  //獲取證書(shū)文件對(duì)應(yīng)的公鑰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 });
          //公鑰摘要計(jì)算結(jié)果
          let mdResult = mdSHA256.digestSync();
          let tool = new util.Base64Helper()
          //公鑰摘要轉(zhuǎn)換為base64編碼字符串
          result = tool.encodeToStringSync(mdResult.data)
        } catch (e) {
          this.msgHistory += '獲取公鑰摘要失敗 ' + e.message + "\r\n";
        }
      }
    }
    return result
  }

  //從文件獲取X509證書(shū)
  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) => {
          this.msgHistory += `創(chuàng)建X509證書(shū)失?。篹rr code is ${err.code}, err message is ${JSON.stringify(err)}\r\n`;
        })
    }
    return newCert
  }
}

步驟4:編譯運(yùn)行,可以使用模擬器或者真機(jī)。

步驟5:按照本節(jié)第2部分“服務(wù)端證書(shū)鎖定演示”操作即可。

4.代碼分析

本示例的關(guān)鍵點(diǎn)有三處,第一處是根據(jù)選擇的證書(shū)文件生成X509證書(shū),方法為getCertFromFile,其中使用getContent方法讀取文件內(nèi)容;第二處為生成證書(shū)公鑰的摘要,方法為getPubKeyHash,這里特別注意的是獲取公鑰內(nèi)容的方法,不能使用X509Cert接口的getPublicKey方法,而是使用getItem方法,生成摘要時(shí)要使用SHA256算法,摘要結(jié)果要通過(guò)Base64編碼后作為字符串使;第三處是設(shè)置請(qǐng)求屬性的PIN碼,這里只設(shè)置了一個(gè)PIN碼,如果信任多個(gè)證書(shū),可以設(shè)置多個(gè)。

(本文作者原創(chuàng),除非明確授權(quán)禁止轉(zhuǎn)載)

本文源碼地址:

https://gitee.com/zl3624/harmonyos_network_samples/tree/master/code/http/CertificatePinningDemo

本系列源碼地址:

https://gitee.com/zl3624/harmonyos_network_samples

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容