-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathpackethandler.go
207 lines (183 loc) · 6.52 KB
/
packethandler.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
// Package o3 handler functions for individual incoming packets. All functions here are called from
// communicationhandler. Functions in here use packetparser to parse packets into their
// respective structs. Any action required upon receiving a specific packet is then per-
// formed within its handler like updating nonces and storing keys in the session context.
// Errors in underlying functions bubble up to here in the form of panics and are passed
// on to communicationhandler for central conversion to go errors.
package o3
import (
"bytes"
"encoding/binary"
"fmt"
"encoding/hex"
"golang.org/x/crypto/nacl/box"
)
func handlerPanicHandler(context string, i interface{}) error {
if _, ok := i.(string); ok {
return fmt.Errorf("%s: error occurred handling %s", context, i)
}
return fmt.Errorf("%s: unknown handling error occurred: %#v", context, i)
}
//not needed at the client
func (sc *SessionContext) handleClientHello(buf *bytes.Buffer) {}
func (sc *SessionContext) handleServerHello(buf *bytes.Buffer) {
defer func() {
if r := recover(); r != nil {
panic(handlerPanicHandler("server hello", r))
}
}()
sh := parseServerHello(buf)
sc.serverNonce.initialize(sh.NoncePrefix, 1)
plaintext, ok := box.Open(nil, sh.Ciphertext[:], sc.serverNonce.bytes(), &sc.serverLPK, &sc.clientSSK)
if !ok {
panic(handlerPanicHandler("handleServerHello", "decrypting cyphertext"))
}
rdr := bytes.NewBuffer(plaintext)
serverSPK, clientNP := parseServerHelloPayload(rdr)
sc.serverSPK = serverSPK
if clientNP != sc.clientNonce.prefix() {
panic("client nonce check failed")
}
}
func (sc *SessionContext) handleHandshakeAck(buf *bytes.Buffer) {
defer func() {
if r := recover(); r != nil {
panic(handlerPanicHandler("handshake acknowledgement", r))
}
}()
sc.serverNonce.setCounter(2)
_, ok := box.Open(nil, buf.Bytes(), sc.serverNonce.bytes(), &sc.serverSPK, &sc.clientSSK)
if !ok {
panic("error decrypting payload")
}
//TODO check zero content?
}
func (sc *SessionContext) handleAuthResponse(buf *bytes.Buffer) {}
func (sc *SessionContext) handleAckMsg(buf *bytes.Buffer) {}
// handleDataMsg
func (sc *SessionContext) handleClientServerMsg(buf *bytes.Buffer) interface{} {
defer func() {
if r := recover(); r != nil {
panic(handlerPanicHandler("handleDataMsg", r))
}
}()
sc.serverNonce.increaseCounter()
plaintext, ok := box.Open(nil, buf.Bytes(), sc.serverNonce.bytes(), &sc.serverSPK, &sc.clientSSK)
if !ok {
panic("Cannot decrypt received packet")
}
var pt pktType
//TODO this can be done nicer
binary.Read(bytes.NewReader(plaintext[:4]), binary.LittleEndian, &pt)
switch pt {
case deliveringMsg:
// It is an e2e message!
msgPkt := parseMsgPkt(bytes.NewBuffer(plaintext))
// Find the sender in our contacts, because we need their public key
sender, ok := sc.ID.Contacts.Get(msgPkt.Sender.String())
if !ok {
var tr ThreemaRest
var err error
// TODO: Add to local contacts?
sender, err = tr.GetContactByID(msgPkt.Sender)
if err != nil {
panic("Sender's PublicKey could not be found!")
}
sc.ID.Contacts.Add(sender)
}
// Decrypt using our private and their public key
msgPkt.Plaintext, ok = box.Open(nil, msgPkt.Ciphertext, msgPkt.Nonce.bytes(), &sender.LPK, &sc.ID.LSK)
if !ok {
panic("Cannot decrypt e2e MSG!")
}
return msgPkt
case serverAck:
// It is an ACK for a message we sent
return parseAckPkt(bytes.NewBuffer(plaintext))
case echoMsg:
// It is an echo reply
return parseEchoPkt(bytes.NewBuffer(plaintext))
case connEstablished:
// We have received all enqueued messages
return parseConnEstPkt(bytes.NewBuffer(plaintext))
case douplicateConnectionError:
return errDuplicateConn
default:
fmt.Printf("Unknown PktType: %.2x", plaintext)
return nil
}
}
//handleMessagePacket parses a messagePacket and returns the according Message type (ImageMessage, TextMessage etc.)
func (sc *SessionContext) handleMessagePacket(mp messagePacket) (Message, error) {
// DEBUG
//fmt.Print(hex.Dump(mp.Plaintext))
buf := bytes.NewBuffer(mp.Plaintext)
var message Message
mt := parseMessageType(buf)
switch mt {
case TEXTMESSAGE:
message = TextMessage{
messageHeader: newMsgHdrFromPkt(mp),
textMessageBody: parseTextMessage(buf)}
case IMAGEMESSAGE:
message = ImageMessage{
messageHeader: newMsgHdrFromPkt(mp),
imageMessageBody: parseImageMessage(buf)}
case AUDIOMESSAGE:
message = AudioMessage{
messageHeader: newMsgHdrFromPkt(mp),
audioMessageBody: parseAudioMessage(buf)}
case GROUPTEXTMESSAGE:
message = GroupTextMessage{
groupMessageHeader: parseGroupMessageHeader(buf),
TextMessage: TextMessage{
messageHeader: newMsgHdrFromPkt(mp),
textMessageBody: parseTextMessage(buf)}}
case GROUPIMAGEMESSAGE:
message = GroupImageMessage{
groupMessageHeader: parseGroupMessageHeader(buf),
messageHeader: newMsgHdrFromPkt(mp),
groupImageMessageBody: parseGroupImageMessage(buf)}
case GROUPSETNAMEMESSAGE:
message = GroupManageSetNameMessage{
groupManageMessageHeader: parseGroupManageMessageHeader(buf),
messageHeader: newMsgHdrFromPkt(mp),
groupManageSetNameMessageBody: parseGroupManageSetNameMessage(buf)}
case GROUPSETIMAGEMESSAGE:
message = GroupManageSetImageMessage{
groupManageMessageHeader: parseGroupManageMessageHeader(buf),
messageHeader: newMsgHdrFromPkt(mp),
groupImageMessageBody: parseGroupImageMessage(buf)}
case GROUPSETMEMEBERSMESSAGE:
message = GroupManageSetMembersMessage{
groupManageMessageHeader: parseGroupManageMessageHeader(buf),
messageHeader: newMsgHdrFromPkt(mp),
groupManageSetMembersMessageBody: parseGroupManageSetMembersMessage(buf)}
case GROUPMEMBERLEFTMESSAGE:
fmt.Println(hex.Dump(buf.Bytes()))
message = GroupMemberLeftMessage{
messageHeader: newMsgHdrFromPkt(mp),
groupMessageHeader: parseGroupMessageHeader(buf)}
case DELIVERYRECEIPT:
message = DeliveryReceiptMessage{
messageHeader: newMsgHdrFromPkt(mp),
deliveryReceiptMessageBody: parseDeliveryReceipt(buf)}
case TYPINGNOTIFICATION:
message = TypingNotificationMessage{
messageHeader: newMsgHdrFromPkt(mp),
typingNotificationBody: parseTypingNotification(buf)}
default:
fmt.Printf("\n%2x\n", buf)
fmt.Printf("\n%s\n", buf)
return nil, fmt.Errorf("o3: unknown MessageType: %d", mt)
}
return message, nil
}
func newMsgHdrFromPkt(mp messagePacket) messageHeader {
return messageHeader{
sender: mp.Sender,
recipient: mp.Recipient,
id: mp.ID,
time: mp.Time,
pubNick: mp.PubNick}
}