forked from tobychui/zoraxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverseproxy.go
1172 lines (1002 loc) · 32.8 KB
/
reverseproxy.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 main
import (
"encoding/json"
"net/http"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"imuslab.com/zoraxy/mod/auth"
"imuslab.com/zoraxy/mod/dynamicproxy"
"imuslab.com/zoraxy/mod/uptime"
"imuslab.com/zoraxy/mod/utils"
)
var (
dynamicProxyRouter *dynamicproxy.Router
)
// Add user customizable reverse proxy
func ReverseProxtInit() {
/*
Load Reverse Proxy Global Settings
*/
inboundPort := 80
if sysdb.KeyExists("settings", "inbound") {
sysdb.Read("settings", "inbound", &inboundPort)
SystemWideLogger.Println("Serving inbound port ", inboundPort)
} else {
SystemWideLogger.Println("Inbound port not set. Using default (80)")
}
useTls := false
sysdb.Read("settings", "usetls", &useTls)
if useTls {
SystemWideLogger.Println("TLS mode enabled. Serving proxxy request with TLS")
} else {
SystemWideLogger.Println("TLS mode disabled. Serving proxy request with plain http")
}
forceLatestTLSVersion := false
sysdb.Read("settings", "forceLatestTLS", &forceLatestTLSVersion)
if forceLatestTLSVersion {
SystemWideLogger.Println("Force latest TLS mode enabled. Minimum TLS LS version is set to v1.2")
} else {
SystemWideLogger.Println("Force latest TLS mode disabled. Minimum TLS version is set to v1.0")
}
developmentMode := false
sysdb.Read("settings", "devMode", &developmentMode)
if useTls {
SystemWideLogger.Println("Development mode enabled. Using no-store Cache Control policy")
} else {
SystemWideLogger.Println("Development mode disabled. Proxying with default Cache Control policy")
}
listenOnPort80 := false
sysdb.Read("settings", "listenP80", &listenOnPort80)
if listenOnPort80 {
SystemWideLogger.Println("Port 80 listener enabled")
} else {
SystemWideLogger.Println("Port 80 listener disabled")
}
forceHttpsRedirect := false
sysdb.Read("settings", "redirect", &forceHttpsRedirect)
if forceHttpsRedirect {
SystemWideLogger.Println("Force HTTPS mode enabled")
//Port 80 listener must be enabled to perform http -> https redirect
listenOnPort80 = true
} else {
SystemWideLogger.Println("Force HTTPS mode disabled")
}
/*
Create a new proxy object
The DynamicProxy is the parent of all reverse proxy handlers,
use for managemening and provide functions to access proxy handlers
*/
dprouter, err := dynamicproxy.NewDynamicProxy(dynamicproxy.RouterOption{
HostUUID: nodeUUID,
HostVersion: version,
Port: inboundPort,
UseTls: useTls,
ForceTLSLatest: forceLatestTLSVersion,
NoCache: developmentMode,
ListenOnPort80: listenOnPort80,
ForceHttpsRedirect: forceHttpsRedirect,
TlsManager: tlsCertManager,
RedirectRuleTable: redirectTable,
GeodbStore: geodbStore,
StatisticCollector: statisticCollector,
WebDirectory: *staticWebServerRoot,
AccessController: accessController,
})
if err != nil {
SystemWideLogger.PrintAndLog("Proxy", "Unable to create dynamic proxy router", err)
return
}
dynamicProxyRouter = dprouter
/*
Load all conf from files
*/
confs, _ := filepath.Glob("./conf/proxy/*.config")
for _, conf := range confs {
err := LoadReverseProxyConfig(conf)
if err != nil {
SystemWideLogger.PrintAndLog("Proxy", "Failed to load config file: "+filepath.Base(conf), err)
return
}
}
if dynamicProxyRouter.Root == nil {
//Root config not set (new deployment?), use internal static web server as root
defaultRootRouter, err := GetDefaultRootConfig()
if err != nil {
SystemWideLogger.PrintAndLog("Proxy", "Failed to generate default root routing", err)
return
}
dynamicProxyRouter.SetProxyRouteAsRoot(defaultRootRouter)
}
//Start Service
//Not sure why but delay must be added if you have another
//reverse proxy server in front of this service
time.Sleep(300 * time.Millisecond)
dynamicProxyRouter.StartProxyService()
SystemWideLogger.Println("Dynamic Reverse Proxy service started")
//Add all proxy services to uptime monitor
//Create a uptime monitor service
go func() {
//This must be done in go routine to prevent blocking on system startup
uptimeMonitor, _ = uptime.NewUptimeMonitor(&uptime.Config{
Targets: GetUptimeTargetsFromReverseProxyRules(dynamicProxyRouter),
Interval: 300, //5 minutes
MaxRecordsStore: 288, //1 day
})
SystemWideLogger.Println("Uptime Monitor background service started")
}()
}
func ReverseProxyHandleOnOff(w http.ResponseWriter, r *http.Request) {
enable, _ := utils.PostPara(r, "enable") //Support root, vdir and subd
if enable == "true" {
err := dynamicProxyRouter.StartProxyService()
if err != nil {
utils.SendErrorResponse(w, err.Error())
return
}
} else {
//Check if it is loopback
if dynamicProxyRouter.IsProxiedSubdomain(r) {
//Loopback routing. Turning it off will make the user lost control
//of the whole system. Do not allow shutdown
utils.SendErrorResponse(w, "Unable to shutdown in loopback rp mode. Remove proxy rules for management interface and retry.")
return
}
err := dynamicProxyRouter.StopProxyService()
if err != nil {
utils.SendErrorResponse(w, err.Error())
return
}
}
utils.SendOK(w)
}
func ReverseProxyHandleAddEndpoint(w http.ResponseWriter, r *http.Request) {
eptype, err := utils.PostPara(r, "type") //Support root and host
if err != nil {
utils.SendErrorResponse(w, "type not defined")
return
}
endpoint, err := utils.PostPara(r, "ep")
if err != nil {
utils.SendErrorResponse(w, "endpoint not defined")
return
}
tls, _ := utils.PostPara(r, "tls")
if tls == "" {
tls = "false"
}
useTLS := (tls == "true")
//Bypass global TLS value / allow direct access from port 80?
bypassGlobalTLS, _ := utils.PostPara(r, "bypassGlobalTLS")
if bypassGlobalTLS == "" {
bypassGlobalTLS = "false"
}
useBypassGlobalTLS := bypassGlobalTLS == "true"
//Enable TLS validation?
stv, _ := utils.PostPara(r, "tlsval")
if stv == "" {
stv = "false"
}
skipTlsValidation := (stv == "true")
//Get access rule ID
accessRuleID, _ := utils.PostPara(r, "access")
if accessRuleID == "" {
accessRuleID = "default"
}
if !accessController.AccessRuleExists(accessRuleID) {
utils.SendErrorResponse(w, "invalid access rule ID selected")
return
}
//Require basic auth?
rba, _ := utils.PostPara(r, "bauth")
if rba == "" {
rba = "false"
}
requireBasicAuth := (rba == "true")
// Bypass WebSocket Origin Check
strbpwsorg, _ := utils.PostPara(r, "bpwsorg")
if strbpwsorg == "" {
strbpwsorg = "false"
}
bypassWebsocketOriginCheck := (strbpwsorg == "true")
//Prase the basic auth to correct structure
cred, _ := utils.PostPara(r, "cred")
basicAuthCredentials := []*dynamicproxy.BasicAuthCredentials{}
if requireBasicAuth {
preProcessCredentials := []*dynamicproxy.BasicAuthUnhashedCredentials{}
err = json.Unmarshal([]byte(cred), &preProcessCredentials)
if err != nil {
utils.SendErrorResponse(w, "invalid user credentials")
return
}
//Check if there are empty password credentials
for _, credObj := range preProcessCredentials {
if strings.TrimSpace(credObj.Password) == "" {
utils.SendErrorResponse(w, credObj.Username+" has empty password")
return
}
}
//Convert and hash the passwords
for _, credObj := range preProcessCredentials {
basicAuthCredentials = append(basicAuthCredentials, &dynamicproxy.BasicAuthCredentials{
Username: credObj.Username,
PasswordHash: auth.Hash(credObj.Password),
})
}
}
var proxyEndpointCreated *dynamicproxy.ProxyEndpoint
if eptype == "host" {
rootOrMatchingDomain, err := utils.PostPara(r, "rootname")
if err != nil {
utils.SendErrorResponse(w, "hostname not defined")
return
}
rootOrMatchingDomain = strings.TrimSpace(rootOrMatchingDomain)
//Check if it contains ",", if yes, split the remainings as alias
aliasHostnames := []string{}
if strings.Contains(rootOrMatchingDomain, ",") {
matchingDomains := strings.Split(rootOrMatchingDomain, ",")
if len(matchingDomains) > 1 {
rootOrMatchingDomain = matchingDomains[0]
for _, aliasHostname := range matchingDomains[1:] {
//Filter out any space
aliasHostnames = append(aliasHostnames, strings.TrimSpace(aliasHostname))
}
}
}
//Generate a proxy endpoint object
thisProxyEndpoint := dynamicproxy.ProxyEndpoint{
//I/O
ProxyType: dynamicproxy.ProxyType_Host,
RootOrMatchingDomain: rootOrMatchingDomain,
MatchingDomainAlias: aliasHostnames,
Domain: endpoint,
//TLS
RequireTLS: useTLS,
BypassGlobalTLS: useBypassGlobalTLS,
SkipCertValidations: skipTlsValidation,
SkipWebSocketOriginCheck: bypassWebsocketOriginCheck,
AccessFilterUUID: accessRuleID,
//VDir
VirtualDirectories: []*dynamicproxy.VirtualDirectoryEndpoint{},
//Custom headers
UserDefinedHeaders: []*dynamicproxy.UserDefinedHeader{},
//Auth
RequireBasicAuth: requireBasicAuth,
BasicAuthCredentials: basicAuthCredentials,
BasicAuthExceptionRules: []*dynamicproxy.BasicAuthExceptionRule{},
DefaultSiteOption: 0,
DefaultSiteValue: "",
}
preparedEndpoint, err := dynamicProxyRouter.PrepareProxyRoute(&thisProxyEndpoint)
if err != nil {
utils.SendErrorResponse(w, "unable to prepare proxy route to target endpoint: "+err.Error())
return
}
dynamicProxyRouter.AddProxyRouteToRuntime(preparedEndpoint)
proxyEndpointCreated = &thisProxyEndpoint
} else if eptype == "root" {
//Get the default site options and target
dsOptString, err := utils.PostPara(r, "defaultSiteOpt")
if err != nil {
utils.SendErrorResponse(w, "default site action not defined")
return
}
var defaultSiteOption int = 1
opt, err := strconv.Atoi(dsOptString)
if err != nil {
utils.SendErrorResponse(w, "invalid default site option")
return
}
defaultSiteOption = opt
dsVal, err := utils.PostPara(r, "defaultSiteVal")
if err != nil && (defaultSiteOption == 1 || defaultSiteOption == 2) {
//Reverse proxy or redirect, must require value to be set
utils.SendErrorResponse(w, "target not defined")
return
}
//Write the root options to file
rootRoutingEndpoint := dynamicproxy.ProxyEndpoint{
ProxyType: dynamicproxy.ProxyType_Root,
RootOrMatchingDomain: "/",
Domain: endpoint,
RequireTLS: useTLS,
BypassGlobalTLS: false,
SkipCertValidations: false,
SkipWebSocketOriginCheck: true,
DefaultSiteOption: defaultSiteOption,
DefaultSiteValue: dsVal,
}
preparedRootProxyRoute, err := dynamicProxyRouter.PrepareProxyRoute(&rootRoutingEndpoint)
if err != nil {
utils.SendErrorResponse(w, "unable to prepare root routing: "+err.Error())
return
}
dynamicProxyRouter.SetProxyRouteAsRoot(preparedRootProxyRoute)
proxyEndpointCreated = &rootRoutingEndpoint
} else {
//Invalid eptype
utils.SendErrorResponse(w, "invalid endpoint type")
return
}
//Save the config to file
err = SaveReverseProxyConfig(proxyEndpointCreated)
if err != nil {
SystemWideLogger.PrintAndLog("Proxy", "Unable to save new proxy rule to file", err)
return
}
//Update utm if exists
UpdateUptimeMonitorTargets()
utils.SendOK(w)
}
/*
ReverseProxyHandleEditEndpoint handles proxy endpoint edit
(host only, for root use Default Site page to edit)
This endpoint do not handle basic auth credential update.
The credential will be loaded from old config and reused
*/
func ReverseProxyHandleEditEndpoint(w http.ResponseWriter, r *http.Request) {
rootNameOrMatchingDomain, err := utils.PostPara(r, "rootname")
if err != nil {
utils.SendErrorResponse(w, "Target proxy rule not defined")
return
}
endpoint, err := utils.PostPara(r, "ep")
if err != nil {
utils.SendErrorResponse(w, "endpoint not defined")
return
}
tls, _ := utils.PostPara(r, "tls")
if tls == "" {
tls = "false"
}
useTLS := (tls == "true")
stv, _ := utils.PostPara(r, "tlsval")
if stv == "" {
stv = "false"
}
skipTlsValidation := (stv == "true")
//Load bypass TLS option
bpgtls, _ := utils.PostPara(r, "bpgtls")
if bpgtls == "" {
bpgtls = "false"
}
bypassGlobalTLS := (bpgtls == "true")
// Basic Auth
rba, _ := utils.PostPara(r, "bauth")
if rba == "" {
rba = "false"
}
requireBasicAuth := (rba == "true")
// Bypass WebSocket Origin Check
strbpwsorg, _ := utils.PostPara(r, "bpwsorg")
if strbpwsorg == "" {
strbpwsorg = "false"
}
bypassWebsocketOriginCheck := (strbpwsorg == "true")
//Load the previous basic auth credentials from current proxy rules
targetProxyEntry, err := dynamicProxyRouter.LoadProxy(rootNameOrMatchingDomain)
if err != nil {
utils.SendErrorResponse(w, "Target proxy config not found or could not be loaded")
return
}
//Generate a new proxyEndpoint from the new config
newProxyEndpoint := dynamicproxy.CopyEndpoint(targetProxyEntry)
newProxyEndpoint.Domain = endpoint
newProxyEndpoint.RequireTLS = useTLS
newProxyEndpoint.BypassGlobalTLS = bypassGlobalTLS
newProxyEndpoint.SkipCertValidations = skipTlsValidation
newProxyEndpoint.RequireBasicAuth = requireBasicAuth
newProxyEndpoint.SkipWebSocketOriginCheck = bypassWebsocketOriginCheck
//Prepare to replace the current routing rule
readyRoutingRule, err := dynamicProxyRouter.PrepareProxyRoute(newProxyEndpoint)
if err != nil {
utils.SendErrorResponse(w, err.Error())
return
}
targetProxyEntry.Remove()
dynamicProxyRouter.AddProxyRouteToRuntime(readyRoutingRule)
//Save it to file
SaveReverseProxyConfig(newProxyEndpoint)
//Update uptime monitor
UpdateUptimeMonitorTargets()
utils.SendOK(w)
}
func ReverseProxyHandleAlias(w http.ResponseWriter, r *http.Request) {
rootNameOrMatchingDomain, err := utils.PostPara(r, "ep")
if err != nil {
utils.SendErrorResponse(w, "Invalid ep given")
return
}
//No need to check for type as root (/) can be set to default route
//and hence, you will not need alias
//Load the previous alias from current proxy rules
targetProxyEntry, err := dynamicProxyRouter.LoadProxy(rootNameOrMatchingDomain)
if err != nil {
utils.SendErrorResponse(w, "Target proxy config not found or could not be loaded")
return
}
newAliasJSON, err := utils.PostPara(r, "alias")
if err != nil {
//No new set of alias given
utils.SendErrorResponse(w, "new alias not given")
return
}
//Write new alias to runtime and file
newAlias := []string{}
err = json.Unmarshal([]byte(newAliasJSON), &newAlias)
if err != nil {
SystemWideLogger.PrintAndLog("Proxy", "Unable to parse new alias list", err)
utils.SendErrorResponse(w, "Invalid alias list given")
return
}
//Set the current alias
newProxyEndpoint := dynamicproxy.CopyEndpoint(targetProxyEntry)
newProxyEndpoint.MatchingDomainAlias = newAlias
// Prepare to replace the current routing rule
readyRoutingRule, err := dynamicProxyRouter.PrepareProxyRoute(newProxyEndpoint)
if err != nil {
utils.SendErrorResponse(w, err.Error())
return
}
targetProxyEntry.Remove()
dynamicProxyRouter.AddProxyRouteToRuntime(readyRoutingRule)
// Save it to file
err = SaveReverseProxyConfig(newProxyEndpoint)
if err != nil {
utils.SendErrorResponse(w, "Alias update failed")
SystemWideLogger.PrintAndLog("Proxy", "Unable to save alias update", err)
}
utils.SendOK(w)
}
func DeleteProxyEndpoint(w http.ResponseWriter, r *http.Request) {
ep, err := utils.GetPara(r, "ep")
if err != nil {
utils.SendErrorResponse(w, "Invalid ep given")
return
}
//Remove the config from runtime
err = dynamicProxyRouter.RemoveProxyEndpointByRootname(ep)
if err != nil {
utils.SendErrorResponse(w, err.Error())
return
}
//Remove the config from file
err = RemoveReverseProxyConfig(ep)
if err != nil {
utils.SendErrorResponse(w, err.Error())
return
}
//Update utm if exists
if uptimeMonitor != nil {
uptimeMonitor.Config.Targets = GetUptimeTargetsFromReverseProxyRules(dynamicProxyRouter)
uptimeMonitor.CleanRecords()
}
//Update uptime monitor
UpdateUptimeMonitorTargets()
utils.SendOK(w)
}
/*
Handle update request for basic auth credential
Require paramter: ep (Endpoint) and pytype (proxy Type)
if request with GET, the handler will return current credentials
on this endpoint by its username
if request is POST, the handler will write the results to proxy config
*/
func UpdateProxyBasicAuthCredentials(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
ep, err := utils.GetPara(r, "ep")
if err != nil {
utils.SendErrorResponse(w, "Invalid ep given")
return
}
//Load the target proxy object from router
targetProxy, err := dynamicProxyRouter.LoadProxy(ep)
if err != nil {
utils.SendErrorResponse(w, err.Error())
return
}
usernames := []string{}
for _, cred := range targetProxy.BasicAuthCredentials {
usernames = append(usernames, cred.Username)
}
js, _ := json.Marshal(usernames)
utils.SendJSONResponse(w, string(js))
} else if r.Method == http.MethodPost {
//Write to target
ep, err := utils.PostPara(r, "ep")
if err != nil {
utils.SendErrorResponse(w, "Invalid ep given")
return
}
creds, err := utils.PostPara(r, "creds")
if err != nil {
utils.SendErrorResponse(w, "Invalid ptype given")
return
}
//Load the target proxy object from router
targetProxy, err := dynamicProxyRouter.LoadProxy(ep)
if err != nil {
utils.SendErrorResponse(w, err.Error())
return
}
//Try to marshal the content of creds into the suitable structure
newCredentials := []*dynamicproxy.BasicAuthUnhashedCredentials{}
err = json.Unmarshal([]byte(creds), &newCredentials)
if err != nil {
utils.SendErrorResponse(w, "Malformed credential data")
return
}
//Merge the credentials into the original config
//If a new username exists in old config with no pw given, keep the old pw hash
//If a new username is found with new password, hash it and push to credential slice
mergedCredentials := []*dynamicproxy.BasicAuthCredentials{}
for _, credential := range newCredentials {
if credential.Password == "" {
//Check if exists in the old credential files
keepUnchange := false
for _, oldCredEntry := range targetProxy.BasicAuthCredentials {
if oldCredEntry.Username == credential.Username {
//Exists! Reuse the old hash
mergedCredentials = append(mergedCredentials, &dynamicproxy.BasicAuthCredentials{
Username: oldCredEntry.Username,
PasswordHash: oldCredEntry.PasswordHash,
})
keepUnchange = true
}
}
if !keepUnchange {
//This is a new username with no pw given
utils.SendErrorResponse(w, "Access password for "+credential.Username+" is empty!")
return
}
} else {
//This username have given password
mergedCredentials = append(mergedCredentials, &dynamicproxy.BasicAuthCredentials{
Username: credential.Username,
PasswordHash: auth.Hash(credential.Password),
})
}
}
targetProxy.BasicAuthCredentials = mergedCredentials
//Save it to file
SaveReverseProxyConfig(targetProxy)
//Replace runtime configuration
targetProxy.UpdateToRuntime()
utils.SendOK(w)
} else {
http.Error(w, "invalid usage", http.StatusMethodNotAllowed)
}
}
// List, Update or Remove the exception paths for basic auth.
func ListProxyBasicAuthExceptionPaths(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
}
ep, err := utils.GetPara(r, "ep")
if err != nil {
utils.SendErrorResponse(w, "Invalid ep given")
return
}
//Load the target proxy object from router
targetProxy, err := dynamicProxyRouter.LoadProxy(ep)
if err != nil {
utils.SendErrorResponse(w, err.Error())
return
}
//List all the exception paths for this proxy
results := targetProxy.BasicAuthExceptionRules
if results == nil {
//It is a config from a really old version of zoraxy. Overwrite it with empty array
results = []*dynamicproxy.BasicAuthExceptionRule{}
}
js, _ := json.Marshal(results)
utils.SendJSONResponse(w, string(js))
return
}
func AddProxyBasicAuthExceptionPaths(w http.ResponseWriter, r *http.Request) {
ep, err := utils.PostPara(r, "ep")
if err != nil {
utils.SendErrorResponse(w, "Invalid ep given")
return
}
matchingPrefix, err := utils.PostPara(r, "prefix")
if err != nil {
utils.SendErrorResponse(w, "Invalid matching prefix given")
return
}
//Load the target proxy object from router
targetProxy, err := dynamicProxyRouter.LoadProxy(ep)
if err != nil {
utils.SendErrorResponse(w, err.Error())
return
}
//Check if the prefix starts with /. If not, prepend it
if !strings.HasPrefix(matchingPrefix, "/") {
matchingPrefix = "/" + matchingPrefix
}
//Add a new exception rule if it is not already exists
alreadyExists := false
for _, thisExceptionRule := range targetProxy.BasicAuthExceptionRules {
if thisExceptionRule.PathPrefix == matchingPrefix {
alreadyExists = true
break
}
}
if alreadyExists {
utils.SendErrorResponse(w, "This matching path already exists")
return
}
targetProxy.BasicAuthExceptionRules = append(targetProxy.BasicAuthExceptionRules, &dynamicproxy.BasicAuthExceptionRule{
PathPrefix: strings.TrimSpace(matchingPrefix),
})
//Save configs to runtime and file
targetProxy.UpdateToRuntime()
SaveReverseProxyConfig(targetProxy)
utils.SendOK(w)
}
func RemoveProxyBasicAuthExceptionPaths(w http.ResponseWriter, r *http.Request) {
// Delete a rule
ep, err := utils.PostPara(r, "ep")
if err != nil {
utils.SendErrorResponse(w, "Invalid ep given")
return
}
matchingPrefix, err := utils.PostPara(r, "prefix")
if err != nil {
utils.SendErrorResponse(w, "Invalid matching prefix given")
return
}
// Load the target proxy object from router
targetProxy, err := dynamicProxyRouter.LoadProxy(ep)
if err != nil {
utils.SendErrorResponse(w, err.Error())
return
}
newExceptionRuleList := []*dynamicproxy.BasicAuthExceptionRule{}
matchingExists := false
for _, thisExceptionalRule := range targetProxy.BasicAuthExceptionRules {
if thisExceptionalRule.PathPrefix != matchingPrefix {
newExceptionRuleList = append(newExceptionRuleList, thisExceptionalRule)
} else {
matchingExists = true
}
}
if !matchingExists {
utils.SendErrorResponse(w, "target matching rule not exists")
return
}
targetProxy.BasicAuthExceptionRules = newExceptionRuleList
// Save configs to runtime and file
targetProxy.UpdateToRuntime()
SaveReverseProxyConfig(targetProxy)
utils.SendOK(w)
}
// Report the current status of the reverse proxy server
func ReverseProxyStatus(w http.ResponseWriter, r *http.Request) {
js, _ := json.Marshal(dynamicProxyRouter)
utils.SendJSONResponse(w, string(js))
}
// Toggle a certain rule on and off
func ReverseProxyToggleRuleSet(w http.ResponseWriter, r *http.Request) {
//No need to check for type as root cannot be turned off
ep, err := utils.PostPara(r, "ep")
if err != nil {
utils.SendErrorResponse(w, "invalid ep given")
return
}
targetProxyRule, err := dynamicProxyRouter.LoadProxy(ep)
if err != nil {
utils.SendErrorResponse(w, "invalid endpoint given")
return
}
enableStr, err := utils.PostPara(r, "enable")
if err != nil {
enableStr = "true"
}
//Flip the enable and disabled tag state
ruleDisabled := enableStr == "false"
targetProxyRule.Disabled = ruleDisabled
err = SaveReverseProxyConfig(targetProxyRule)
if err != nil {
utils.SendErrorResponse(w, "unable to save updated rule")
return
}
utils.SendOK(w)
}
func ReverseProxyListDetail(w http.ResponseWriter, r *http.Request) {
eptype, err := utils.PostPara(r, "type") //Support root and host
if err != nil {
utils.SendErrorResponse(w, "type not defined")
return
}
if eptype == "host" {
epname, err := utils.PostPara(r, "epname")
if err != nil {
utils.SendErrorResponse(w, "epname not defined")
return
}
endpointRaw, ok := dynamicProxyRouter.ProxyEndpoints.Load(epname)
if !ok {
utils.SendErrorResponse(w, "proxy rule not found")
return
}
targetEndpoint := dynamicproxy.CopyEndpoint(endpointRaw.(*dynamicproxy.ProxyEndpoint))
js, _ := json.Marshal(targetEndpoint)
utils.SendJSONResponse(w, string(js))
} else if eptype == "root" {
js, _ := json.Marshal(dynamicProxyRouter.Root)
utils.SendJSONResponse(w, string(js))
} else {
utils.SendErrorResponse(w, "Invalid type given")
}
}
func ReverseProxyList(w http.ResponseWriter, r *http.Request) {
eptype, err := utils.PostPara(r, "type") //Support root and host
if err != nil {
utils.SendErrorResponse(w, "type not defined")
return
}
if eptype == "host" {
results := []*dynamicproxy.ProxyEndpoint{}
dynamicProxyRouter.ProxyEndpoints.Range(func(key, value interface{}) bool {
thisEndpoint := dynamicproxy.CopyEndpoint(value.(*dynamicproxy.ProxyEndpoint))
//Clear the auth passwords before showing to front-end
cleanedCredentials := []*dynamicproxy.BasicAuthCredentials{}
for _, user := range thisEndpoint.BasicAuthCredentials {
cleanedCredentials = append(cleanedCredentials, &dynamicproxy.BasicAuthCredentials{
Username: user.Username,
PasswordHash: "",
})
}
thisEndpoint.BasicAuthCredentials = cleanedCredentials
results = append(results, thisEndpoint)
return true
})
sort.Slice(results, func(i, j int) bool {
return results[i].Domain < results[j].Domain
})
js, _ := json.Marshal(results)
utils.SendJSONResponse(w, string(js))
} else if eptype == "root" {
js, _ := json.Marshal(dynamicProxyRouter.Root)
utils.SendJSONResponse(w, string(js))
} else {
utils.SendErrorResponse(w, "Invalid type given")
}
}
// Handle port 80 incoming traffics
func HandleUpdatePort80Listener(w http.ResponseWriter, r *http.Request) {
enabled, err := utils.GetPara(r, "enable")
if err != nil {
//Load the current status
currentEnabled := false
err = sysdb.Read("settings", "listenP80", ¤tEnabled)
if err != nil {
utils.SendErrorResponse(w, err.Error())
return
}
js, _ := json.Marshal(currentEnabled)
utils.SendJSONResponse(w, string(js))
} else {
if enabled == "true" {
sysdb.Write("settings", "listenP80", true)
SystemWideLogger.Println("Enabling port 80 listener")
dynamicProxyRouter.UpdatePort80ListenerState(true)
} else if enabled == "false" {
sysdb.Write("settings", "listenP80", false)
SystemWideLogger.Println("Disabling port 80 listener")
dynamicProxyRouter.UpdatePort80ListenerState(false)
} else {
utils.SendErrorResponse(w, "invalid mode given: "+enabled)
}
utils.SendOK(w)
}
}
// Handle https redirect
func HandleUpdateHttpsRedirect(w http.ResponseWriter, r *http.Request) {
useRedirect, err := utils.GetPara(r, "set")
if err != nil {
currentRedirectToHttps := false
//Load the current status
err = sysdb.Read("settings", "redirect", ¤tRedirectToHttps)
if err != nil {
utils.SendErrorResponse(w, err.Error())
return
}
js, _ := json.Marshal(currentRedirectToHttps)
utils.SendJSONResponse(w, string(js))
} else {
if dynamicProxyRouter.Option.Port == 80 {
utils.SendErrorResponse(w, "This option is not available when listening on port 80")
return
}
if useRedirect == "true" {
sysdb.Write("settings", "redirect", true)
SystemWideLogger.Println("Updating force HTTPS redirection to true")
dynamicProxyRouter.UpdateHttpToHttpsRedirectSetting(true)
} else if useRedirect == "false" {
sysdb.Write("settings", "redirect", false)
SystemWideLogger.Println("Updating force HTTPS redirection to false")
dynamicProxyRouter.UpdateHttpToHttpsRedirectSetting(false)
}
utils.SendOK(w)
}
}
// Handle checking if the current user is accessing via the reverse proxied interface
// Of the management interface.
func HandleManagementProxyCheck(w http.ResponseWriter, r *http.Request) {
isProxied := dynamicProxyRouter.IsProxiedSubdomain(r)
js, _ := json.Marshal(isProxied)
utils.SendJSONResponse(w, string(js))
}
func HandleDevelopmentModeChange(w http.ResponseWriter, r *http.Request) {
enableDevelopmentModeStr, err := utils.GetPara(r, "enable")
if err != nil {
//Load the current development mode toggle state
js, _ := json.Marshal(dynamicProxyRouter.Option.NoCache)
utils.SendJSONResponse(w, string(js))
} else {
//Write changes to runtime
enableDevelopmentMode := false
if enableDevelopmentModeStr == "true" {
enableDevelopmentMode = true
}
//Write changes to runtime
dynamicProxyRouter.Option.NoCache = enableDevelopmentMode
//Write changes to database
sysdb.Write("settings", "devMode", enableDevelopmentMode)
utils.SendOK(w)
}
}
// Handle incoming port set. Change the current proxy incoming port
func HandleIncomingPortSet(w http.ResponseWriter, r *http.Request) {
newIncomingPort, err := utils.PostPara(r, "incoming")
if err != nil {
utils.SendErrorResponse(w, "invalid incoming port given")
return
}