/
client.go
527 lines (498 loc) · 12.9 KB
/
client.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
// secureShare client lib
package client
import (
"bufio"
"bytes"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/cathalgarvey/go-minilock"
"github.com/cathalgarvey/go-minilock/taber"
"github.com/google/uuid"
"golang.org/x/crypto/scrypt"
"gopkg.in/yaml.v2"
"h12.me/socks"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"net/http/httputil"
"net/textproto"
"net/url"
"os/user"
"path/filepath"
"strings"
"github.com/scusi/secureShare/libs/client/addressBook"
"github.com/scusi/secureShare/libs/message"
)
const defaultURL = "https://securehare.scusi.io/"
var Debug bool
type Client struct {
PublicKey string // encodeID of the user
Keys *taber.Keys // minilock Keys
Salt []byte // salt used to scrypt the encodeID
Username string // scryped user encodeID
MachineID string // UUID for the local machine
MachineToken string // auth token for this machine
APIToken string // sessionID for API requests
URL string // URL of the API
Socksproxy string // socks5 proxy to connect to server
httpClient *http.Client // http.Client to talk to the API
}
func (c *Client) Do(r *http.Request) (resp *http.Response, err error) {
resp, err = c.httpClient.Do(r)
return
}
var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
func escapeQuotes(s string) string {
log.Printf("escaping '%s'\n", s)
return quoteEscaper.Replace(s)
}
type OptionFunc func(*Client) error
func SetURL(url string) OptionFunc {
return func(client *Client) error {
if url == "" {
err := fmt.Errorf("URL is empty\n")
return err
}
if strings.HasSuffix(url, "/") {
client.URL = url
} else {
client.URL = url + "/"
}
return nil
}
}
func SetSocksproxy(sproxy string) OptionFunc {
return func(client *Client) error {
if sproxy == "" {
err := fmt.Errorf("provided socksproxy is empty\n")
return err
}
client.Socksproxy = sproxy
return nil
}
}
func SetUsername(username string) OptionFunc {
return func(client *Client) error {
if username == "" {
err := fmt.Errorf("Username is empty\n")
return err
}
client.Username = username
return nil
}
}
func SetKeys(keys *taber.Keys) OptionFunc {
return func(client *Client) error {
client.Keys = keys
return nil
}
}
func SetAPIToken(token string) OptionFunc {
return func(client *Client) error {
if token == "" {
err := fmt.Errorf("APIToken is empty\n")
return err
}
client.APIToken = token
return nil
}
}
func New(options ...OptionFunc) (c *Client, err error) {
c = new(Client)
if uuid.SetNodeID(uuid.NodeID()) != true {
err = fmt.Errorf("Could not set nodeID")
return
}
u, err := uuid.NewUUID()
if err != nil {
err = fmt.Errorf("Could not create new UUID")
return
}
c.MachineID = hex.EncodeToString(u.NodeID())
c.URL = defaultURL
for _, option := range options {
if err := option(c); err != nil {
return nil, err
}
}
salt := make([]byte, 16)
_, err = rand.Read(salt)
if err != nil {
return nil, err
}
c.Salt = salt
if c.Socksproxy != "" {
dialSocksProxy := socks.DialSocksProxy(socks.SOCKS5, c.Socksproxy)
tr := &http.Transport{Dial: dialSocksProxy}
c.httpClient = &http.Client{Transport: tr}
} else {
c.httpClient = new(http.Client)
}
return c, nil
}
// ID - returns the clientID / secureShareUsername
func (c *Client) ID() (id string) {
dk, err := scrypt.Key([]byte(c.PublicKey), c.Salt, 1<<15, 8, 1, 32)
if err != nil {
log.Fatal(err)
}
return base64.URLEncoding.EncodeToString(dk)
}
// sets the http.Client to be used for requests to secureShareServer
func (c *Client) SetHttpClient(hc *http.Client) {
c.httpClient = hc
}
// UpdateKey - asks the secureShareServer for the actual key of a given user
func (c *Client) UpdateKey(username string) (pubKey string, err error) {
v := url.Values{}
v.Add("username", username)
req, err := http.NewRequest("GET", c.URL+"lookupKey?"+v.Encode(), nil)
if err != nil {
return
}
resp, err := c.httpClient.Do(req)
if err != nil {
return
}
if resp.StatusCode != 200 {
err = fmt.Errorf("ERROR: Server could not answer request.\n")
dump, errDump := httputil.DumpResponse(resp, true)
if errDump != nil {
log.Printf("ERROR: Could not dump Response\n")
} else {
log.Printf("Response:\n%s\n", dump)
}
} else {
pk, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(pk), err
}
return
}
func (c *Client) SaveConfigOnServer() (err error) {
// marshal client
clientBytes, err := json.Marshal(c)
if err != nil {
return
}
// encrypt clientBytes
// TODO: minilock.EncryptFileContents()
// create save request
bodyReader := bytes.NewReader(clientBytes)
urlString := c.URL + "config/" + c.Username
req, err := http.NewRequest("POST", urlString, bodyReader)
if err != nil {
return
}
if Debug {
dump, _ := httputil.DumpRequestOut(req, false)
log.Printf("%s", dump)
}
// send request
resp, err := c.Do(req)
if err != nil {
return
}
if Debug {
dump, _ := httputil.DumpResponse(resp, true)
log.Printf("%s", dump)
}
// check response
if resp.StatusCode != 200 {
log.Printf("status code (%d) is NOT OK\n", resp.StatusCode)
body, readErr := ioutil.ReadAll(resp.Body)
if readErr != nil {
return readErr
}
log.Printf("Server error: '%s'\n", body)
err = fmt.Errorf("Server error: '%s'\n", body)
return
}
// return
return
}
func (c *Client) GetConfigOnServer() (err error) {
urlString := c.URL + "config/" + c.Username
req, err := http.NewRequest("GET", urlString, nil)
if err != nil {
return
}
if Debug {
dump, _ := httputil.DumpRequestOut(req, false)
log.Printf("%s", dump)
}
// send request
resp, err := c.Do(req)
if err != nil {
return
}
if Debug {
dump, _ := httputil.DumpResponse(resp, true)
log.Printf("%s", dump)
}
// check response
if resp.StatusCode != 200 {
log.Printf("status code (%d) is NOT OK\n", resp.StatusCode)
body, readErr := ioutil.ReadAll(resp.Body)
if readErr != nil {
return readErr
}
log.Printf("Server error: '%s'\n", body)
err = fmt.Errorf("Server error: '%s'\n", body)
return
}
// read body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
/* // decrypt body
senderID, _, rr, err := minilock.DecryptFileContents(body, c.Keys)
if err != nil {
return
}
if senderID != c.Username {
err = fmt.Errorf("config senderID not correct: '%s' vs. '%s'\n", senderID, c.Username)
return
}
// unmarshal
err = json.Unmarshal(rr, c)
if err != nil {
return
}
*/
// unmarshal
err = json.Unmarshal(body, c)
if err != nil {
return
}
return
}
// Register - register a new user at the secureShareServer
func (c *Client) Register(pubID string) (user, token, mID, mToken string, err error) {
v := url.Values{}
v.Add("pubID", pubID)
v.Add("MachineID", c.MachineID)
// does not work
//req, err := http.NewRequest("POST", c.URL+"register", strings.NewReader(v.Encode()))
req, err := http.NewRequest("GET", c.URL+"register?"+v.Encode(), nil)
if err != nil {
return
}
if Debug {
dump, _ := httputil.DumpRequestOut(req, false)
log.Printf("%s", dump)
}
resp, err := c.Do(req)
if err != nil {
return
}
if Debug {
dump, _ := httputil.DumpResponse(resp, true)
log.Printf("%s", dump)
}
if resp.StatusCode != 200 {
log.Printf("status code (%d) is NOT OK\n", resp.StatusCode)
body, readErr := ioutil.ReadAll(resp.Body)
if readErr != nil {
return "", "", "", "", readErr
}
log.Printf("Server error: '%s'\n", body)
err = fmt.Errorf("Server error: '%s'\n", body)
return
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
// decrypt and parse response
registerResp := new(message.RegisterResponse)
// decrypt body
senderID, _, rr, err := minilock.DecryptFileContents(body, c.Keys)
if err != nil {
return
}
// TODO: check if senderID is the serverID
log.Printf("register response senderID: '%s'\n", senderID)
// unmarshal decrypted register response
err = yaml.Unmarshal(rr, registerResp)
if err != nil {
return
}
// return to client
return registerResp.Username, registerResp.APIToken,
registerResp.MachineID, registerResp.MachineToken, nil
}
// UploadFile will upload a given file for a given user on secureShare
func (c *Client) UploadFile(recipient string, data []byte) (fileID string, err error) {
recipientList := strings.Split(recipient, ",")
log.Printf("UploadFile: recipientList: %v\n", recipientList)
log.Printf("UploadFile: length of data: %d\n", len(data))
buf := bytes.NewReader(data)
log.Printf("UploadFile: data = %d byte\n", len(data))
fieldname := "file"
filename := "data.file"
//bodyReader, bodyWriter := io.Pipe()
var body bytes.Buffer
bodyWriter := bufio.NewWriter(&body)
mimeW := multipart.NewWriter(bodyWriter)
// WIP create a recipientList
rh := make(textproto.MIMEHeader)
rh.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"`, escapeQuotes("recipientList")))
//rh.Set("Content-Type", "multipart/form-data")
part, err := mimeW.CreatePart(rh)
if err != nil {
return
}
for _, recipient := range recipientList {
part.Write([]byte(recipient + "\n"))
}
fdct := mimeW.FormDataContentType()
fh := make(textproto.MIMEHeader)
fh.Set("Content-Disposition",
fmt.Sprintf(`form-data; name="%s"; filename="%s"`,
escapeQuotes(fieldname), escapeQuotes(filename)))
fh.Set("Content-Type", "application/octet-stream")
log.Printf("mime header: %s\n", fh)
part, err = mimeW.CreatePart(fh)
if err != nil {
return
}
log.Printf("new part created")
//n, err := part.Write(data)
n, err := io.Copy(part, buf)
if err != nil {
return
}
log.Printf("%d byte written to mime part\n", n)
mimeW.Close()
bodyWriter.Flush()
bodyReader := bufio.NewReader(&body)
// build http request
req, err := http.NewRequest("POST", c.URL+"upload/", bodyReader)
if err != nil {
return
}
req.Header.Add("Content-Type", fdct)
req.Header.Add("APIUsername", c.Username)
req.Header.Add("APIKey", c.APIToken)
/*
*/
if Debug {
dump, err := httputil.DumpRequestOut(req, false)
if err != nil {
log.Fatal(err)
}
log.Printf("%s", dump)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return "", err
}
if resp.StatusCode == 200 {
fileID, err := ioutil.ReadAll(resp.Body)
return string(fileID), err
} else {
err := fmt.Errorf("Request could not be processed by the server\n")
dump, errDump := httputil.DumpResponse(resp, true)
if errDump != nil {
log.Printf("Could not dump response: %s\n", errDump.Error())
}
log.Printf("RESPONSE:\n%s\n", dump)
return "", err
}
}
func (c *Client) List() (fileList string, err error) {
req, err := http.NewRequest("GET", c.URL+"list/", nil)
req.Header.Add("APIUsername", c.Username)
req.Header.Add("APIKey", c.APIToken)
if Debug {
dump, errDump := httputil.DumpRequestOut(req, true)
if errDump != nil {
log.Printf("Could not dump request '%s'\n", errDump.Error())
}
log.Printf("RequestDump:\n%s\n", dump)
}
resp, err := c.Do(req)
if err != nil {
return
}
if resp.StatusCode != 200 {
err = fmt.Errorf("Response is NOT OK, Status: %s\n", resp.Status)
dump, errDump := httputil.DumpResponse(resp, true)
if errDump != nil {
log.Printf("Could not dump response '%s'\n", errDump.Error())
}
log.Printf("ResponseDump:\n%s\n", dump)
return
}
list, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
return string(list), nil
}
func (c *Client) DownloadFile(fileID string) (filename string, fileContent []byte, err error) {
req, err := http.NewRequest("GET", c.URL+c.Username+"/"+fileID, nil)
req.Header.Add("APIUsername", c.Username)
req.Header.Add("APIKey", c.APIToken)
if Debug {
dump, errDump := httputil.DumpRequestOut(req, true)
if errDump != nil {
log.Printf("Could not dump request '%s'\n", errDump.Error())
}
log.Printf("RequestDump:\n%s\n", dump)
}
resp, err := c.Do(req)
if err != nil {
return
}
if resp.StatusCode != 200 {
err = fmt.Errorf("Response is NOT OK, Status: %s\n", resp.Status)
dump, errDump := httputil.DumpResponse(resp, true)
if errDump != nil {
log.Printf("Could not dump response '%s'\n", errDump.Error())
}
log.Printf("ResponseDump:\n%s\n", dump)
return
}
fileContent, err = ioutil.ReadAll(resp.Body)
if err != nil {
return
}
senderId, filename, content, err := minilock.DecryptFileContents(fileContent, c.Keys)
if err != nil {
log.Printf("decryption error: '%s'\n", err.Error())
}
log.Printf("SenderID was: %s\n", senderId)
return filename, content, err
}
func (c *Client) SaveAddressbook(a *addressbook.Addressbook) (err error) {
// save addressbook
// get user home dir
usr, err := user.Current()
if err != nil {
return
}
addressbookPath := filepath.Join(usr.HomeDir, ".config", "secureshare", "client", c.Username)
addressbookPath = filepath.Join(addressbookPath, "addressbook.yml")
adata, err := yaml.Marshal(&a)
if err != nil {
return
}
if Debug {
log.Printf("addrbook to save: %s\n", adata)
}
err = ioutil.WriteFile(addressbookPath, adata, 0700)
if err != nil {
return
}
return
}