-
Notifications
You must be signed in to change notification settings - Fork 3
/
ctx.go
executable file
·1415 lines (1177 loc) · 32.1 KB
/
ctx.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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package pitchfork
import (
"errors"
"fmt"
"math"
"net"
"strconv"
"strings"
useragent "github.com/mssola/user_agent"
i18n "github.com/nicksnyder/go-i18n/i18n"
)
var ErrLoginIncorrect = errors.New("Login incorrect")
type PfNewUserI func() (user PfUser)
type PfNewGroupI func() (user PfGroup)
type PfMenuI func(ctx PfCtx, menu *PfMenu)
type PfAppPermsI func(ctx PfCtx, what string, perms Perm) (final bool, ok bool, err error)
type PfPostBecomeI func(ctx PfCtx)
type PfCreds struct {
sel_user PfUser /* Selected User */
sel_group PfGroup /* Selected Group */
}
type PfModOptsI interface {
IsModOpts() bool
}
type PfModOptsS struct {
/* CLI command prefix, eg 'group wiki' */
Cmdpfx string
/* URL prefix, typically System_Get().PublicURL() */
URLpfx string
/* Path Root */
Pathroot string
/* URL root, inside the hostname, eg '/group/name/wiki/' */
URLroot string
}
func (m PfModOptsS) IsModOpts() bool {
return true
}
func PfModOpts(ctx PfCtx, cmdpfx string, path_root string, web_root string) PfModOptsS {
urlpfx := System_Get().PublicURL
web_root = URL_EnsureSlash(web_root)
return PfModOptsS{cmdpfx, urlpfx, path_root, web_root}
}
/* Context Interface, allowing it to be extended */
type PfCtx interface {
GetAbort() <-chan bool
SetAbort(abort <-chan bool)
StoreCreds() (creds PfCreds)
RestoreCreds(creds PfCreds)
SetTx(tx *Tx)
GetTx() (tx *Tx)
Err(message string)
Errf(format string, a ...interface{})
Log(message string)
Logf(format string, a ...interface{})
Dbg(message string)
Dbgf(format string, a ...interface{})
Init() (err error)
SetStatus(code int)
GetStatus() (code int)
SetReturnCode(rc int)
GetReturnCode() (rc int)
GetLoc() string
GetLastPart() string
Become(user PfUser)
GetToken() (tok string)
NewToken() (err error)
LoginToken(tok string) (expsoon bool, err error)
Login(username string, password string, twofactor string) (err error)
Logout()
IsLoggedIn() bool
IsGroupMember() bool
IAmGroupAdmin() bool
IAmGroupMember() bool
GroupHasWiki() bool
GroupHasFile() bool
GroupHasCalendar() bool
CanBeSysAdmin() bool
SwapSysAdmin() bool
IsSysAdmin() bool
ConvertPerms(str string) (perm Perm, err error)
IsPerm(perms Perm, perm Perm) bool
IsPermSet(perms Perm, perm Perm) bool
CheckPerms(what string, perms Perm) (ok bool, err error)
CheckPermsT(what string, permstr string) (ok bool, err error)
TheUser() (user PfUser)
SelectedSelf() bool
SelectedUser() (user PfUser)
SelectedGroup() (grp PfGroup)
SelectedML() (ml PfML)
SelectedEmail() (email PfUserEmail)
SelectedUser2FA() (tfa PfUser2FA)
HasSelectedUser() bool
HasSelectedGroup() bool
HasSelectedML() bool
SelectMe()
SelectUser(username string, perms Perm) (err error)
SelectUser2FA(id int, perms Perm) (err error)
SelectGroupA(grp PfGroup, gr_name string, perms Perm) (err error)
SelectGroup(gr_name string, perms Perm) (err error)
SelectML(ml_name string, perms Perm) (err error)
SelectEmail(email string) (err error)
SetModOpts(opts PfModOptsI)
GetModOpts() (opts interface{})
PDbgf(what string, perm Perm, format string, a ...interface{})
Out(txt string)
Outf(format string, a ...interface{})
OutLn(format string, a ...interface{})
SetOutUnbuffered(obj interface{}, fun string)
OutBuffered(on bool)
IsBuffered() bool
Buffered() (o string)
GetRemote() (remote string)
SetClient(clientip net.IP, remote string, ua string)
GetClientIP() net.IP
GetUserAgent() (string, string, string)
SelectObject(obj *interface{})
SelectedObject() (obj *interface{})
GetLanguage() string
SetLanguage(name string)
GetTfunc() i18n.TranslateFunc
NewUser() (user PfUser)
NewUserI() (i interface{})
NewGroup() (user PfGroup)
NewGroupI() (i interface{})
/* Menu Overrides */
MenuOverride(menu *PfMenu)
/* menu.go */
Menu(args []string, menu PfMenu) (err error)
WalkMenu(args []string) (menu *PfMEntry, err error)
Cmd(args []string) (err error)
CmdOut(cmd string, args []string) (msg string, err error)
Batch(filename string) (err error)
/* appdata */
SetAppData(data interface{})
GetAppData() interface{}
}
type SessionClaims struct {
JWTClaims
UserDesc string `json:"userdesc"`
IsSysAdmin bool `json:"issysadmin"`
}
type PfCtxS struct {
abort <-chan bool /* Abort the request */
status int /* HTTP Status code */
returncode int /* Command Line return code */
loc string /* Command tree location */
output string /* Output buffer */
mode_buffered bool /* Buffering of output in effect */
user PfUser /* Authenticated User */
token string /* The authentication token */
token_claims SessionClaims /* Parsed Token Claims */
remote string /* The address of the client, including X-Forwarded-For */
client_ip net.IP /* Client's IP addresses */
ua_full string /* The HTTP User Agent */
ua_browser string /* HTTP User Agent: Browser */
ua_os string /* HTTP User Agent: Operating System */
language string /* User's chosen language (TODO: Allow user to select it) */
tfunc i18n.TranslateFunc /* Translation function populated with current language */
sel_user PfUser /* Selected User */
sel_user_2fa *PfUser2FA /* Selected User 2FA */
sel_group PfGroup /* Selected Group */
sel_ml *PfML /* Selected Mailing List */
sel_email *PfUserEmail /* Selected User email address */
sel_obj *interface{} /* Selected Object (ctx + struct only) */
mod_opts interface{} /* Module Options for Messages/Wiki/Files etc */
f_newuser PfNewUserI /* Create a new User */
f_newgroup PfNewGroupI /* Create a new Group */
f_menuoverride PfMenuI /* Override a menu */
f_appperms PfAppPermsI /* Application Permission Check */
f_postbecome PfPostBecomeI /* Post Become() */
/* Unbuffered Output */
outunbuf_fun string /* Function name that handles unbuffered output */
outunbuf_obj ObjFuncI /* Object where the function lives */
/* Database internal */
db_Tx *Tx
/* Menu internal values */
menu_walkonly bool
menu_args []string
menu_menu *PfMEntry
/* Application Data */
appdata interface{}
}
type PfNewCtx func() PfCtx
func NewPfCtx(newuser PfNewUserI, newgroup PfNewGroupI, menuoverride PfMenuI, appperms PfAppPermsI, postbecome PfPostBecomeI) PfCtx {
if newuser == nil {
newuser = NewPfUserA
}
if newgroup == nil {
newgroup = NewPfGroup
}
tfunc, err := i18n.Tfunc(Config.TransDefault)
if err != nil {
panic(err.Error())
}
return &PfCtxS{f_newuser: newuser,
f_newgroup: newgroup, f_menuoverride: menuoverride, f_appperms: appperms,
f_postbecome: postbecome,
language: Config.TransDefault, mode_buffered: true, tfunc: tfunc}
}
func (ctx *PfCtxS) GetAbort() <-chan bool {
return ctx.abort
}
func (ctx *PfCtxS) SetAbort(abort <-chan bool) {
ctx.abort = abort
}
func (ctx *PfCtxS) GetLanguage() string {
return ctx.language
}
func (ctx *PfCtxS) SetLanguage(name string) {
ctx.language = name
tfunc, err := i18n.Tfunc(name, Config.TransDefault)
if err != nil {
panic(err.Error())
}
ctx.tfunc = tfunc
}
func (ctx *PfCtxS) GetTfunc() i18n.TranslateFunc {
return ctx.tfunc
}
func (ctx *PfCtxS) SetAppData(appdata interface{}) {
ctx.appdata = appdata
}
func (ctx *PfCtxS) GetAppData() interface{} {
return ctx.appdata
}
func (ctx *PfCtxS) StoreCreds() (creds PfCreds) {
creds.sel_user = ctx.sel_user
creds.sel_group = ctx.sel_group
return
}
func (ctx *PfCtxS) RestoreCreds(creds PfCreds) {
ctx.sel_user = creds.sel_user
ctx.sel_group = creds.sel_group
}
func (ctx *PfCtxS) NewUser() PfUser {
return ctx.f_newuser()
}
func (ctx *PfCtxS) NewUserI() interface{} {
return ctx.f_newuser()
}
func (ctx *PfCtxS) NewGroup() PfGroup {
return ctx.f_newgroup()
}
func (ctx *PfCtxS) NewGroupI() interface{} {
return ctx.f_newgroup()
}
func (ctx *PfCtxS) MenuOverride(menu *PfMenu) {
if ctx.f_menuoverride != nil {
ctx.f_menuoverride(ctx, menu)
}
}
func (ctx *PfCtxS) SetTx(tx *Tx) {
ctx.db_Tx = tx
}
func (ctx *PfCtxS) GetTx() (tx *Tx) {
return ctx.db_Tx
}
func (ctx *PfCtxS) GetRemote() (remote string) {
return ctx.remote
}
func (ctx *PfCtxS) SetClient(clientip net.IP, remote string, fullua string) {
ctx.client_ip = clientip
ctx.remote = remote
/* Split the UA in several parts */
ua := useragent.New(fullua)
ctx.ua_full = fullua
if ua != nil {
ctx.ua_browser, _ = ua.Browser()
ctx.ua_os = ua.OS()
} else {
/* Did not parse as it is the CLI */
if clientip.IsLoopback() {
ctx.ua_browser = "Tickly"
ctx.ua_os = "Trident"
} else {
ctx.ua_browser = "unknown"
ctx.ua_os = "unknown"
}
}
}
func (ctx *PfCtxS) GetClientIP() net.IP {
return ctx.client_ip
}
func (ctx *PfCtxS) GetUserAgent() (string, string, string) {
return ctx.ua_full, ctx.ua_browser, ctx.ua_os
}
func (ctx *PfCtxS) SelectObject(obj *interface{}) {
ctx.sel_obj = obj
}
func (ctx *PfCtxS) SelectedObject() (obj *interface{}) {
return ctx.sel_obj
}
func (ctx *PfCtxS) SetModOpts(opts PfModOptsI) {
ctx.mod_opts = opts
}
func (ctx *PfCtxS) GetModOpts() (opts interface{}) {
return ctx.mod_opts
}
type Perm uint64
/*
* Note: Keep in sync with permnames && ui/ui (convienence for all the menus there)
*
* It is used as a bitfield, hence multiple perms are possible
* Check access using the CheckPerms() function
*
* The perms use the sel_{user|group|ml} vars to compare against
*
* Note: Being sysadmin overrides almost all permissions!
*
* Change the 'false' in PDbgf to 'true' to see what permission
* decisions are being made.
*/
const (
PERM_NOTHING Perm = 0 /* Nothing / empty permissions */
PERM_NONE Perm = 1 << iota /* No access bits needed (unauthenticated) */
PERM_GUEST /* Not authenticated */
PERM_USER /* User (authenticated) */
PERM_USER_SELF /* User when they selected themselves */
PERM_USER_NOMINATE /* User when doing nomination */
PERM_USER_VIEW /* User when just trying to view */
PERM_GROUP_MEMBER /* Member of the group */
PERM_GROUP_ADMIN /* Admin of the group */
PERM_GROUP_WIKI /* Group has Wiki section enabled */
PERM_GROUP_FILE /* Group has File section enabled */
PERM_GROUP_CALENDAR /* Group has Calendar section enabled */
PERM_SYS_ADMIN /* System Administrator */
PERM_SYS_ADMIN_CAN /* Can be a System Administrator */
PERM_CLI /* When CLI is enabled */
PERM_API /* When API is enabled */
PERM_OAUTH /* When OAUTH is enabled */
PERM_LOOPBACK /* Connected from Loopback */
PERM_HIDDEN /* Option is hidden */
PERM_NOCRUMB /* Don't add a crumb for this menu */
PERM_NOSUBS /* No sub menus for this menu entry */
PERM_NOBODY /* Nobody has access */
/* Application permissions */
PERM_APP_0
PERM_APP_1
PERM_APP_2
PERM_APP_3
PERM_APP_4
PERM_APP_5
PERM_APP_6
PERM_APP_7
PERM_APP_8
PERM_APP_9
)
var permnames []string
/* String init */
func init() {
permnames = []string{
"nothing",
"none",
"guest",
"user",
"self",
"user_nominate",
"user_view",
"group_member",
"group_admin",
"group_wiki",
"group_file",
"group_calendar",
"sysadmin",
"sysadmin_can",
"cli",
"api",
"oauth",
"loopback",
"hidden",
"nocrumb",
"nosubs",
"nobody",
"app_0",
"app_1",
"app_2",
"app_3",
"app_4",
"app_5",
"app_6",
"app_7",
"app_9",
}
max := uint64(1 << uint64(len(permnames)))
if max != uint64(PERM_APP_9) {
fmt.Printf("Expected %d got %d\n", max, PERM_APP_9)
panic("Invalid permnames")
}
}
const (
StatusOK = 200
StatusUnauthorized = 401
)
var Debug = false
/* Constructor */
func (ctx *PfCtxS) Init() (err error) {
/* Default HTTP status */
ctx.status = StatusOK
/* Default Shell Return Code to 0 */
ctx.returncode = 0
return err
}
func (ctx *PfCtxS) SetStatus(code int) {
ctx.status = code
}
func (ctx *PfCtxS) GetStatus() (code int) {
return ctx.status
}
func (ctx *PfCtxS) SetReturnCode(rc int) {
ctx.returncode = rc
}
func (ctx *PfCtxS) GetReturnCode() (rc int) {
return ctx.returncode
}
func (ctx *PfCtxS) GetLoc() string {
return ctx.loc
}
func (ctx *PfCtxS) GetLastPart() string {
fa := strings.Split(ctx.loc, " ")
return fa[len(fa)-1]
}
func (ctx *PfCtxS) Become(user PfUser) {
/* Use the details from the user */
ctx.user = user
/* Select one-self */
ctx.sel_user = user
/* Post Become() hook? */
if ctx.f_postbecome != nil {
ctx.f_postbecome(ctx)
}
}
func (ctx *PfCtxS) GetToken() (tok string) {
return ctx.token
}
func (ctx *PfCtxS) NewToken() (err error) {
if !ctx.IsLoggedIn() {
return errors.New("Not authenticated")
}
theuser := ctx.TheUser()
/* Set some claims */
ctx.token_claims.UserDesc = theuser.GetFullName()
ctx.token_claims.IsSysAdmin = theuser.IsSysAdmin()
username := theuser.GetUserName()
/* Create the token */
token := Token_New("websession", username, TOKEN_EXPIRATIONMINUTES, &ctx.token_claims)
/* Sign and get the complete encoded token as a string */
ctx.token, err = token.Sign()
if err != nil {
/* Invalid token when something went wrong */
ctx.token = ""
}
return
}
func (ctx *PfCtxS) LoginToken(tok string) (expsoon bool, err error) {
/* No valid token */
ctx.token = ""
/* Parse the provided token */
expsoon, err = Token_Parse(tok, "websession", &ctx.token_claims)
if err != nil {
return expsoon, err
}
/* Who they claim they are */
user := ctx.NewUser()
user.SetUserName(ctx.token_claims.Subject)
user.SetFullName(ctx.token_claims.UserDesc)
user.SetSysAdmin(ctx.token_claims.IsSysAdmin)
/* Fetch the details */
err = user.Refresh(ctx)
if err == ErrNoRows {
ctx.Dbgf("No such user %q", ctx.token_claims.Subject)
return false, errors.New("No such user")
} else if err != nil {
ctx.Dbgf("Fetch of user %q failed: %s", ctx.token_claims.Subject, err.Error())
return false, err
}
/* Looking good, become the user */
ctx.Become(user)
/* Valid Token */
ctx.token = tok
return expsoon, nil
}
func (ctx *PfCtxS) Login(username string, password string, twofactor string) (err error) {
user := ctx.NewUser()
err = user.CheckAuth(ctx, username, password, twofactor)
if err != nil {
/* Log the error, so that it can be looked up in the log */
ctx.Errf("CheckAuth(%s): %s", username, err)
/* Overwrite the error so that we do not leak too much detail */
err = ErrLoginIncorrect
return
}
/* Force generation of a new token */
ctx.token = ""
ctx.Become(user)
userevent(ctx, "login")
return nil
}
func (ctx *PfCtxS) Logout() {
if ctx.token != "" {
Jwt_invalidate(ctx.token, &ctx.token_claims)
}
/* Invalidate user + token */
ctx.user = nil
ctx.token = ""
ctx.token_claims = SessionClaims{}
}
func (ctx *PfCtxS) IsLoggedIn() bool {
if ctx.user == nil {
return false
}
return true
}
func (ctx *PfCtxS) IsGroupMember() bool {
if !ctx.HasSelectedUser() {
return false
}
if !ctx.HasSelectedGroup() {
return false
}
ismember, _, state, err := ctx.sel_group.IsMember(ctx.user.GetUserName())
if err != nil {
ctx.Log("IsGroupMember: " + err.Error())
return false
}
if !ismember {
return false
}
/* Group Admins can always select users, even when blocked */
if ctx.IAmGroupAdmin() {
return true
}
/* Normal group users, it depends on wether they can see them */
return state.can_see
}
func (ctx *PfCtxS) IAmGroupAdmin() bool {
if !ctx.IsLoggedIn() {
return false
}
if !ctx.HasSelectedGroup() {
return false
}
if ctx.IsSysAdmin() {
return true
}
_, isadmin, _, err := ctx.sel_group.IsMember(ctx.user.GetUserName())
if err != nil {
return false
}
return isadmin
}
func (ctx *PfCtxS) IAmGroupMember() bool {
if !ctx.IsLoggedIn() {
return false
}
if !ctx.HasSelectedGroup() {
return false
}
ismember, _, _, err := ctx.sel_group.IsMember(ctx.user.GetUserName())
if err != nil {
return false
}
return ismember
}
func (ctx *PfCtxS) GroupHasWiki() bool {
if !ctx.HasSelectedGroup() {
return false
}
return ctx.sel_group.HasWiki()
}
func (ctx *PfCtxS) GroupHasFile() bool {
if !ctx.HasSelectedGroup() {
return false
}
return ctx.sel_group.HasFile()
}
func (ctx *PfCtxS) GroupHasCalendar() bool {
if !ctx.HasSelectedGroup() {
return false
}
return ctx.sel_group.HasCalendar()
}
func (ctx *PfCtxS) CanBeSysAdmin() bool {
if !ctx.IsLoggedIn() {
return false
}
/* Can we be or not? */
if !ctx.user.CanBeSysAdmin() {
return false
}
/* Could be, if the user wanted */
return true
}
func (ctx *PfCtxS) SwapSysAdmin() bool {
/* Not logged, can't be SysAdmin */
if !ctx.IsLoggedIn() {
return false
}
/* If they cannot be one, then do not toggle either */
if !ctx.user.CanBeSysAdmin() {
return false
}
/* Toggle state: SysAdmin <> Regular */
ctx.user.SetSysAdmin(!ctx.user.IsSysAdmin())
/* Force generation of a new token */
ctx.token = ""
return true
}
func (ctx *PfCtxS) IsSysAdmin() bool {
if !ctx.IsLoggedIn() {
return false
}
/* Not a SysAdmin, easy */
if !ctx.user.IsSysAdmin() {
return false
}
sys := System_Get()
/*
* SysAdmin IP Restriction in effect?
*
* Loopback (127.0.0.1 / ::1) are excluded from this restriction
*/
if sys.sar_cache == nil || ctx.client_ip.IsLoopback() {
return true
}
/* Check all the prefixes */
for _, n := range sys.sar_cache {
if n.Contains(ctx.client_ip) {
/* It is valid */
return true
}
}
/* Not in the SARestrict list */
return false
}
func (ctx *PfCtxS) ConvertPerms(str string) (perm Perm, err error) {
str = strings.ToLower(str)
perm = PERM_NOTHING
p := strings.Split(str, ",")
for _, pm := range p {
if pm == "" {
continue
}
found := false
var i uint
i = 0
for _, n := range permnames {
if pm == n {
perm += 1 << i
found = true
break
}
i++
}
if !found {
return PERM_NOTHING, errors.New("Unknown permission: '" + pm + "'")
}
break
}
return perm, nil
}
func (perm Perm) String() (str string) {
for i := 0; i < len(permnames); i++ {
p := uint64(math.Pow(float64(2), float64(i)))
if uint64(perm)&p == 0 {
continue
}
if str != "" {
str += ","
}
str += permnames[i]
}
return str
}
func (ctx *PfCtxS) IsPerm(perms Perm, perm Perm) bool {
return perms == perm
}
func (ctx *PfCtxS) IsPermSet(perms Perm, perm Perm) bool {
return perms&perm > 0
}
/*
* Multiple permissions can be specified
* thus test from least to most to see
* if any of them allows access
*/
func (ctx *PfCtxS) CheckPerms(what string, perms Perm) (ok bool, err error) {
/* No error yet */
sys := System_Get()
ctx.PDbgf(what, perms, "Text: %s", perms.String())
if ctx.IsLoggedIn() {
ctx.PDbgf(what, perms, "user = %s", ctx.user.GetUserName())
} else {
ctx.PDbgf(what, perms, "user = ::NONE::")
}
if ctx.HasSelectedUser() {
ctx.PDbgf(what, perms, "sel_user = %s", ctx.sel_user.GetUserName())
} else {
ctx.PDbgf(what, perms, "sel_user = ::NONE::")
}
if ctx.HasSelectedGroup() {
ctx.PDbgf(what, perms, "sel_group = %s", ctx.sel_group.GetGroupName())
} else {
ctx.PDbgf(what, perms, "sel_group = ::NONE::")
}
/* Nobody? */
if ctx.IsPermSet(perms, PERM_NOBODY) {
ctx.PDbgf(what, perms, "Nobody")
return false, errors.New("Nobody is allowed")
}
if ctx.IsPerm(perms, PERM_NOBODY) {
panic("EHMM")
}
/* No permissions? */
if ctx.IsPerm(perms, PERM_NOTHING) {
ctx.PDbgf(what, perms, "Nothing")
return true, nil
}
/* CLI when enabled and user is authenticated */
if ctx.IsPermSet(perms, PERM_CLI) {
ctx.PDbgf(what, perms, "CLI")
if ctx.IsLoggedIn() && sys.CLIEnabled {
ctx.PDbgf(what, perms, "CLI - Enabled")
return true, nil
} else {
err = errors.New("CLI is not enabled")
}
}
/* Loopback calls can always access the API (for tcli) */
if ctx.IsPermSet(perms, PERM_API) {
ctx.PDbgf(what, perms, "API")
if sys.APIEnabled {
ctx.PDbgf(what, perms, "API - Enabled")
return true, nil
} else {
err = errors.New("API is not enabled")
}
}
/* Is OAuth enabled? */
if ctx.IsPermSet(perms, PERM_OAUTH) {
ctx.PDbgf(what, perms, "OAuth")
if sys.OAuthEnabled {
ctx.PDbgf(what, perms, "OAuth - Enabled")
return true, nil
} else {
err = errors.New("OAuth is not enabled")
}
}
/* Loopback? */
if ctx.IsPermSet(perms, PERM_LOOPBACK) {
ctx.PDbgf(what, perms, "Loopback")
if ctx.client_ip.IsLoopback() {
ctx.PDbgf(what, perms, "Is Loopback")
return true, nil
} else {
err = errors.New("Not a Loopback")
}
}
/* User must not be authenticated */
if ctx.IsPermSet(perms, PERM_GUEST) {
ctx.PDbgf(what, perms, "Guest")
if !ctx.IsLoggedIn() {
ctx.PDbgf(what, perms, "Guest - Not Logged In")
return true, nil
}
ctx.PDbgf(what, perms, "Guest - Logged In")
return false, errors.New("Must not be authenticated")
}
/* User has to have selected themselves */
if ctx.IsPermSet(perms, PERM_USER_SELF) {
ctx.PDbgf(what, perms, "User Self")
if ctx.IsLoggedIn() {
ctx.PDbgf(what, perms, "User Self - Logged In")
if ctx.HasSelectedUser() {
ctx.PDbgf(what, perms, "User Self - Has selected user")
if ctx.sel_user.GetUserName() == ctx.user.GetUserName() {
/* Passed the test */
ctx.PDbgf(what, perms, "User Self - It is me")
return true, nil
} else {
ctx.PDbgf(what, perms, "User Self - Other user")
err = errors.New("Different user selected")
}
} else {
err = errors.New("No user selected")
}
} else {
err = errors.New("Not Authenticated")
}
}
/* User has to have selected themselves */
if ctx.IsPermSet(perms, PERM_USER_VIEW) {
ctx.PDbgf(what, perms, "User View")
if ctx.IsLoggedIn() {
ctx.PDbgf(what, perms, "User View - Logged In")
if ctx.HasSelectedUser() {
ctx.PDbgf(what, perms, "User View - Has selected user")
if ctx.sel_user.GetUserName() == ctx.user.GetUserName() {
/* Passed the test */
ctx.PDbgf(what, perms, "User View - It is me")
return true, nil
} else {
ok, err = ctx.sel_user.SharedGroups(ctx, ctx.user)
if ok {
/* Passed the test */
ctx.PDbgf(what, perms, "User View - It is in my group")
return true, nil
} else {
ctx.PDbgf(what, perms, "User View - Other user")
err = errors.New("Different user selected")
}
}
} else {
err = errors.New("No user selected")
}
} else {
err = errors.New("Not Authenticated")
}
}
/* User has to be a group member + Wiki enabled */
if ctx.IsPermSet(perms, PERM_GROUP_WIKI) {
ctx.PDbgf(what, perms, "Group Wiki?")
if ctx.GroupHasWiki() {
ctx.PDbgf(what, perms, "HasWiki - ok")
if ctx.IsGroupMember() {
ctx.PDbgf(what, perms, "Group member - ok")
return true, nil
}
err = errors.New("Not a group member")
} else {
err = errors.New("Group does not have a Wiki")
return false, err
}
}
/* User has to be a group member + File enabled */
if ctx.IsPermSet(perms, PERM_GROUP_FILE) {