AdSense

網頁

2021/9/8

Golang JSON Injection 安全漏洞 json.Unmarshal to map[string]interface{}

最近碰到Go原始碼在靜態程式碼掃描時警告有JSON Injection漏洞(vulnerabilities),本篇紀錄解決方式。


原始的流程如下。

resp, err := httpGet(req)            // send requet to outside system
// deal err
jb, err := ioutil.ReadAll(resp.Body) // read reaponse body (json) as byte
// deal err
var m map[string]interface{}         // create map[string]interface variable to receive arbitrary struct data
json.Unmarshal(jb, &m)               // receive json byte to map[string]interface variable
b, err := json.Marshal(m)            // turn map[string]interface{} to bytes. JSON Injection!

發生JSON Injection的點在於接收外部回來的response資料為內部變數時使用了map[string]interface{}來接收任意JSON結構資料並直接轉為另個JSON byte,如果接收的JSON有什麼屬性,轉成的JSON就有什麼屬性,這代表可透過竄改外部回傳資料注入任意屬性及值來進行惡意攻擊。


不應用map[string]interface{}來接收任意JSON資料,改用struct清楚地定義欄位要接收的資料來避免JSON Injection。例如下面改用Datastruct接收response body的內容。

resp, err := httpGet(req)            // send requet to outside system
// deal err
jb, err := ioutil.ReadAll(resp.Body) // read reaponse body (json) as byte
// deal err
data := Data{}                       // creat Data struct to recive request body bytes
json.Unmarshal(jb, &data)            // read json bytes to Data struct
b, err := json.Marshal(data)         // turn data struct to bytes.

沒有留言:

AdSense