forked from chanxuehong/wechat
/
serve_http.go
216 lines (184 loc) · 6.59 KB
/
serve_http.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
// @description wechat 是腾讯微信公众平台 api 的 golang 语言封装
// @link https://github.com/c77cc/wechat for the canonical source repository
// @license https://github.com/c77cc/wechat/blob/master/LICENSE
// @authors c77cc(c77cc@gmail.com)
package corp
import (
"bytes"
"crypto/subtle"
"encoding/base64"
"encoding/xml"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"github.com/c77cc/wechat/util"
)
var zeroAESKey [32]byte
// 微信服务器请求 http body
type RequestHttpBody struct {
XMLName struct{} `xml:"xml" json:"-"`
CorpId string `xml:"ToUserName"`
AgentId int64 `xml:"AgentID"`
EncryptedMsg string `xml:"Encrypt"`
}
// ServeHTTP 处理 http 消息请求
// NOTE: 调用者保证所有参数有效
func ServeHTTP(w http.ResponseWriter, r *http.Request, queryValues url.Values,
agentServer AgentServer, invalidRequestHandler InvalidRequestHandler) {
switch r.Method {
case "POST": // 消息处理
msgSignature1, timestampStr, nonce, err := parsePostURLQuery(queryValues)
if err != nil {
invalidRequestHandler.ServeInvalidRequest(w, r, err)
return
}
// 首先判断签名长度是否合法
if len(msgSignature1) != 40 {
err = fmt.Errorf("the length of msg_signature mismatch, have: %d, want: 40", len(msgSignature1))
invalidRequestHandler.ServeInvalidRequest(w, r, err)
return
}
timestamp, err := strconv.ParseInt(timestampStr, 10, 64)
if err != nil {
err = errors.New("can not parse timestamp to int64: " + timestampStr)
invalidRequestHandler.ServeInvalidRequest(w, r, err)
return
}
// 解析 RequestHttpBody
var requestHttpBody RequestHttpBody
if err := xml.NewDecoder(r.Body).Decode(&requestHttpBody); err != nil {
invalidRequestHandler.ServeInvalidRequest(w, r, err)
return
}
haveCorpId := requestHttpBody.CorpId
wantCorpId := agentServer.CorpId()
if len(haveCorpId) != len(wantCorpId) {
err = fmt.Errorf("the RequestHttpBody's ToUserName mismatch, have: %s, want: %s", haveCorpId, wantCorpId)
invalidRequestHandler.ServeInvalidRequest(w, r, err)
return
}
if subtle.ConstantTimeCompare([]byte(haveCorpId), []byte(wantCorpId)) != 1 {
err = fmt.Errorf("the RequestHttpBody's ToUserName mismatch, have: %s, want: %s", haveCorpId, wantCorpId)
invalidRequestHandler.ServeInvalidRequest(w, r, err)
return
}
haveAgentId := requestHttpBody.AgentId
wantAgentId := agentServer.AgentId()
if haveAgentId != wantAgentId && haveAgentId != 0 {
err = fmt.Errorf("the RequestHttpBody's AgentId mismatch, have: %d, want: %d", haveAgentId, wantAgentId)
invalidRequestHandler.ServeInvalidRequest(w, r, err)
return
}
// 此时
// 要么 haveAgentId == wantAgentId,
// 要么 haveAgentId == 0
agentToken := agentServer.Token()
// 验证签名
msgSignature2 := util.MsgSign(agentToken, timestampStr, nonce, requestHttpBody.EncryptedMsg)
if subtle.ConstantTimeCompare([]byte(msgSignature1), []byte(msgSignature2)) != 1 {
err = fmt.Errorf("check signature failed, input: %s, local: %s", msgSignature1, msgSignature2)
invalidRequestHandler.ServeInvalidRequest(w, r, err)
return
}
// 解密
EncryptedMsgBytes, err := base64.StdEncoding.DecodeString(requestHttpBody.EncryptedMsg)
if err != nil {
invalidRequestHandler.ServeInvalidRequest(w, r, err)
return
}
AESKey := agentServer.CurrentAESKey()
Random, RawMsgXML, err := util.AESDecryptMsg(EncryptedMsgBytes, wantCorpId, AESKey)
if err != nil {
// 尝试用上一次的 AESKey 来解密
LastAESKey := agentServer.LastAESKey()
if bytes.Equal(AESKey[:], LastAESKey[:]) || bytes.Equal(zeroAESKey[:], LastAESKey[:]) {
invalidRequestHandler.ServeInvalidRequest(w, r, err)
return
}
AESKey = LastAESKey // NOTE
Random, RawMsgXML, err = util.AESDecryptMsg(EncryptedMsgBytes, wantCorpId, AESKey)
if err != nil {
invalidRequestHandler.ServeInvalidRequest(w, r, err)
return
}
}
// 解密成功, 解析 MixedMessage
var MixedMsg MixedMessage
if err = xml.Unmarshal(RawMsgXML, &MixedMsg); err != nil {
invalidRequestHandler.ServeInvalidRequest(w, r, err)
return
}
// 安全考虑再次验证
if haveCorpId != MixedMsg.ToUserName {
err = fmt.Errorf("the RequestHttpBody's ToUserName(==%s) mismatch the MixedMessage's ToUserName(==%s)", haveCorpId, MixedMsg.ToUserName)
invalidRequestHandler.ServeInvalidRequest(w, r, err)
return
}
if haveAgentId != MixedMsg.AgentId {
err = fmt.Errorf("the RequestHttpBody's AgentId(==%d) mismatch the MixedMessage's AgengId(==%d)", haveAgentId, MixedMsg.AgentId)
invalidRequestHandler.ServeInvalidRequest(w, r, err)
return
}
// 如果是订阅/取消订阅 整个企业号, haveAgentId == 0
if haveAgentId != wantAgentId {
if MixedMsg.MsgType == "event" &&
(MixedMsg.Event == "subscribe" || MixedMsg.Event == "unsubscribe") {
// do nothing
} else {
err = fmt.Errorf("the RequestHttpBody's AgentId mismatch, have: %d, want: %d", haveAgentId, wantAgentId)
invalidRequestHandler.ServeInvalidRequest(w, r, err)
return
}
}
// 成功, 交给 MessageHandler
r := &Request{
HttpRequest: r,
QueryValues: queryValues,
MsgSignature: msgSignature1,
Timestamp: timestamp,
Nonce: nonce,
RawMsgXML: RawMsgXML,
MixedMsg: &MixedMsg,
AESKey: AESKey,
Random: Random,
CorpId: haveCorpId,
AgentId: haveAgentId,
AgentToken: agentToken,
}
agentServer.MessageHandler().ServeMessage(w, r)
case "GET": // 首次验证
msgSignature1, timestamp, nonce, encryptedMsg, err := parseGetURLQuery(queryValues)
if err != nil {
invalidRequestHandler.ServeInvalidRequest(w, r, err)
return
}
// 验证签名
if len(msgSignature1) != 40 {
err = fmt.Errorf("the length of msg_signature mismatch, have: %d, want: 40", len(msgSignature1))
invalidRequestHandler.ServeInvalidRequest(w, r, err)
return
}
msgSignature2 := util.MsgSign(agentServer.Token(), timestamp, nonce, encryptedMsg)
if subtle.ConstantTimeCompare([]byte(msgSignature1), []byte(msgSignature2)) != 1 {
err = fmt.Errorf("check signature failed, input: %s, local: %s", msgSignature1, msgSignature2)
invalidRequestHandler.ServeInvalidRequest(w, r, err)
return
}
// 解密
EncryptedMsgBytes, err := base64.StdEncoding.DecodeString(encryptedMsg)
if err != nil {
invalidRequestHandler.ServeInvalidRequest(w, r, err)
return
}
CorpId := agentServer.CorpId()
AESKey := agentServer.CurrentAESKey()
_, echostr, err := util.AESDecryptMsg(EncryptedMsgBytes, CorpId, AESKey)
if err != nil {
invalidRequestHandler.ServeInvalidRequest(w, r, err)
return
}
w.Write(echostr)
}
}