gf icon indicating copy to clipboard operation
gf copied to clipboard

r.Response.WriteJsonP 存在XSS攻击漏洞

Open insuns opened this issue 2 years ago • 0 comments

看了下源代码,客户提交的callback并未经过处理,再使用框架的时候如果不知情很容易造成XSS攻击:

// WriteJson writes <content> to the response with JSONP format.
//
// Note that there should be a "callback" parameter in the request for JSONP format.
func (r *Response) WriteJsonP(content interface{}) error {
	// If given string/[]byte, response it directly to client.
	switch content.(type) {
	case string, []byte:
		r.Header().Set("Content-Type", "application/json")
		r.Write(gconv.String(content))
		return nil
	}
	// Else use json.Marshal function to encode the parameter.
	if b, err := json.Marshal(content); err != nil {
		return err
	} else {
		//r.Header().Set("Content-Type", "application/json")
		if callback := r.Request.GetString("callback"); callback != "" {
			buffer := []byte(callback)
			buffer = append(buffer, byte('('))
			buffer = append(buffer, b...)
			buffer = append(buffer, byte(')'))
			r.Write(buffer)
		} else {
			r.Write(b)
		}
	}
	return nil
}

这里需要对callback进行处理:

if callback := r.Request.GetString("callback"); callback != "" {
		re, _ := regexp.Compile(`[^a-zA-Z_\-\d]+`)
		callback = re.ReplaceAllString(callback, "")

		buffer := []byte(callback)
		buffer = append(buffer, byte('('))
		buffer = append(buffer, b...)
		buffer = append(buffer, byte(')'))
		r.Write(buffer)
	} else {
		r.Write(b)
	}

WX20220920-095715@2x

insuns avatar Sep 20 '22 02:09 insuns