-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
message.go
218 lines (174 loc) · 6.6 KB
/
message.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
217
218
package stun
import (
"bytes"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"encoding/binary"
"errors"
"fmt"
"hash/crc32"
"strings"
"github.com/adalkiran/webrtc-nuts-and-bolts/src/config"
)
var (
//errInvalidTURNFrame = errors.New("data is not a valid TURN frame, no STUN or ChannelData found")
errIncompleteTURNFrame = errors.New("data contains incomplete STUN or TURN frame")
)
type Message struct {
MessageType MessageType
TransactionID [TransactionIDSize]byte
Attributes map[AttributeType]Attribute
RawMessage []byte
}
const (
magicCookie = 0x2112A442
messageHeaderSize = 20
TransactionIDSize = 12 // 96 bit
stunHeaderSize = 20
hmacSignatureSize = 20
fingerprintSize = 4
fingerprintXorMask = 0x5354554e
)
func (m Message) String() string {
transactionIDStr := base64.StdEncoding.EncodeToString(m.TransactionID[:])
attrsStr := ""
for _, a := range m.Attributes {
attrsStr += fmt.Sprintf("%s ", strings.ReplaceAll(a.String(), "\r", " "))
}
return fmt.Sprintf("%s id=%s attrs=%s", m.MessageType, transactionIDStr, attrsStr)
}
func IsMessage(buf []byte, offset int, arrayLen int) bool {
return arrayLen >= messageHeaderSize && binary.BigEndian.Uint32(buf[offset+4:offset+8]) == magicCookie
}
func DecodeMessage(buf []byte, offset int, arrayLen int) (*Message, error) {
if arrayLen < stunHeaderSize {
return nil, errIncompleteTURNFrame
}
offsetBackup := offset
messageType := binary.BigEndian.Uint16(buf[offset : offset+2])
offset += 2
messageLength := int(binary.BigEndian.Uint16(buf[offset : offset+2]))
offset += 2
// Adding message cookie length
offset += 4
result := new(Message)
result.RawMessage = buf[offsetBackup : offsetBackup+arrayLen]
result.MessageType = decodeMessageType(messageType)
copy(result.TransactionID[:], buf[offset:offset+TransactionIDSize])
offset += TransactionIDSize
result.Attributes = map[AttributeType]Attribute{}
for offset-stunHeaderSize < messageLength {
decodedAttr, err := DecodeAttribute(buf, offset, arrayLen)
if err != nil {
return nil, err
}
result.SetAttribute(*decodedAttr)
offset += decodedAttr.GetRawFullLength()
if decodedAttr.GetRawDataLength()%4 > 0 {
offset += 4 - decodedAttr.GetRawDataLength()%4
}
}
return result, nil
}
func calculateHmac(binMsg []byte, pwd string) []byte {
key := []byte(pwd)
messageLength := uint16(len(binMsg) + attributeHeaderSize + hmacSignatureSize - messageHeaderSize)
binary.BigEndian.PutUint16(binMsg[2:4], messageLength)
mac := hmac.New(sha1.New, key)
mac.Write(binMsg)
return mac.Sum(nil)
}
func calculateFingerprint(binMsg []byte) []byte {
result := make([]byte, 4)
messageLength := uint16(len(binMsg) + attributeHeaderSize + fingerprintSize - messageHeaderSize)
binary.BigEndian.PutUint16(binMsg[2:4], messageLength)
binary.BigEndian.PutUint32(result, crc32.ChecksumIEEE(binMsg)^fingerprintXorMask)
return result
}
func (m *Message) preEncode() {
// https://github.com/jitsi/ice4j/blob/32a8aadae8fde9b94081f8d002b6fda3490c20dc/src/main/java/org/ice4j/message/Message.java#L1015
delete(m.Attributes, AttrMessageIntegrity)
delete(m.Attributes, AttrFingerprint)
m.Attributes[AttrSoftware] = *createAttrSoftware(config.Val.Server.SoftwareName)
}
func (m *Message) postEncode(encodedMessage []byte, dataLength int, pwd string) []byte {
// https://github.com/jitsi/ice4j/blob/32a8aadae8fde9b94081f8d002b6fda3490c20dc/src/main/java/org/ice4j/message/Message.java#L1015
messageIntegrityAttr := &Attribute{
AttributeType: AttrMessageIntegrity,
Value: calculateHmac(encodedMessage, pwd),
}
encodedMessageIntegrity := messageIntegrityAttr.Encode()
encodedMessage = append(encodedMessage, encodedMessageIntegrity...)
messageFingerprint := &Attribute{
AttributeType: AttrFingerprint,
Value: calculateFingerprint(encodedMessage),
}
encodedFingerprint := messageFingerprint.Encode()
encodedMessage = append(encodedMessage, encodedFingerprint...)
binary.BigEndian.PutUint16(encodedMessage[2:4], uint16(dataLength+len(encodedMessageIntegrity)+len(encodedFingerprint)))
return encodedMessage
}
func (m *Message) Encode(pwd string) []byte {
m.preEncode()
// https://github.com/jitsi/ice4j/blob/311a495b21f38cc2dfcc4f7118dab96b8134aed6/src/main/java/org/ice4j/message/Message.java#L907
var encodedAttrs []byte
for _, attr := range m.Attributes {
encodedAttr := attr.Encode()
encodedAttrs = append(encodedAttrs, encodedAttr...)
}
result := make([]byte, messageHeaderSize+len(encodedAttrs))
binary.BigEndian.PutUint16(result[0:2], m.MessageType.Encode())
binary.BigEndian.PutUint16(result[2:4], uint16(len(encodedAttrs)))
binary.BigEndian.PutUint32(result[4:8], magicCookie)
copy(result[8:20], m.TransactionID[:])
copy(result[20:], encodedAttrs)
result = m.postEncode(result, len(encodedAttrs), pwd)
return result
}
func (m *Message) Validate(ufrag string, pwd string) {
// https://github.com/jitsi/ice4j/blob/311a495b21f38cc2dfcc4f7118dab96b8134aed6/src/main/java/org/ice4j/stack/StunStack.java#L1254
userNameAttr, okUserName := m.Attributes[AttrUserName]
if okUserName {
userName := strings.Split(string(userNameAttr.Value), ":")[0]
if userName != ufrag {
panic("Message not valid: UserName!")
}
}
if messageIntegrityAttr, ok := m.Attributes[AttrMessageIntegrity]; ok {
if !okUserName {
panic("Message not valid: missing username!")
}
binMsg := make([]byte, messageIntegrityAttr.OffsetInMessage)
copy(binMsg, m.RawMessage[0:messageIntegrityAttr.OffsetInMessage])
calculatedHmac := calculateHmac(binMsg, pwd)
if !bytes.Equal(calculatedHmac, messageIntegrityAttr.Value) {
panic(fmt.Sprintf("Message not valid: MESSAGE-INTEGRITY not valid expected: %v , received: %v not compatible!", calculatedHmac, messageIntegrityAttr.Value))
}
}
if fingerprintAttr, ok := m.Attributes[AttrFingerprint]; ok {
binMsg := make([]byte, fingerprintAttr.OffsetInMessage)
copy(binMsg, m.RawMessage[0:fingerprintAttr.OffsetInMessage])
calculatedFingerprint := calculateFingerprint(binMsg)
if !bytes.Equal(calculatedFingerprint, fingerprintAttr.Value) {
panic(fmt.Sprintf("Message not valid: FINGERPRINT not valid expected: %v , received: %v not compatible!", calculatedFingerprint, fingerprintAttr.Value))
}
}
}
func (m *Message) SetAttribute(attr Attribute) {
m.Attributes[attr.AttributeType] = attr
}
func createAttrSoftware(software string) *Attribute {
return &Attribute{
AttributeType: AttrSoftware,
Value: []byte(software),
}
}
func NewMessage(messageType MessageType, transactionID [12]byte) *Message {
result := &Message{
MessageType: messageType,
TransactionID: transactionID,
Attributes: map[AttributeType]Attribute{},
}
return result
}