This repository has been archived by the owner on Dec 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
417 lines (321 loc) · 8.67 KB
/
session.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
package gosn
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"io"
"regexp"
"strings"
"syscall"
keyring "github.com/zalando/go-keyring"
"golang.org/x/crypto/ssh/terminal"
"github.com/spf13/viper"
)
const (
SNServerURL = "https://sync.standardnotes.org"
KeyringApplicationName = "session"
KeyringService = "StandardNotesCLI"
MsgSessionRemovalSuccess = "session removed successfully"
MsgSessionRemovalFailure = "failed to remove session"
)
func GetCredentials(inServer string) (email, password, apiServer, errMsg string) {
switch {
case viper.GetString("email") != "":
email = viper.GetString("email")
default:
fmt.Print("email: ")
_, err := fmt.Scanln(&email)
if err != nil || len(strings.TrimSpace(email)) == 0 {
errMsg = "email required"
return
}
}
if viper.GetString("password") != "" {
password = viper.GetString("password")
} else {
fmt.Print("password: ")
bytePassword, err := terminal.ReadPassword(int(syscall.Stdin))
fmt.Println()
if err == nil {
password = string(bytePassword)
} else {
errMsg = err.Error()
return
}
if strings.TrimSpace(password) == "" {
errMsg = "password not defined"
}
}
switch {
case inServer != "":
apiServer = inServer
case viper.GetString("server") != "":
apiServer = viper.GetString("server")
default:
apiServer = SNServerURL
}
return email, password, apiServer, errMsg
}
// encrypt string to base64 crypto using AES
func Encrypt(key []byte, text string) string {
key = padToAESBlockSize(key)
plaintext := []byte(text)
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
panic(err)
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
// convert to base64
return base64.URLEncoding.EncodeToString(ciphertext)
}
func GetSessionFromKeyring(k keyring.Keyring) (s string, err error) {
if k == nil {
return keyring.Get(KeyringService, KeyringApplicationName)
}
return k.Get(KeyringService, KeyringApplicationName)
}
func AddSession(snServer, inKey string, k keyring.Keyring) (res string, err error) {
// check if session exists in keyring
var s string
s, err = GetSessionFromKeyring(k)
// only return an error if there's an issue accessing the keyring
if err != nil && !strings.Contains(err.Error(), "secret not found in keyring") {
return
}
if inKey == "." {
var byteKey []byte
fmt.Print("session key: ")
byteKey, err = terminal.ReadPassword(int(syscall.Stdin))
if err != nil {
return
}
inKey = string(byteKey)
fmt.Println()
}
if s != "" {
fmt.Print("replace existing session (y|n): ")
var resp string
_, err := fmt.Scanln(&resp)
if err != nil || strings.ToLower(resp) != "y" {
// do nothing
return "", nil
}
}
var session Session
var email string
session, email, err = GetSessionFromUser(snServer)
if err != nil {
return fmt.Sprint("failed to get session: ", err), err
}
rS := makeSessionString(email, session)
if inKey != "" {
key := []byte(inKey)
rS = Encrypt(key, MakeSessionString(email, session))
}
err = writeSession(rS, k)
if err != nil {
return fmt.Sprint("failed to set session: ", err), err
}
return "session added successfully", err
}
func writeSession(s string, k keyring.Keyring) error {
if k == nil {
return keyring.Set(KeyringService, KeyringApplicationName, s)
}
return k.Set(KeyringService, KeyringApplicationName, s)
}
func makeSessionString(email string, session Session) string {
return fmt.Sprintf("%s;%s;%s;%s;%s", email, session.Server, session.Token, session.Ak, session.Mk)
}
func SessionExists(k keyring.Keyring) error {
s, err := GetSessionFromKeyring(k)
if err != nil {
return err
}
if len(s) == 0 {
return errors.New("session is empty")
}
return nil
}
// RemoveSession removes the SN session from the keyring
func RemoveSession(k keyring.Keyring) string {
var err error
if err = SessionExists(k); err != nil {
return fmt.Sprintf("%s: %s", MsgSessionRemovalFailure, err.Error())
}
if k == nil {
err = keyring.Delete(KeyringService, KeyringApplicationName)
} else {
err = k.Delete(KeyringService, KeyringApplicationName)
}
if err != nil {
return fmt.Sprintf("%s: %s", MsgSessionRemovalFailure, err.Error())
}
return MsgSessionRemovalSuccess
}
func MakeSessionString(email string, session Session) string {
return fmt.Sprintf("%s;%s;%s;%s;%s", email, session.Server, session.Token, session.Ak, session.Mk)
}
func GetSessionFromUser(server string) (Session, string, error) {
var sess Session
var err error
var email, password, apiServer, errMsg string
email, password, apiServer, errMsg = GetCredentials(server)
if errMsg != "" {
if strings.Contains(errMsg, "password not defined") {
err = fmt.Errorf("password not defined")
} else {
fmt.Printf("\nerror: %s\n\n", errMsg)
}
return sess, email, err
}
sess, err = CliSignIn(email, password, apiServer)
if err != nil {
return sess, email, err
}
return sess, email, err
}
func GetSession(loadSession bool, sessionKey, server string) (session Session, email string, err error) {
if loadSession {
var rawSess string
rawSess, err = keyring.Get(KeyringService, KeyringApplicationName)
if err != nil {
return
}
if !isUnencryptedSession(rawSess) {
if sessionKey == "" {
var byteKey []byte
fmt.Print("session key: ")
byteKey, err = terminal.ReadPassword(int(syscall.Stdin))
if err != nil {
return
}
fmt.Println()
if len(byteKey) == 0 {
err = fmt.Errorf("key not provided")
return
}
sessionKey = string(byteKey)
}
if rawSess, err = Decrypt([]byte(sessionKey), rawSess); err != nil {
return
}
}
email, session, err = ParseSessionString(rawSess)
if err != nil {
return
}
} else {
session, email, err = GetSessionFromUser(server)
if err != nil {
return
}
}
return session, email, err
}
func isUnencryptedSession(in string) bool {
re := regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
if len(strings.Split(in, ";")) == 5 && re.MatchString(strings.Split(in, ";")[0]) {
return true
}
return false
}
func ParseSessionString(in string) (email string, session Session, err error) {
if !isUnencryptedSession(in) {
err = errors.New("session invalid, or encrypted and key was not provided")
return
}
parts := strings.Split(in, ";")
email = parts[0]
session = Session{
Token: parts[2],
Mk: parts[4],
Ak: parts[3],
Server: parts[1],
}
return
}
// decrypt from base64 to decrypted string
func Decrypt(key []byte, cryptoText string) (pt string, err error) {
var ciphertext []byte
if ciphertext, err = base64.URLEncoding.DecodeString(cryptoText); err != nil {
return
}
key = padToAESBlockSize(key)
var block cipher.Block
if block, err = aes.NewCipher(key); err != nil {
return
}
if len(ciphertext) < aes.BlockSize {
return "", errors.New("ciphertext too short")
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
stream.XORKeyStream(ciphertext, ciphertext)
pt = fmt.Sprintf("%s", ciphertext)
return
}
func getSessionContent(key, rawSession string) (session string, err error) {
// check if Session is encrypted
if len(strings.Split(rawSession, ";")) != 5 {
if key == "" {
fmt.Printf("encryption key: ")
var byteKey []byte
byteKey, err = terminal.ReadPassword(int(syscall.Stdin))
fmt.Println()
if err == nil {
key = string(byteKey)
}
if len(strings.TrimSpace(key)) == 0 {
err = fmt.Errorf("key required")
return
}
}
if session, err = Decrypt([]byte(key), rawSession); err != nil {
return
}
if len(strings.Split(session, ";")) != 5 {
err = fmt.Errorf("invalid session or wrong key provided")
}
} else {
session = rawSession
}
return
}
func SessionStatus(sKey string, k keyring.Keyring) (msg string, err error) {
var rawSession string
rawSession, err = GetSessionFromKeyring(k)
if err != nil {
return
}
if len(rawSession) == 0 {
return "", errors.New("keyring is empty")
}
// now decrypt if needed
var session string
session, err = getSessionContent(sKey, rawSession)
if err != nil {
if strings.Contains(err.Error(), "illegal base64") {
err = errors.New("stored session is corrupt")
}
return
}
var email string
email, _, err = ParseSessionString(session)
if err != nil {
msg = fmt.Sprint("failed to parse session: ", err)
return
}
msg = fmt.Sprint("session found: ", email)
return
}