forked from janimo/textsecure
/
server.go
381 lines (335 loc) · 8.81 KB
/
server.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
// Copyright (c) 2014 Canonical Ltd.
// Licensed under the GPLv3, see the COPYING file for details.
package textsecure
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/golang/protobuf/proto"
"github.com/janimo/textsecure/axolotl"
"github.com/janimo/textsecure/protobuf"
)
var (
createAccountPath = "/v1/accounts/%s/code/%s"
verifyAccountPath = "/v1/accounts/code/%s"
prekeyMetadataPath = "/v2/keys/"
prekeyPath = "/v2/keys/%s"
prekeyDevicePath = "/v2/keys/%s/%s"
signedPrekeyPath = "/v2/keys/signed"
provisioningCodePath = "/v1/devices/provisioning/code"
provisioningMessagePath = "/v1/provisioning/%s"
directoryTokensPath = "/v1/directory/tokens"
directoryVerifyPath = "/v1/directory/%s"
messagePath = "/v1/messages/%s"
acknowledgeMessagePath = "/v1/messages/%s/%d"
receiptPath = "/v1/receipt/%s/%d"
allocateAttachmentPath = "/v1/attachments/"
attachmentPath = "/v1/attachments/%d"
)
// RegistrationInfo holds the data required to be identified by and
// to communicate with the push server.
// The data is generated once at install time and stored locally.
type RegistrationInfo struct {
password string
registrationID uint32
signalingKey []byte
}
var registrationInfo RegistrationInfo
// Registration
func requestCode(tel, method string) (string, error) {
resp, err := transport.get(fmt.Sprintf(createAccountPath, method, tel))
if err != nil {
return "", err
}
// unofficial dev method, useful for development, with no telephony account needed on the server
if method == "dev" {
code := make([]byte, 7)
_, err = resp.Body.Read(code)
if err != nil {
return "", err
}
return string(code[:3]) + string(code[4:]), nil
}
return "", nil
}
type verificationData struct {
SignalingKey string `json:"signalingKey"`
RegistrationID uint32 `json:"registrationId"`
FetchesMessages bool `json:"fetchesMessages"`
}
func verifyCode(code string) error {
code = strings.Replace(code, "-", "", -1)
vd := verificationData{
SignalingKey: base64.StdEncoding.EncodeToString(registrationInfo.signalingKey),
FetchesMessages: true,
RegistrationID: registrationInfo.registrationID,
}
body, err := json.Marshal(vd)
if err != nil {
return err
}
resp, err := transport.putJSON(fmt.Sprintf(verifyAccountPath, code), body)
if err != nil {
return err
}
if resp.isError() {
return resp
}
return nil
}
// PUT /v2/keys/
func registerPreKeys() error {
body, err := json.MarshalIndent(preKeys, "", "")
if err != nil {
return err
}
resp, err := transport.putJSON(prekeyMetadataPath, body)
if err != nil {
return err
}
if resp.isError() {
return resp
}
return nil
}
// GET /v2/keys/{number}/{device_id}?relay={relay}
func getPreKeys(tel string) (*preKeyResponse, error) {
resp, err := transport.get(fmt.Sprintf(prekeyDevicePath, tel, "*"))
if err != nil {
return nil, err
}
if resp.isError() {
return nil, resp
}
dec := json.NewDecoder(resp.Body)
k := &preKeyResponse{}
dec.Decode(k)
return k, nil
}
// jsonContact is the data returned by the server for each registered contact
type jsonContact struct {
Token string `json:"token"`
Relay string `json:"relay"`
}
// GetRegisteredContacts returns the subset of the local contacts
// that are also registered with the server
func GetRegisteredContacts() ([]Contact, error) {
lc, err := client.GetLocalContacts()
if err != nil {
return nil, fmt.Errorf("Could not get local contacts :%s\n", err)
}
tokens := make([]string, len(lc))
m := make(map[string]Contact)
for i, c := range lc {
t := telToToken(c.Tel)
tokens[i] = t
m[t] = c
}
contacts := make(map[string][]string)
contacts["contacts"] = tokens
body, err := json.MarshalIndent(contacts, "", " ")
if err != nil {
return nil, err
}
resp, err := transport.putJSON(directoryTokensPath, body)
if err != nil {
return nil, err
}
if resp.isError() {
return nil, resp
}
dec := json.NewDecoder(resp.Body)
var jc map[string][]jsonContact
dec.Decode(&jc)
lc = make([]Contact, len(jc["contacts"]))
for i, c := range jc["contacts"] {
lc[i] = m[c.Token]
}
return lc, nil
}
// Attachment handling
type jsonAllocation struct {
ID uint64 `json:"id"`
Location string `json:"location"`
}
// GET /v1/attachments/
func allocateAttachment() (uint64, string, error) {
resp, err := transport.get(allocateAttachmentPath)
if err != nil {
return 0, "", err
}
dec := json.NewDecoder(resp.Body)
var a jsonAllocation
dec.Decode(&a)
return a.ID, a.Location, nil
}
func getAttachmentLocation(id uint64) (string, error) {
resp, err := transport.get(fmt.Sprintf(attachmentPath, id))
if err != nil {
return "", err
}
dec := json.NewDecoder(resp.Body)
var a jsonAllocation
dec.Decode(&a)
return a.Location, nil
}
// Messages
type jsonMessage struct {
Type int32 `json:"type"`
DestDeviceID uint32 `json:"destinationDeviceId"`
DestRegistrationID uint32 `json:"destinationRegistrationId"`
Body string `json:"body"`
Content string `json:"content"`
Relay string `json:"relay,omitempty"`
}
func createMessage(msg *outgoingMessage) ([]byte, error) {
dm := &textsecure.DataMessage{}
if msg.msg != "" {
dm.Body = &msg.msg
}
if msg.attachment != nil {
dm.Attachments = []*textsecure.AttachmentPointer{
&textsecure.AttachmentPointer{
Id: &msg.attachment.id,
ContentType: &msg.attachment.ct,
Key: msg.attachment.keys,
},
}
}
if msg.group != nil {
dm.Group = &textsecure.GroupContext{
Id: msg.group.id,
Type: &msg.group.typ,
Name: &msg.group.name,
Members: msg.group.members,
}
}
dm.Flags = &msg.flags
b, err := proto.Marshal(dm)
if err != nil {
return nil, err
}
return padMessage(b), nil
}
func padMessage(msg []byte) []byte {
l := (len(msg) + 160)
l = l - l%160
n := make([]byte, l)
copy(n, msg)
n[len(msg)] = 0x80
return n
}
func stripPadding(msg []byte) []byte {
for i := len(msg) - 1; i >= 0; i-- {
if msg[i] == 0x80 {
return msg[:i]
}
}
return msg
}
func makePreKeyBundle(tel string) (*axolotl.PreKeyBundle, error) {
pkr, err := getPreKeys(tel)
if err != nil {
return nil, err
}
ndev := len(pkr.Devices)
pkbs := make([]*axolotl.PreKeyBundle, ndev)
for i, d := range pkr.Devices {
if d.PreKey == nil {
return nil, fmt.Errorf("No prekey for contact %s, device %d\n", tel, i)
}
decPK, err := decodeKey(d.PreKey.PublicKey)
if err != nil {
return nil, err
}
decSPK, err := decodeKey(d.SignedPreKey.PublicKey)
if err != nil {
return nil, err
}
decSig, err := decodeSignature(d.SignedPreKey.Signature)
if err != nil {
return nil, err
}
decIK, err := decodeKey(pkr.IdentityKey)
if err != nil {
return nil, err
}
pkbs[i], err = axolotl.NewPreKeyBundle(
d.RegistrationID, d.DeviceID, d.PreKey.ID,
axolotl.NewECPublicKey(decPK), int32(d.SignedPreKey.ID), axolotl.NewECPublicKey(decSPK),
decSig, axolotl.NewIdentityKey(decIK))
if err != nil {
return nil, err
}
}
return pkbs[0], nil
}
type att struct {
id uint64
ct string
keys []byte
}
func buildMessage(msg *outgoingMessage) ([]jsonMessage, error) {
devid := uint32(1) //FIXME: support multiple destination devices
paddedMessage, err := createMessage(msg)
if err != nil {
return nil, err
}
recid := recID(msg.tel)
if !textSecureStore.ContainsSession(recid, devid) {
pkb, err := makePreKeyBundle(msg.tel)
if err != nil {
return nil, err
}
sb := axolotl.NewSessionBuilder(textSecureStore, textSecureStore, textSecureStore, textSecureStore, recid, pkb.DeviceID)
err = sb.BuildSenderSession(pkb)
if err != nil {
return nil, err
}
}
sc := axolotl.NewSessionCipher(textSecureStore, textSecureStore, textSecureStore, textSecureStore, recid, devid)
encryptedMessage, messageType, err := sc.SessionEncryptMessage(paddedMessage)
if err != nil {
return nil, err
}
rrID, err := sc.GetRemoteRegistrationID()
if err != nil {
return nil, err
}
messages := []jsonMessage{{
Type: messageType,
DestDeviceID: devid,
DestRegistrationID: rrID,
Body: base64.StdEncoding.EncodeToString(encryptedMessage),
}}
return messages, nil
}
// ErrRemoteGone is returned when the peer reinstalled and lost its session state.
var ErrRemoteGone = errors.New("The remote device is gone (probably reinstalled)")
func sendMessage(msg *outgoingMessage) error {
m := make(map[string]interface{})
bm, err := buildMessage(msg)
if err != nil {
return err
}
m["messages"] = bm
m["destination"] = msg.tel
body, err := json.MarshalIndent(m, "", " ")
if err != nil {
return err
}
resp, err := transport.putJSON(fmt.Sprintf(messagePath, msg.tel), body)
if err != nil {
return err
}
if resp.Status == 410 {
textSecureStore.DeleteSession(recID(msg.tel), uint32(1))
return ErrRemoteGone
}
if resp.isError() {
return resp
}
return nil
}