/
go-inn2-auth.go
722 lines (657 loc) · 19 KB
/
go-inn2-auth.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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
package main
/*
* https://www.eyrie.org/~eagle/software/inn/docs-2.7/external-auth.html
*
* nnrpd External Authentication Support
* A fundamental part of the readers.conf(5)-based authorization mechanism is the interface
* to external authenticator and resolver programs. This interface is documented below.
* INN ships with a number of such programs (all written in C, although any language can be used).
* Code for them can be found in authprogs/ of the source tree;
* the authenticators are installed to pathbin/auth/passwd,
* and the resolvers are installed to pathbin/auth/resolv.
*
*
* usage: ./go-inn2-auth -daemon=true
* TEST: echo -en "ClientAuthname: testuser1\r\nClientPassword: testpass1\r\nClientHost: localhost\r\nClientIP: 127.0.0.1\r\nClientPort: 5678\r\nLocalIP: 1.2.3.4\r\nLocalPort: 1234\r\n.\r\n" | ./go-inn2-auth | hexdump -c
* inn2.conf: ????
*
*/
import (
"bufio"
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"golang.org/x/crypto/bcrypt"
"io"
"io/ioutil"
"log"
"net"
"net/textproto"
"os"
"os/signal"
"strings"
"sync"
"time"
)
const (
LIMIT_REQUESTS int = 16 // parallel requests
RELOAD_USER int64 = 60 // reloads user.json
STDIN_SCAN_MAX int = 7 // do not change! refers to 'external-auth' lines
)
type CFG struct {
Settings SETTINGS
Json_Auth JSON_AUTH
Mongo_Auth MONGO_AUTH // TODO
Mysql_Auth MYSQL_AUTH // TODO
Pgsql_Auth PGSQL_AUTH // TODO
Redis_Auth REDIS_AUTH // TODO
} // end CFG
type SETTINGS struct {
Max_Workers int `json:"Max_Workers"`
STDIN_TIMEOUT int64 `json:"STDIN_TIMEOUT"`
Debug bool `json:"Debug"`
Debug_Daemon bool `json:"Debug_Daemon"`
Debug_CLI bool `json:"Debug_CLI"`
Daemon_Host string `json:"Daemon_Host"`
Daemon_TCP string `json:"Daemon_TCP"`
Daemon_Socket string `json:"Daemon_Socket"`
Daemon_Chmod int `json:"Daemon_Chmod"`
Auth_Mode string `json:"Auth_Mode"`
Pass_Mode string `json:"Pass_Mode"`
USER_Len_Min int `json:"USER_Len_Min"`
PASS_Len_Min int `json:"PASS_Len_Min"`
Logs_File string `json:"Logs_File"`
SSL_CRT string `json:"SSL_CRT"`
SSL_KEY string `json:"SSL_KEY"`
} // end SETTINGS
type JSON_AUTH struct {
User_File string `json:"User_File"`
}
type JSON_USERS struct {
Users []JSON_USER
}
type JSON_USER struct {
Username string `json:"Username"`
Password string `json:"Password"`
Expire int64 `json:"Expire"`
Hostname string `json:"Hostname"`
ClientIP string `json:"ClientIP"`
}
type MONGO_AUTH struct {
Mongo_User string `json:"Mongo_User"`
Mongo_Pass string `json:"Mongo_Pass"`
Mongo_Host string `json:"Mongo_Host"`
Mongo_DB string `json:"Mongo_DB"`
}
type MYSQL_AUTH struct {
Mysql_User string `json:"Mysql_User"`
Mysql_Pass string `json:"Mysql_Pass"`
Mysql_Host string `json:"Mysql_Host"`
Mysql_DB string `json:"Mysql_DB"`
}
type PGSQL_AUTH struct {
Pgsql_User string `json:"Pgsql_User"`
Pgsql_Pass string `json:"Pgsql_Pass"`
Pgsql_Host string `json:"Pgsql_Host"`
Pgsql_DB string `json:"Pgsql_DB"`
}
type REDIS_AUTH struct {
Redis_User string `json:"Redis_User"`
Redis_Pass string `json:"Redis_Pass"`
Redis_Host string `json:"Redis_Host"`
Redis_DB string `json:"Redis_DB"`
}
type USER_DATA struct {
Username string
Password string
Expire int64
Hostname string
ClientIP string
}
type AUTH_CACHE struct {
mux sync.RWMutex
data map[string]USER_DATA
last int64
hash string // hash of user.json: reloads only on change
}
var (
auth AUTH_CACHE
//done_daemons chan struct{}
REQUEST_CHAN chan INN2_STDIN
STDIN_TIMEOUT int = 5 // default of inn2
LIMIT_REQUESTS_CHAN = make(chan struct{}, LIMIT_REQUESTS)
)
/*
- LINES:
ClientAuthname: user\r\n
ClientPassword: pass\r\n
ClientHost: hostname\r\n
ClientIP: IP-address\r\n
ClientPort: port\r\n
LocalIP: IP-address\r\n
LocalPort: port\r\n
.\r\n
*/
type INN2_STDIN struct {
ClientAuthname string
ClientPassword string
ClientHost string
ClientIP string
ClientPort uint16
LocalIP string
LocalPort uint16
Retchan chan string
} // end INN2_STDIN struct
func main() {
var DEBUG bool
var DEBUG_DAEMON bool
var DEBUG_CLI bool
var boot_daemon bool
var conf_file string
/*
var user_add string
var user_del string
var user_expi int64
var passwd string
*/
flag.StringVar(&conf_file, "config", "config.json", "/path/config.json")
flag.BoolVar(&boot_daemon, "daemon", false, "[true|false]")
/*
flag.StringVar(&passwd, "passwd", "", "username:newpasswd")
flag.StringVar(&user_add, "useradd", "", "username:password")
flag.StringVar(&user_del, "userdel", "", "username")
flag.Int64Var(&user_expi, "expire", 0, "(date +%%s)")
*/
flag.Parse()
cfg := ReadConfig(DEBUG, conf_file)
if cfg.Settings.Max_Workers <= 0 {
cfg.Settings.Max_Workers = 1
}
DEBUG = cfg.Settings.Debug
DEBUG_CLI = cfg.Settings.Debug_CLI
DEBUG_DAEMON = cfg.Settings.Debug_Daemon
use_ssl := false
if cfg.Settings.SSL_CRT != "" && cfg.Settings.SSL_CRT[0] != '!' &&
cfg.Settings.SSL_KEY != "" && cfg.Settings.SSL_KEY[0] != '!' {
use_ssl = true
}
var timeout <-chan time.Time
if !boot_daemon {
go ReadStdin(DEBUG_CLI, cfg, use_ssl)
timeout = time.After(time.Duration(cfg.Settings.STDIN_TIMEOUT) * time.Second)
} else {
auth.Make_AUTH_CACHE()
switch cfg.Settings.Auth_Mode {
case "json":
auth.Update_Cache(auth.ReadUserJson(DEBUG, cfg))
case "mongo":
// TODO: check conn mongo
case "mysql":
// TODO: check conn mysql
case "pgsql":
// TODO: check conn pgsql
case "redis":
// TODO: check conn redis
default:
log.Fatal("ERROR main: unknown Auth_Mode")
} // end switch
REQUEST_CHAN = make(chan INN2_STDIN, cfg.Settings.Max_Workers)
//done_daemons = make(chan struct{}, cfg.Settings.Max_Workers)
for wid := 1; wid <= cfg.Settings.Max_Workers; wid++ {
go Daemon(DEBUG_DAEMON, wid, cfg)
time.Sleep(time.Second / 1000)
}
if use_ssl {
go SSL(DEBUG_DAEMON, cfg)
} else {
go TCP(DEBUG_DAEMON, cfg)
}
} // end if boot_daemon
// Setting up signal capturing
// kill -2 $pid ==> SIGINT
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
forever:
for {
select {
case <-stop:
log.Printf("OS_SIGINT")
break forever
case <-timeout:
log.Printf("CLI_TIMEOUT")
}
}
os.Exit(1)
} // end func main
func ReadStdin(DEBUG bool, cfg CFG, use_ssl bool) {
logf(DEBUG, "ReadStdin")
rdr := bufio.NewReader(os.Stdin)
var lines []string
scanner:
for i := 1; i <= STDIN_SCAN_MAX; i++ {
switch line, err := rdr.ReadString('\n'); err {
case io.EOF:
log.Printf("WARN Stdin io.EOF: read %d lines", i)
break scanner
case nil:
// no error from stdin: clear CRLF
if line[len(line)-1] == '\n' {
line = line[:len(line)-1]
}
if line[len(line)-1] == '\r' {
line = line[:len(line)-1]
}
logf(DEBUG, "ReadStdin: line='%s'", line)
if line == "." {
logf(DEBUG, "ReadStdin: DOT @ line: %d", i)
break scanner
}
lines = append(lines, line)
} // end switch
} // end for scanner
if len(lines) < STDIN_SCAN_MAX {
log.Printf("ERROR ReadStdin lines=%d", len(lines))
os.Exit(1)
}
if username := CLI(DEBUG, cfg, lines, use_ssl); username != "" {
line := fmt.Sprintf("User:%s\r\n", username)
fmt.Print(line)
os.Exit(0)
}
os.Exit(1)
} // end func ReadStdin
func CLI(DEBUG bool, cfg CFG, lines []string, use_ssl bool) string {
logf(DEBUG, "CLI lines=%d", len(lines))
var conn net.Conn
var err error
if !use_ssl {
if conn, err = net.Dial(cfg.Settings.Daemon_TCP, cfg.Settings.Daemon_Host); err != nil {
log.Printf("ERROR CLI net.Dial err='%v'", err)
return ""
}
} else {
ssl_conf := &tls.Config{
InsecureSkipVerify: false,
}
if conn, err = tls.Dial(cfg.Settings.Daemon_TCP, cfg.Settings.Daemon_Host, ssl_conf); err != nil {
log.Printf("ERROR CLI tls.Dial err='%v'", err)
return ""
}
}
srvtp := textproto.NewConn(conn)
dw := srvtp.DotWriter()
buf := bufio.NewWriter(dw)
for _, line := range lines {
buf.WriteString(line + "\r\n")
}
buf.Flush()
err = dw.Close()
if err != nil {
return ""
}
if code, username, err := srvtp.ReadCodeLine(200); err == nil {
logf(DEBUG, "CLI code=%d msg=%s", code, username) // AUTH OK
return username
} else {
logf(DEBUG, "ERROR CLI code=%d err='%v'", code, err) // AUTH FAIL
}
return ""
} // end func CLI
func Daemon(DEBUG bool, wid int, cfg CFG) {
logf(DEBUG, "BOOT: DAEMON %d", wid)
var reload <-chan time.Time
timeout := time.Duration(RELOAD_USER)
if wid == 1 { // only first worker may reload user data
reload = time.After(timeout * time.Second)
}
daemon:
for {
select {
case auth_request, ok := <-REQUEST_CHAN:
if !ok {
break daemon
}
logf(DEBUG, "DAEMON: got auth_request='%v'", auth_request)
if auth_request.ClientAuthname == "" || len(auth_request.ClientAuthname) < cfg.Settings.USER_Len_Min {
logf(DEBUG, "ERROR ClientAuthname len=%d", len(auth_request.ClientAuthname))
auth_request.Retchan <- "" // AUTH: DENIED short username
continue daemon
}
if auth_request.ClientPassword == "" || len(auth_request.ClientPassword) < cfg.Settings.PASS_Len_Min {
logf(DEBUG, "ERROR ClientPassword len=%d", len(auth_request.ClientPassword))
auth_request.Retchan <- "" // AUTH: DENIED short password
continue daemon
}
if AUTH(DEBUG, cfg, auth_request) {
auth_request.Retchan <- auth_request.ClientAuthname // AUTH: OK
continue daemon
} // end AUTH
auth_request.Retchan <- "" // AUTH: DENIED
continue daemon
case <-reload:
switch cfg.Settings.Auth_Mode {
case "json":
auth.Update_Cache(auth.ReadUserJson(DEBUG, cfg))
}
reload = time.After(timeout * time.Second)
} // end select
} // end for daemon
logf(DEBUG, "Daemon %d done", wid)
//done_daemons <- struct{}{}
} // end func Daemon
func AUTH(DEBUG bool, cfg CFG, auth_request INN2_STDIN) bool {
/* auth_request.
ClientAuthname: testuser\r\n
ClientPassword: testpass\r\n
ClientHost: hostname\r\n
ClientIP: IP-address\r\n
ClientPort: port\r\n
LocalIP: IP-address\r\n
LocalPort: port\r\n
+++ Retchan bool
*/
user_data := auth.Get_Cached_Userdata(auth_request.ClientAuthname)
if user_data.Username == "" {
// is not cached
switch cfg.Settings.Auth_Mode {
case "json":
logf(DEBUG, "DENIED json: unknown user='%s' clientip='%s' hostname='%s'", auth_request.ClientAuthname, auth_request.ClientIP, auth_request.ClientHost)
// user does not exist in user.json, maybe with next reload
return false
case "mongo":
// TODO: get user_data from mongo && auth.Update_Userdata || return false
case "mysql":
// TODO: get user_data from myqsl && auth.Update_Userdata || return false
case "pgsql":
// TODO: get user_data from pgsql && auth.Update_Userdata || return false
case "redis":
// TODO: get user_data from redis && auth.Update_Userdata || return false
default:
logf(DEBUG, "ERROR AUTH: unknown Auth_Mode")
return false
} // end switch cfg.Settings.Auth_Mode
}
now := UnixTimeSec()
if user_data.Expire >= 0 && user_data.Expire < now {
// user expired
logf(DEBUG, "AUTH: EXPIRED user=%s since=%d", user_data.Username, now-user_data.Expire)
return false
}
if user_data.ClientIP != "" && user_data.ClientIP != auth_request.ClientIP {
// check clientip failed
logf(DEBUG, "DENIED user='%s' clientip='%s'", user_data.Username, auth_request.ClientIP)
return false
}
if user_data.Hostname != "" && user_data.Hostname != auth_request.ClientHost {
// check hostname failed
logf(DEBUG, "DENIED user='%s' hostname='%s'", user_data.Username, auth_request.ClientHost)
return false
}
switch cfg.Settings.Pass_Mode {
case "plain":
if user_data.Password == auth_request.ClientPassword {
return true
}
case "bcrypt":
passwd := BCRYPT(user_data.Password)
if passwd != "" && passwd == auth_request.ClientPassword {
return true
}
case "sha256":
passwd := SHA256(user_data.Password)
if passwd != "" && passwd == auth_request.ClientPassword {
return true
}
} // end switch Auth_Mode
return false
} // end func AUTH
func SSL(DEBUG bool, cfg CFG) {
ssl, err := tls.LoadX509KeyPair(cfg.Settings.SSL_CRT, cfg.Settings.SSL_KEY)
if err != nil {
log.Printf("ERROR tls.LoadX509KeyPair err='%v'", err)
os.Exit(1)
}
ssl_conf := &tls.Config{
Certificates: []tls.Certificate{ssl},
//MinVersion: tls.VersionTLS12,
//MaxVersion: tls.VersionTLS13,
}
listener_ssl, err := tls.Listen(cfg.Settings.Daemon_TCP, cfg.Settings.Daemon_Host, ssl_conf)
if err != nil {
log.Printf("ERROR SSL err='%v'", err)
return
}
defer listener_ssl.Close()
log.Printf("Listen SSL: %s", cfg.Settings.Daemon_Host)
var id uint64
listener:
for {
conn, err := listener_ssl.Accept()
if err != nil {
log.Printf("ERROR listener_ssl err='%v'", err)
time.Sleep(time.Second * 9)
continue listener
}
id++
go handleRequest(DEBUG, id, conn)
} // end for listener_ssl
//logf(DEBUG, "SSL listener_ssl closed %s", cfg.Settings.Daemon_Host)
} // end func SSL
func TCP(DEBUG bool, cfg CFG) {
var conn net.Conn
var err error
listener_tcp, err := net.Listen(cfg.Settings.Daemon_TCP, cfg.Settings.Daemon_Host)
if err != nil {
log.Printf("ERROR TCP err='%v'", err)
os.Exit(1)
}
defer listener_tcp.Close()
log.Printf("Listen TCP: %s", cfg.Settings.Daemon_Host)
var id uint64
listener:
for {
if conn, err = listener_tcp.Accept(); err != nil {
log.Printf("ERROR listener_tcp err='%v'", err)
time.Sleep(time.Second * 9)
continue listener
}
id++
go handleRequest(DEBUG, id, conn)
} // end for listener_tcp
//logf(DEBUG, "TCP listener_tcp closed %s", cfg.Settings.Daemon_Host)
} // end func TCP
func lock_LIMIT_REQUESTS() {
// will block when channel is full
LIMIT_REQUESTS_CHAN <- struct{}{}
}
func return_LIMIT_REQUESTS() {
<-LIMIT_REQUESTS_CHAN
}
func handleRequest(DEBUG bool, id uint64, conn net.Conn) {
start := time.Now().UnixNano()
lock_LIMIT_REQUESTS()
defer return_LIMIT_REQUESTS()
defer conn.Close()
logf(DEBUG, "handleRequest id=%d waited=(%d ns)", id, time.Now().UnixNano()-start)
tp := textproto.NewConn(conn)
if lines, err := tp.ReadDotLines(); err != nil {
logf(DEBUG, "ERROR handleRequest ReadDotLines err='%v'", err)
return
} else {
if username := parseRequest(DEBUG, lines); username != "" {
logf(DEBUG, "handleRequest: 200 %s", username)
tp.Cmd("200 %s", username)
return
}
logf(DEBUG, "handleRequest: 400 DENIED")
tp.Cmd("400 DENIED")
}
} // end func handleRequest
func parseRequest(DEBUG bool, lines []string) string {
logf(DEBUG, "parseRequest lines=%d", len(lines))
var auth_request INN2_STDIN
e := 0
for _, line := range lines {
l := strings.Split(line, " ")
if len(l) != 2 {
e++
if e > 3 {
break
}
continue
}
k, v := l[0], l[1]
switch k {
case "ClientAuthname:":
auth_request.ClientAuthname = v
case "ClientPassword:":
auth_request.ClientPassword = v
case "ClientHost:":
auth_request.ClientHost = v
case "ClientIP:":
auth_request.ClientIP = v
}
} // end for lines
auth_request.Retchan = make(chan string, 1)
// send the received auth_request from TCP to REQUEST_CHAN
REQUEST_CHAN <- auth_request
username := <-auth_request.Retchan
logf(DEBUG, "parseRequest: Retchan got username='%s'", username)
return username
} // end func parseRequest
func ReadConfig(DEBUG bool, filename string) CFG {
logf(DEBUG, "ReadConfig: file='%s'", filename)
file, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatalf("%v", err)
}
var cfg CFG
err = json.Unmarshal(file, &cfg)
if err != nil {
log.Fatalf("%v", err)
}
return cfg
} // end func ReadConfig
func (ac *AUTH_CACHE) Make_AUTH_CACHE() {
ac.mux.Lock()
if ac.data == nil {
ac.data = make(map[string]USER_DATA)
}
ac.mux.Unlock()
} // auth.Make_AUTH_CACHE
func (ac *AUTH_CACHE) Update_Cache(DEBUG bool, newmap map[string]USER_DATA, err error) bool {
if err != nil {
log.Printf("ERROR Update_Cache caller err='%v'", err)
return false
}
if newmap == nil {
//logf(DEBUG, "IGNORE Update_Cache newmap=nil")
return false
}
now := UnixTimeSec()
ac.mux.Lock()
if ac.last > now-RELOAD_USER {
logf(DEBUG, "IGNORE Update_Cache not allowed")
ac.mux.Unlock()
return false
}
log.Printf("Update_Cache OK")
ac.last, ac.data = now, newmap
ac.mux.Unlock()
return true
} // end func auth.Update_Cache
func (ac *AUTH_CACHE) Update_Userdata(username string, user_data USER_DATA) {
ac.mux.Lock()
ac.data[username] = user_data
ac.mux.Unlock()
} // end func auth.Update_Cache
func (ac *AUTH_CACHE) Get_Cached_Userdata(user string) USER_DATA {
var retval USER_DATA
ac.mux.RLock()
if ac.data != nil {
retval = ac.data[user]
}
ac.mux.RUnlock()
return retval
} // end func auth.Get_Cached_Userdata
func (ac *AUTH_CACHE) ReadUserJson(DEBUG bool, cfg CFG) (bool, map[string]USER_DATA, error) {
ac.mux.RLock()
if ac.last > UnixTimeSec()-RELOAD_USER {
ac.mux.RUnlock()
return DEBUG, nil, nil
}
filehash := FILEHASH(cfg.Json_Auth.User_File)
if ac.hash == filehash {
//logf(DEBUG, "IGNORE ReadUserJson hash == filehash")
ac.mux.RUnlock()
return DEBUG, nil, nil
}
ac.mux.RUnlock()
logf(DEBUG, "ReadUserJson: file='%s'", cfg.Json_Auth.User_File)
file, err := ioutil.ReadFile(cfg.Json_Auth.User_File)
if err != nil {
log.Printf("ERROR ReadUserJson err='%v'", err)
return DEBUG, nil, err
}
var json_users JSON_USERS
if err := json.Unmarshal(file, &json_users); err != nil {
log.Printf("ERROR ReadUserJson Unmarshal err='%v'", err)
return DEBUG, nil, err
}
now := UnixTimeSec()
user_map := make(map[string]USER_DATA)
load_users2map:
for i, usr := range json_users.Users {
if usr.Username == "" || usr.Password == "" {
log.Printf("ERROR JSON empty field i=%d: username|password", i)
continue load_users2map
}
if usr.Expire >= 0 && usr.Expire < now { // set to -1 to never expire user
since := now - usr.Expire
log.Printf("EXPIRED user='%s' expi=%d diff=%d", usr.Username, usr.Expire, since)
continue load_users2map
}
logf(DEBUG, "LOAD user='%s' pass='%s' expi=%d hostname='%s' clientip='%s'", usr.Username, usr.Password, usr.Expire, usr.Hostname, usr.ClientIP)
user_map[usr.Username] = USER_DATA{usr.Username, usr.Password, usr.Expire, usr.Hostname, usr.ClientIP}
}
ac.mux.Lock()
ac.hash = filehash
ac.mux.Unlock()
return DEBUG, user_map, nil
} // end func ReadUserJson
func SHA256(password string) string {
hash := sha256.Sum256([]byte(password))
return hex.EncodeToString(hash[:])
} // end func SHA256
func BCRYPT(password string) string {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 10)
if err != nil {
log.Printf("ERROR BCRYPT err='%v'", err)
return ""
}
return string(bytes)
} // end func BCRYPT
func FILEHASH(file_path string) string {
file, err := os.Open(file_path)
if err != nil {
return ""
}
defer file.Close() // Be sure to close your file!
hash := sha256.New() // Use the Hash in crypto/sha256
if _, err := io.Copy(hash, file); err != nil {
return ""
}
sum := fmt.Sprintf("%x", hash.Sum(nil)) // Get encoded hash sum
return sum
} // end func FILEHASH
func UnixTimeSec() int64 {
return time.Now().UnixNano() / 1e9
} // end func UnixTimeSec
func logf(DEBUG bool, format string, a ...any) {
if DEBUG {
log.Printf(format, a...)
}
} // end logf