-
Notifications
You must be signed in to change notification settings - Fork 19
/
user.go
485 lines (405 loc) · 11.4 KB
/
user.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
package sshego
import (
"bytes"
"fmt"
"os"
"path/filepath"
"regexp"
"sync"
"time"
scrypt "github.com/elithrar/simple-scrypt"
"github.com/glycerine/greenpack/msgp"
"github.com/glycerine/sshego/xendor/github.com/glycerine/xcryptossh"
"github.com/pquerna/otp"
)
//go:generate greenpack
// LoginRecord is per public key.
type LoginRecord struct {
FirstTm time.Time
LastTm time.Time
SeenCount int64
AcceptedCount int64
PubFinger string
}
func (r LoginRecord) String() string {
return fmt.Sprintf(`LoginRecord{ FirstTm:"%s", LastTm:"%s", SeenCount:%v, AcceptedCount: %v, PubFinger:"%s"}`,
r.FirstTm, r.LastTm, r.SeenCount, r.AcceptedCount, r.PubFinger)
}
// User represents a user authorized
// to login to the embedded sshd.
type User struct {
MyEmail string
MyFullname string
MyLogin string
PublicKeyPath string
PrivateKeyPath string
TOTPpath string
QrPath string
Issuer string
PublicKey ssh.PublicKey `msg:"-"`
SeenPubKey map[string]LoginRecord
ScryptedPassword []byte
ClearPw string // only on network, never on disk.
TOTPorig string
oneTime *TOTP
FirstLoginTime time.Time
LastLoginTime time.Time
LastLoginAddr string
IPwhitelist []string
DisabledAcct bool
mut sync.Mutex
}
func (u *User) String() string {
var buf bytes.Buffer
err := msgp.Encode(&buf, u)
panicOn(err)
var js bytes.Buffer
_, err = msgp.CopyToJSON(&js, &buf)
panicOn(err)
return js.String()
}
func NewUser() *User {
u := &User{
SeenPubKey: make(map[string]LoginRecord),
}
return u
}
// only these fields are actually saved/restored.
type HostDbPersist struct {
// Users: key is MyLogin; value is *User.
Users *AtomicUserMap `zid:"0"`
HostPrivateKeyPath string `zid:"1"`
}
type HostDb struct {
UserHomePrefix string
HostSshSigner ssh.Signer `msg:"-"`
cfg *SshegoConfig
Persist HostDbPersist
loadedFromDisk bool
saveMut sync.Mutex
userTcp TcpPort
db Filedb
}
func (h *HostDb) String() string {
return h.Persist.Users.String()
}
func (cfg *SshegoConfig) NewHostDb() error {
p("SshegoConfig.NewHostDB() called...")
h := &HostDb{
UserHomePrefix: "",
cfg: cfg,
Persist: HostDbPersist{
Users: NewAtomicUserMap(),
},
userTcp: TcpPort{Port: cfg.SshegoSystemMutexPort},
}
cfg.HostDb = h
return h.init()
}
func (h *HostDb) privpath() string {
return h.cfg.EmbeddedSSHdHostDbPath + ".hostkey"
}
func (h *HostDb) init() error {
h.Persist.HostPrivateKeyPath = h.privpath()
p("HostDb.init(): h.Persist.HostPrivateKeyPath = '%v'", h.Persist.HostPrivateKeyPath)
err := h.loadOrCreate()
return err
}
func (h *HostDb) generateHostKey() error {
p("generateHostKey called.")
err := h.gendir()
if err != nil {
return err
}
path := h.privpath()
bits := h.cfg.BitLenRSAkeys // default 4096
p("\n bits = %v\n", bits)
host, _ := os.Hostname()
_, signer, err := GenRSAKeyPair(path, bits, host)
if err != nil {
return err
}
h.HostSshSigner = signer
h.Persist.HostPrivateKeyPath = path
return nil
}
func (h *HostDb) gendir() error {
path := h.cfg.EmbeddedSSHdHostDbPath
p("HostDb.gendir has h.cfg.EmbeddedSSHdHostDbPath='%s'", h.cfg.EmbeddedSSHdHostDbPath)
if dirExists(path) {
return nil
}
err := os.MkdirAll(path, 0777)
if err != nil {
return fmt.Errorf("HostDb: MkdirAll on '%s' failed: %v",
path, err)
}
return nil
}
func makeway(path string) error {
dir := filepath.Dir(path)
return os.MkdirAll(dir, 0777)
}
func (h *HostDb) msgpath() string {
return h.cfg.EmbeddedSSHdHostDbPath + "/msgp.db"
}
func (h *HostDb) userpath(username string) string {
return h.cfg.EmbeddedSSHdHostDbPath + "/users/" + username
}
func (h *HostDb) Rsapath(username string) string {
return h.cfg.EmbeddedSSHdHostDbPath + "/users/" + username + "/id_rsa"
}
func (h *HostDb) toptpath(username string) string {
return h.cfg.EmbeddedSSHdHostDbPath + "/users/" + username + "/topt"
}
const skiplock = false
const lockit = true
// always opens h.msgpath()
func (h *HostDb) opendb() error {
if h.cfg.EmbeddedSSHdHostDbPath == "" {
panic("opendb() called on empty h.cfg.EmbeddedSSHdHostDbPath")
}
p("HostDb.opendb() has h.cfg.EmbeddedSSHdHostDbPath='%s'", h.cfg.EmbeddedSSHdHostDbPath)
if h.db.HostDb == nil {
err := h.gendir()
if err != nil {
return err
}
filedb, err := NewFiledb(h.msgpath())
if err != nil {
return fmt.Errorf("HostDb.opendb: create newFiledb at '%s' failed: %v",
h.msgpath(), err)
}
if filedb.HostDb != nil {
h.Persist = filedb.HostDb.Persist
filedb.HostDb = h
}
}
return nil
}
// There should only one writer to disk at a time...
// Let this be the main handshake/user auth goroutine
// that listens for sshd connections.
func (h *HostDb) save(lock bool) error {
if lock == lockit {
h.saveMut.Lock()
defer h.saveMut.Unlock()
}
h.db.filepath = h.msgpath()
err := h.db.storeHostDb(h)
if err != nil {
return fmt.Errorf("HostDb: h.db.storeHostDb(h) gave error = '%v'", err)
}
return nil
}
func (h *HostDb) loadOrCreate() error {
p("top of HostDb.loadOrCreate()...")
p("HostDb.loadOrCreate has h.cfg.EmbeddedSSHdHostDbPath='%s'", h.cfg.EmbeddedSSHdHostDbPath)
err := h.opendb()
if err != nil {
panic(err)
return fmt.Errorf("HostDb.loadOrCreate(): opendb() at path '%s' gave error '%v'",
h.msgpath(), err)
}
if h.Persist.HostPrivateKeyPath != "" && fileExists(h.Persist.HostPrivateKeyPath) {
p("h.Persist.HostPrivateKeyPath exists already... loaded HostDb from msgpath()='%s'. db = '%s'", h.msgpath(), h)
} else {
p("h.Persist.HostPrivateKeyPath = '%s' doesn't exist; make a host key...", h.msgpath())
// no db, so make a host key
err := h.generateHostKey()
if err != nil {
return err
}
err = h.save(skiplock)
if err != nil {
return fmt.Errorf("HostDb.Save MarshalMsg failed: %v", err)
}
}
h.loadedFromDisk = true
if fileExists(h.Persist.HostPrivateKeyPath) {
_, err := h.adoptNewHostKeyFromPath(h.Persist.HostPrivateKeyPath)
if err != nil {
return err
}
} else {
panic(fmt.Sprintf("missing h.Persist.HostPrivateKeyPath='%s'", h.Persist.HostPrivateKeyPath))
}
return nil
}
func (h *HostDb) adoptNewHostKeyFromPath(path string) (ssh.PublicKey, error) {
if !fileExists(path) {
return nil, fmt.Errorf("error in adoptNewHostKeyFromPath: path '%s' does not exist", path)
}
sshPrivKey, err := LoadRSAPrivateKey(path)
if err != nil {
return nil, fmt.Errorf("error in adoptNewHostKeyFromPath: loading"+
" path '%s' with LoadRSAPrivateKey() resulted in error '%v'", path, err)
}
// avoid data race:
h.saveMut.Lock()
h.HostSshSigner = sshPrivKey
h.saveMut.Unlock()
h.Persist.HostPrivateKeyPath = path
return sshPrivKey.PublicKey(), nil
}
func ScryptHash(password string) []byte {
hash, err := scrypt.GenerateFromPassword([]byte(password), scrypt.DefaultParams)
panicOn(err)
return hash
}
func (user *User) MatchingHashAndPw(password string) bool {
return nil == scrypt.CompareHashAndPassword(user.ScryptedPassword, []byte(password))
}
// emailAddressRE matches the mail addresses
// we admit. Since we are writing out
// to file system paths that include the email,
// we want to be restrictive.
//
var emailAddressREstring = `^([a-zA-Z0-9][\+-_.a-zA-Z0-9]{0,63})@([-_.a-zA-Z0-9]{1,255})$`
var emailAddressRE = regexp.MustCompile(emailAddressREstring)
// AddUser will use an existing extantRsaPath path to private key if provided, otherwise
// we make a new private/public key pair.
//
func (h *HostDb) AddUser(mylogin, myemail, pw, issuer, fullname, extantPrivateKeyPath string) (toptPath, qrPath, rsaPath string, err error) {
p("AddUser mylogin:'%v' pw:'%v' myemail:'%v'", mylogin, pw, myemail)
var valid bool
valid, err = h.ValidLogin(mylogin)
if !valid {
// err already set
return
}
p("h = %#v", h)
_, ok := h.Persist.Users.Get2(mylogin)
if ok {
err = fmt.Errorf("user already exists; manually -deluser '%s' first!",
mylogin)
return
} else {
p("brand new user '%s'", mylogin)
}
if extantPrivateKeyPath != "" {
rsaPath = extantPrivateKeyPath
} else {
rsaPath = h.Rsapath(mylogin)
}
// path := h.userpath(mylogin)
user := NewUser()
user.MyLogin = mylogin
user.MyEmail = myemail
user.ClearPw = pw
user.Issuer = issuer
user.MyFullname = fullname
if !h.cfg.SkipRSA {
user.PrivateKeyPath = rsaPath
user.PublicKeyPath = rsaPath + ".pub"
}
return h.finishUserBuildout(user)
}
func (h *HostDb) finishUserBuildout(user *User) (toptPath, qrPath, rsaPath string, err error) {
p("finishUserBuildout started: user.MyLogin:'%v' user.ClearPw:'%v' user.MyEmail:'%v' toptPath='%v'",
user.MyLogin, user.ClearPw, user.MyEmail, toptPath)
if !h.cfg.SkipPassphrase {
user.ScryptedPassword = ScryptHash(user.ClearPw)
}
if !h.cfg.SkipTOTP {
var w *TOTP
w, err = NewTOTP(user.MyEmail, fmt.Sprintf("%s/%s", user.MyLogin, user.Issuer))
if err != nil {
panic(err)
}
toptPath = h.toptpath(user.MyLogin)
user.TOTPpath = toptPath
makeway(toptPath)
user.TOTPorig = w.Key.String()
_, qrPath, err = w.SaveToFile(toptPath)
panicOn(err)
user.oneTime = w
user.QrPath = qrPath
}
if !h.cfg.SkipRSA {
// rsa private key already exists and supplied above?
if user.PrivateKeyPath != "" && fileExists(user.PrivateKeyPath) {
rsaPath = user.PrivateKeyPath
} else {
// need to make a new
rsaPath = h.Rsapath(user.MyLogin)
user.PrivateKeyPath = rsaPath
user.PublicKeyPath = rsaPath + ".pub"
makeway(rsaPath)
bits := h.cfg.BitLenRSAkeys // default 4096
var signer ssh.Signer
_, signer, err = GenRSAKeyPair(rsaPath, bits, user.MyEmail)
if err != nil {
return
}
user.PublicKeyPath = rsaPath + ".pub"
user.PublicKey = signer.PublicKey()
}
}
// don't save ClearPw to disk, and no need
// to ship it back b/c they supplied it in
// the first place (and we can't change it
// after the fact).
user.ClearPw = ""
// p("user = %#v", user)
h.Persist.Users.Set(user.MyLogin, user)
err = h.save(lockit)
return
}
func (h *HostDb) DelUser(mylogin string) error {
ok, err := h.ValidLogin(mylogin)
if !ok {
return err
}
/*
if !emailAddressRE.MatchString(mylogin) {
return fmt.Errorf("We are restrictive about what we "+
"accept as user email, and '%s' doesn't match "+
"our permitted regex '%s'", myemail, emailAddressREstring)
}
*/
p("DelUser %v", mylogin)
_, ok = h.Persist.Users.Get2(mylogin)
if ok {
// cleanup old
path := h.userpath(mylogin)
err := os.RemoveAll(path)
h.Persist.Users.Del(mylogin)
if err != nil {
panicOn(err)
}
return h.save(lockit)
}
return fmt.Errorf("error in -userdel '%s': user not found.", mylogin)
}
func (user *User) RestoreTotp() {
if user.oneTime == nil && user.TOTPorig != "" {
user.oneTime = &TOTP{}
w, err := otp.NewKeyFromURL(user.TOTPorig)
panicOn(err)
user.oneTime.Key = w
}
}
// UserExists is used by sshego/cmd/gosshtun/main.go
func (h *HostDb) UserExists(mylogin string) bool {
_, ok := h.Persist.Users.Get2(mylogin)
return ok
}
func (h *HostDb) ValidEmail(myemail string) (bool, error) {
if !emailAddressRE.MatchString(myemail) {
return false, fmt.Errorf("bad email: '%s' did not "+
"conform to '%s'. Please provide a conforming "+
"email if you wish to opt-in to passphrase "+
"backup to email.", myemail, emailAddressREstring)
}
return true, nil
}
var loginREstring = `^[a-z][-_a-z0-9]{0,31}$`
var loginRE = regexp.MustCompile(loginREstring)
func (h *HostDb) ValidLogin(login string) (bool, error) {
if !loginRE.MatchString(login) {
return false, fmt.Errorf("bad login: '%s' did not conform to '%s'",
login, loginREstring)
}
return true, nil
}