forked from Ysurac/openmptcprouter-vps-admin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathomr-admin.py
executable file
·2641 lines (2436 loc) · 134 KB
/
omr-admin.py
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
#!/usr/bin/env python3
#
# Copyright (C) 2018-2022 Ycarus (Yannick Chabanois) <[email protected]> for OpenMPTCProuter
#
# This is free software, licensed under the GNU General Public License v3.0.
# See /LICENSE for more information.
#
import json
import base64
import secrets
import uuid
import configparser
import argparse
import subprocess
import os
import sys
import socket
import re
import hashlib
import pathlib
import psutil
import time
import uuid
from pprint import pprint
from datetime import datetime, timedelta
from tempfile import mkstemp
from typing import List, Optional
from shutil import move
from enum import Enum
from os import path
import logging
import uvicorn
import jwt
from jwt import PyJWTError
from netaddr import *
from ipaddress import ip_address, IPv4Address, IPv6Address
from netjsonconfig import OpenWrt
from fastapi import Depends, FastAPI, HTTPException, Security, Query, Request
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes, OAuth2
from passlib.context import CryptContext
from fastapi.encoders import jsonable_encoder
from fastapi.security.base import SecurityBase
from fastapi.security.utils import get_authorization_scheme_param
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel
from fastapi.openapi.utils import get_openapi
from fastapi.openapi.models import SecurityBase as SecurityBaseModel
from fastapi.responses import StreamingResponse, FileResponse
from pydantic import BaseModel, ValidationError # pylint: disable=E0611
from starlette.status import HTTP_403_FORBIDDEN
from starlette.responses import RedirectResponse, Response, JSONResponse
#from starlette.requests import Request
import netifaces
LOG = logging.getLogger('api')
LOG.setLevel(logging.ERROR)
#LOG.setLevel(logging.DEBUG)
# Generate a random secret key
SECRET_KEY = uuid.uuid4().hex
JWT_SECRET_KEY = uuid.uuid4().hex
PERMANENT_SESSION_LIFETIME = timedelta(hours=24)
ACCESS_TOKEN_EXPIRE_MINUTES = 1440
ALGORITHM = "HS256"
# Get main net interface
FILE = open('/etc/shorewall/params.net', "r")
READ = FILE.read()
IFACE = None
for line in READ.splitlines():
if 'NET_IFACE=' in line:
IFACE = line.split('=', 1)[1]
FILE.close()
# Get ipv6 net interface
FILE = open('/etc/shorewall6/params.net', "r")
READ = FILE.read()
IFACE6 = None
for line in READ.splitlines():
if 'NET_IFACE=' in line:
IFACE6 = line.split('=', 1)[1]
FILE.close()
# Get interface rx/tx
def get_bytes(t, iface='eth0'):
if path.exists('/sys/class/net/' + iface + '/statistics/' + t + '_bytes'):
with open('/sys/class/net/' + iface + '/statistics/' + t + '_bytes', 'r') as f:
data = f.read()
return int(data)
return 0
def get_bytes_ss(port):
try:
ss_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ss_socket.settimeout(1)
ss_socket.sendto('ping'.encode(), ("127.0.0.1", 8839))
ss_recv = ss_socket.recv(1024)
except socket.timeout as err:
LOG.debug("Shadowsocks stats timeout (" + str(err) + ")")
return 0
except socket.error as err:
LOG.debug("Shadowsocks stats error (" + str(err) + ")")
return 0
json_txt = ss_recv.decode("utf-8").replace('stat: ', '')
result = json.loads(json_txt)
if str(port) in result:
return result[str(port)]
return 0
def get_bytes_v2ray(t,user):
if t == "tx":
side="downlink"
else:
side="uplink"
try:
data = subprocess.check_output('/usr/bin/v2ctl api --server=127.0.0.1:10085 StatsService.GetStats ' + "'" + 'name: "user>>>' + user + '>>>traffic>>>' + side + '"' + "'" + ' 2>/dev/null | grep value | cut -d: -f2 | tr -d " "', shell = True)
except:
return 0
if data.decode("utf-8") != '':
return int(data.decode("utf-8"))
else:
return 0
def checkIfProcessRunning(processName):
for proc in psutil.process_iter():
try:
if processName.lower() in proc.name().lower():
return True
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
return False;
def file_as_bytes(file):
with file:
return file.read()
def get_username_from_userid(userid):
if userid == 0:
return 'openmptcprouter'
with open('/etc/openmptcprouter-vps-admin/omr-admin-config.json') as f:
content = f.read()
content = re.sub(",\s*}", "}", content) # pylint: disable=W1401
try:
data = json.loads(content)
except ValueError as e:
return {'error': 'Config file not readable', 'route': 'get_username'}
for user in data['users'][0]:
if 'userid' in data['users'][0][user] and int(data['users'][0][user]['userid']) == userid:
return user
return ''
def check_username_serial(username, serial):
with open('/etc/openmptcprouter-vps-admin/omr-admin-config.json') as f:
content = f.read()
content = re.sub(",\s*}", "}", content) # pylint: disable=W1401
try:
data = json.loads(content)
except ValueError as e:
return {'error': 'Config file not readable', 'route': 'check_serial'}
if 'serial_enforce' not in data or data['serial_enforce'] == False:
return True
if 'serial' not in data['users'][0][username]:
data['users'][0][username]['serial'] = serial
if data:
with open('/etc/openmptcprouter-vps-admin/omr-admin-config.json', 'w') as outfile:
json.dump(data, outfile, indent=4)
return True
if data['users'][0][username]['serial'] == serial:
return True
if 'serial_error' not in data['users'][0][username]:
data['users'][0][username]['serial_error'] = 1
else:
data['users'][0][username]['serial_error'] = int(data['users'][0][username]['serial_error']) + 1
if data:
with open('/etc/openmptcprouter-vps-admin/omr-admin-config.json', 'w') as outfile:
json.dump(data, outfile, indent=4)
else:
LOG.debug("Empty data for check_username_serial")
return False
def set_global_param(key, value):
with open('/etc/openmptcprouter-vps-admin/omr-admin-config.json') as f:
content = f.read()
content = re.sub(",\s*}", "}", content) # pylint: disable=W1401
try:
data = json.loads(content)
except ValueError as e:
return {'error': 'Config file not readable', 'route': 'global_param'}
data[key] = value
if data:
with open('/etc/openmptcprouter-vps-admin/omr-admin-config.json', 'w') as outfile:
json.dump(data, outfile, indent=4)
else:
LOG.debug("Empty data for set_global_param")
def modif_config_user(user, changes):
with open('/etc/openmptcprouter-vps-admin/omr-admin-config.json') as f:
content = json.load(f)
content['users'][0][user].update(changes)
if content:
with open('/etc/openmptcprouter-vps-admin/omr-admin-config.json', 'w') as f:
json.dump(content, f, indent=4)
else:
LOG.debug("Empty data for modif_config_user")
def add_ss_user(port, key, userid=0, ip=''):
with open('/etc/shadowsocks-libev/manager.json') as f:
content = f.read()
content = re.sub(",\s*}", "}", content) # pylint: disable=W1401
data = json.loads(content)
if ip == '' and 'port_key' in data:
if port is None or port == '' or port == 0 or port == 'None':
port = int(max(data['port_key'], key=int)) + 1
data['port_key'][str(port)] = key
else:
if 'port_conf' not in data:
data['port_conf'] = {}
if 'port_key' in data:
for old_port in data['port_key']:
data['port_conf'][old_port] = {'key': data['port_key'][old_port]}
del data['port_key']
if port == '' or port == "None" or port is None or port == 0:
port = int(max(data['port_conf'], key=int)) + 1
if ip != '':
data['port_conf'][str(port)] = {'key': key, 'local_address': ip, 'userid': userid}
else:
data['port_conf'][str(port)] = {'key': key, 'userid': userid}
with open('/etc/shadowsocks-libev/manager.json', 'w') as f:
json.dump(data, f, indent=4)
try:
ss_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
if ip != '':
data = 'add: {"server_port": ' + str(port) + ', "key": "' + key + '", "local_addr": "' + ip + '"}'
else:
data = 'add: {"server_port": ' + str(port) + ', "key": "' + key + '"}'
ss_socket.settimeout(1)
ss_socket.sendto(data.encode(), ("127.0.0.1", 8839))
except socket.timeout as err:
LOG.debug("Shadowsocks add timeout (" + str(err) + ")")
except socket.error as err:
LOG.debug("Shadowsocks add error (" + str(err) + ")")
return port
def remove_ss_user(port):
with open('/etc/shadowsocks-libev/manager.json') as f:
content = f.read()
content = re.sub(",\s*}", "}", content) # pylint: disable=W1401
data = json.loads(content)
if 'port_key' in data:
del data['port_key'][str(port)]
else:
del data['port_conf'][str(port)]
with open('/etc/shadowsocks-libev/manager.json', 'w') as f:
json.dump(data, f, indent=4)
try:
ss_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
data = 'remove: {"server_port": ' + str(port) + '}'
ss_socket.settimeout(1)
ss_socket.sendto(data.encode(), ("127.0.0.1", 8839))
except socket.timeout as err:
LOG.debug("Shadowsocks remove timeout (" + str(err) + ")")
except socket.error as err:
LOG.debug("Shadowsocks remove error (" + str(err) + ")")
def v2ray_add_user(user, restart=1):
v2rayuuid = str(uuid.uuid1())
initial_md5 = hashlib.md5(file_as_bytes(open('/etc/v2ray/v2ray-server.json', 'rb'))).hexdigest()
with open('/etc/v2ray/v2ray-server.json') as f:
data = json.load(f)
exist = 0
for inbounds in data['inbounds']:
if inbounds['tag'] == 'omrin-tunnel':
inbounds['settings']['clients'].append({'id': v2rayuuid, 'level': 0, 'alterId': 0, 'email': user})
with open('/etc/v2ray/v2ray-server.json', 'w') as f:
json.dump(data, f, indent=4)
final_md5 = hashlib.md5(file_as_bytes(open('/etc/v2ray/v2ray-server.json', 'rb'))).hexdigest()
if initial_md5 != final_md5 and restart == 1:
os.system("systemctl -q restart v2ray")
return v2rayuuid
def v2ray_del_user(user, restart=1):
v2rayuuid = str(uuid.uuid1())
initial_md5 = hashlib.md5(file_as_bytes(open('/etc/v2ray/v2ray-server.json', 'rb'))).hexdigest()
with open('/etc/v2ray/v2ray-server.json') as f:
data = json.load(f)
for inbounds in data['inbounds']:
if inbounds['tag'] == 'omrin-tunnel':
for v2rayuser in inbounds['settings']['clients']:
if v2rayuser['email'] == user:
inbounds['settings']['clients'].remove(v2rayuser)
with open('/etc/v2ray/v2ray-server.json', 'w') as f:
json.dump(data, f, indent=4)
final_md5 = hashlib.md5(file_as_bytes(open('/etc/v2ray/v2ray-server.json', 'rb'))).hexdigest()
if initial_md5 != final_md5 and restart == 1:
os.system("systemctl -q restart v2ray")
def v2ray_add_outbound(tag,ip, restart=1):
initial_md5 = hashlib.md5(file_as_bytes(open('/etc/v2ray/v2ray-server.json', 'rb'))).hexdigest()
with open('/etc/v2ray/v2ray-server.json') as f:
data = json.load(f)
data['outbounds'].append({'protocol': 'freedom', 'settings': { 'userLevel': 0 }, 'tag': tag, 'sendThrough': ip})
with open('/etc/v2ray/v2ray-server.json', 'w') as f:
json.dump(data, f, indent=4)
final_md5 = hashlib.md5(file_as_bytes(open('/etc/v2ray/v2ray-server.json', 'rb'))).hexdigest()
if initial_md5 != final_md5 and restart == 1:
os.system("systemctl -q restart v2ray")
def v2ray_del_outbound(tag, restart=1):
initial_md5 = hashlib.md5(file_as_bytes(open('/etc/v2ray/v2ray-server.json', 'rb'))).hexdigest()
with open('/etc/v2ray/v2ray-server.json') as f:
data = json.load(f)
for outbounds in data['outbounds']:
if outbounds['tag'] == tag:
data['outbounds'].remove(outbounds)
with open('/etc/v2ray/v2ray-server.json', 'w') as f:
json.dump(data, f, indent=4)
final_md5 = hashlib.md5(file_as_bytes(open('/etc/v2ray/v2ray-server.json', 'rb'))).hexdigest()
if initial_md5 != final_md5 and restart == 1:
os.system("systemctl -q restart v2ray")
def v2ray_add_routing(tag, restart=1):
initial_md5 = hashlib.md5(file_as_bytes(open('/etc/v2ray/v2ray-server.json', 'rb'))).hexdigest()
with open('/etc/v2ray/v2ray-server.json') as f:
data = json.load(f)
data['routing']['rules'].append({'type': 'field', 'inboundTag': ( 'omrintunnel' ), 'outboundTag': tag})
with open('/etc/v2ray/v2ray-server.json', 'w') as f:
json.dump(data, f, indent=4)
final_md5 = hashlib.md5(file_as_bytes(open('/etc/v2ray/v2ray-server.json', 'rb'))).hexdigest()
if initial_md5 != final_md5 and restart == 1:
os.system("systemctl -q restart v2ray")
def v2ray_del_routing(tag, restart=1):
initial_md5 = hashlib.md5(file_as_bytes(open('/etc/v2ray/v2ray-server.json', 'rb'))).hexdigest()
with open('/etc/v2ray/v2ray-server.json') as f:
data = json.load(f)
for rules in data['routing']['rules']:
if rules['outboundTag'] == tag:
data['routing']['rules'].remove(rules)
with open('/etc/v2ray/v2ray-server.json', 'w') as f:
json.dump(data, f, indent=4)
final_md5 = hashlib.md5(file_as_bytes(open('/etc/v2ray/v2ray-server.json', 'rb'))).hexdigest()
if initial_md5 != final_md5 and restart == 1:
os.system("systemctl -q restart v2ray")
def add_gre_tunnels():
nbip = 0
allips = []
for intf in netifaces.interfaces():
addrs = netifaces.ifaddresses(intf)
try:
ipv4_addr_list = addrs[netifaces.AF_INET]
for ip_info in ipv4_addr_list:
addr = ip_info['addr']
if not IPAddress(addr).is_private() and not IPAddress(addr).is_reserved():
allips.append(addr)
nbip = nbip + 1
except Exception as exception:
pass
if nbip > 1:
nbgre = 0
nbip = 0
initial_md5 = hashlib.md5(file_as_bytes(open('/etc/shorewall/snat', 'rb'))).hexdigest()
for intf in netifaces.interfaces():
addrs = netifaces.ifaddresses(intf)
try:
ipv4_addr_list = addrs[netifaces.AF_INET]
for ip_info in ipv4_addr_list:
addr = ip_info['addr']
if not IPAddress(addr).is_private() and not IPAddress(addr).is_reserved():
netmask = ip_info['netmask']
ip = IPNetwork('10.255.249.0/24')
with open('/etc/openmptcprouter-vps-admin/omr-admin-config.json') as f:
content = json.load(f)
for user in content['users'][0]:
if user != "admin":
subnets = ip.subnet(30)
network = list(subnets)[nbgre]
nbgre = nbgre + 1
userid = 0
username = user
iface = intf.split(':')[0]
if 'userid' in content['users'][0][user]:
userid = content['users'][0][user]['userid']
if 'username' in content['users'][0][user]:
username = content['users'][0][user]['username']
gre_intf = 'gre-user' + str(userid) + '-ip' + str(nbip)
with open('/etc/openmptcprouter-vps-admin/intf/' + gre_intf, 'w') as n:
n.write('INTF=' + str(intf.split(':')[0]) + "\n")
n.write('INTFADDR=' + str(addr) + "\n")
n.write('INTFNETMASK=' + str(netmask) + "\n")
n.write('NETWORK=' + str(network) + "\n")
n.write('LOCALIP=' + str(list(network)[1]) + "\n")
n.write('REMOTEIP=' + str(list(network)[2]) + "\n")
n.write('NETMASK=255.255.255.252' + "\n")
n.write('BROADCASTIP=' + str(network.broadcast) + "\n")
n.write('USERNAME=' + str(username) + "\n")
n.write('USERID=' + str(userid) + "\n")
fd, tmpfile = mkstemp()
with open('/etc/shorewall/snat', 'r') as h, open(tmpfile, 'a+') as n:
for line in h:
if not '# OMR GRE for public IP ' + str(addr) + ' for user ' + str(user) in line:
n.write(line)
n.write('SNAT(' + str(addr) + ') ' + str(network) + ' ' + str(iface) + ' # OMR GRE for public IP ' + str(addr) + ' for user ' + str(user) + "\n")
n.write('SNAT(' + str(list(network)[1]) + ') - ' + gre_intf + ' # OMR GRE for public IP ' + str(addr) + ' for user ' + str(user) + "\n")
os.close(fd)
move(tmpfile, '/etc/shorewall/snat')
#fd, tmpfile = mkstemp()
#with open('/etc/shorewall/interfaces', 'r') as h, open(tmpfile, 'a+') as n:
# for line in h:
# if not 'gre-user' + str(userid) + '-ip' + str(nbip) in line:
# n.write(line)
# n.write('vpn gre-user' + str(userid) + '-ip' + str(nbip) + ' nosmurfs,tcpflags' + "\n")
#os.close(fd)
#move(tmpfile, '/etc/shorewall/interfaces')
if str(iface) != IFACE:
fd, tmpfile = mkstemp()
with open('/etc/shorewall/interfaces', 'r') as h, open(tmpfile, 'a+') as n:
for line in h:
if not str(iface) in line:
n.write(line)
n.write('net ' + str(iface) + ' dhcp,nosmurfs,tcpflags,routefilter,sourceroute=0' + "\n")
os.close(fd)
move(tmpfile, '/etc/shorewall/interfaces')
user_gre_tunnels = {}
if 'gre_tunnels' in content['users'][0][user]:
user_gre_tunnels = content['users'][0][user]['gre_tunnels']
if not gre_intf in user_gre_tunnels or user_gre_tunnels[gre_intf]['public_ip'] != str(addr):
with open('/etc/shadowsocks-libev/manager.json') as g:
contentss = g.read()
contentss = re.sub(",\s*}", "}", contentss) # pylint: disable=W1401
datass = json.loads(contentss)
ss_port = content['users'][0][user]['shadowsocks_port']
if 'port_key' in datass:
ss_key = datass['port_key'][str(ss_port)]
if 'port_conf' in datass:
ss_key = datass['port_conf'][str(ss_port)]['key']
if gre_intf not in user_gre_tunnels:
user_gre_tunnels[gre_intf] = {}
user_gre_tunnels[gre_intf] = {'shadowsocks_port': str(add_ss_user('', ss_key, userid, str(addr))), 'local_ip': str(list(network)[1]), 'remote_ip': str(list(network)[2]), 'public_ip': str(addr)}
#user_gre_tunnels[gre_intf] = {'local_ip': str(list(network)[1]), 'remote_ip': str(list(network)[2]), 'public_ip': str(addr)}
modif_config_user(user, {'gre_tunnels': user_gre_tunnels})
nbip = nbip + 1
except Exception as exception:
pass
final_md5 = hashlib.md5(file_as_bytes(open('/etc/shorewall/snat', 'rb'))).hexdigest()
if initial_md5 != final_md5:
os.system("systemctl -q reload shorewall")
os.system("systemctl -q restart shadowsocks-libev-manager@manager")
set_global_param('allips', allips)
add_gre_tunnels()
def add_glorytun_tcp(userid):
port = '650{:02d}'.format(userid)
ip = IPNetwork('10.255.255.0/24')
subnets = ip.subnet(30)
network = list(subnets)[userid]
with open('/etc/glorytun-tcp/tun0', 'r') as f, \
open('/etc/glorytun-tcp/tun' + str(userid), 'w') as n:
for line in f:
if 'PORT' in line:
n.write('PORT=' + port + "\n")
elif 'DEV' in line:
n.write('DEV=tun' + str(userid) + "\n")
elif (not 'LOCALIP' in line
and not 'REMOTEIP' in line
and not 'BROADCASTIP' in line
and not line == "\n"):
n.write(line)
n.write("\n" + 'LOCALIP=' + str(list(network)[1]) + "\n")
n.write('REMOTEIP=' + str(list(network)[2]) + "\n")
n.write('BROADCASTIP=' + str(network.broadcast) + "\n")
glorytun_tcp_key = secrets.token_hex(32)
with open('/etc/glorytun-tcp/tun' + str(userid) + '.key', 'w') as f:
f.write(glorytun_tcp_key.upper())
os.system("systemctl -q enable glorytun-tcp@tun" + str(userid))
os.system("systemctl -q restart glorytun-tcp@tun" + str(userid))
def remove_glorytun_tcp(userid):
os.system("systemctl -q disable glorytun-tcp@tun" + str(userid))
os.system("systemctl -q stop glorytun-tcp@tun" + str(userid))
os.remove('/etc/glorytun-tcp/tun' + str(userid) + '.key')
os.remove('/etc/glorytun-tcp/tun' + str(userid))
def add_glorytun_udp(userid):
port = '650{:02d}'.format(userid)
ip = IPNetwork('10.255.254.0/24')
subnets = ip.subnet(30)
network = list(subnets)[userid]
with open('/etc/glorytun-udp/tun0', 'r') as f, \
open('/etc/glorytun-udp/tun' + str(userid), 'w') as n:
for line in f:
if 'BIND_PORT' in line:
n.write('BIND_PORT=' + port + "\n")
elif 'DEV' in line:
n.write('DEV=tun' + str(userid) + "\n")
elif (not 'LOCALIP' in line
and not 'REMOTEIP' in line
and not 'BROADCASTIP' in line
and not line == "\n"):
n.write(line)
n.write("\n" + 'LOCALIP=' + str(list(network)[1]) + "\n")
n.write('REMOTEIP=' + str(list(network)[2]) + "\n")
n.write('BROADCASTIP=' + str(network.broadcast) + "\n")
with open('/etc/glorytun-tcp/tun' + str(userid) + '.key', 'r') as f, \
open('/etc/glorytun-udp/tun' + str(userid) + '.key', 'w') as n:
for line in f:
n.write(line)
os.system("systemctl -q enable glorytun-udp@tun" + str(userid))
os.system("systemctl -q restart glorytun-udp@tun" + str(userid))
def remove_glorytun_udp(userid):
os.system("systemctl -q disable glorytun-udp@tun" + str(userid))
os.system("systemctl -q stop glorytun-udp@tun" + str(userid))
os.remove('/etc/glorytun-udp/tun' + str(userid) + '.key')
os.remove('/etc/glorytun-udp/tun' + str(userid))
def add_dsvpn(userid):
port = '654{:02d}'.format(userid)
ip = IPNetwork('10.255.251.0/24')
subnets = ip.subnet(30)
network = list(subnets)[userid]
with open('/etc/dsvpn/dsvpn0', 'r') as f, open('/etc/dsvpn/dsvpn' + str(userid), 'w') as n:
for line in f:
if 'PORT' in line:
n.write('PORT=' + port + "\n")
elif 'DEV' in line:
n.write('DEV=dsvpn' + str(userid) + "\n")
elif 'LOCALTUNIP' in line:
n.write('LOCALTUNIP=' + str(list(network)[1]) + "\n")
elif 'REMOTETUNIP' in line:
n.write('REMOTETUNIP=' + str(list(network)[2]) + "\n")
else:
n.write(line)
dsvpn_key = secrets.token_hex(32)
with open('/etc/dsvpn/dsvpn' + str(userid) + '.key', 'w') as f:
f.write(dsvpn_key.upper())
os.system("systemctl -q enable dsvpn@dsvpn" + str(userid))
os.system("systemctl -q restart dsvpn@dsvpn" + str(userid))
def remove_dsvpn(userid):
os.system("systemctl -q disable dsvpn@dsvpn" + str(userid))
os.system("systemctl -q stop dsvpn@dsvpn" + str(userid))
os.remove('/etc/dsvpn/dsvpn' + str(userid))
os.remove('/etc/dsvpn/dsvpn' + str(userid) + '.key')
def ordered(obj):
if isinstance(obj, dict):
return sorted((k, ordered(v)) for k, v in obj.items())
if isinstance(obj, list):
return sorted(ordered(x) for x in obj)
else:
return obj
def v2ray_add_port(user, port, proto, name, destip, destport):
userid = user.userid
if userid is None:
userid = 0
tag = user.username + '_redir_' + proto + '_' + str(port) + '_to_' + destip + ':' + str(destport)
initial_md5 = hashlib.md5(file_as_bytes(open('/etc/v2ray/v2ray-server.json', 'rb'))).hexdigest()
with open('/etc/v2ray/v2ray-server.json') as f:
data = json.load(f)
exist = 0
for inbounds in data['inbounds']:
LOG.debug(inbounds)
if inbounds['tag'] == tag:
exist = 1
if exist == 0:
inbounds = {'tag': tag, 'port': int(port), 'protocol': 'dokodemo-door', 'settings': {'network': proto, 'port': int(destport), 'address': destip}}
#inbounds = {'tag': user.username + '_redir_' + proto + '_' + str(port), 'port': str(port), 'protocol': 'dokodemo-door', 'settings': {'network': proto, 'port': str(destport), 'address': destip}}
data['inbounds'].append(inbounds)
routing = {'type': 'field','inboundTag': [tag], 'outboundTag': 'OMRLan'}
data['routing']['rules'].append(routing)
with open('/etc/v2ray/v2ray-server.json', 'w') as f:
json.dump(data, f, indent=4)
final_md5 = hashlib.md5(file_as_bytes(open('/etc/v2ray/v2ray-server.json', 'rb'))).hexdigest()
if initial_md5 != final_md5:
os.system("systemctl -q restart v2ray")
def v2ray_del_port(user, port, proto, name, destip, destport):
userid = user.userid
if userid is None:
userid = 0
tag = user.username + '_redir_' + proto + '_' + str(port)
if destip != '':
tag = tag + '_to_' + destip + ':' + str(destport)
initial_md5 = hashlib.md5(file_as_bytes(open('/etc/v2ray/v2ray-server.json', 'rb'))).hexdigest()
with open('/etc/v2ray/v2ray-server.json') as f:
data = json.load(f)
for inbounds in data['inbounds']:
if inbounds['tag'] == tag:
data['inbounds'].remove(inbounds)
for routing in data['routing']['rules']:
if routing['inboundTag'][0] == tag:
data['routing']['rules'].remove(routing)
with open('/etc/v2ray/v2ray-server.json', 'w') as f:
json.dump(data, f, indent=4)
final_md5 = hashlib.md5(file_as_bytes(open('/etc/v2ray/v2ray-server.json', 'rb'))).hexdigest()
if initial_md5 != final_md5:
os.system("systemctl -q restart v2ray")
def shorewall_add_port(user, port, proto, name, fwtype='ACCEPT', source_dip='', dest_ip='', vpn='default', gencomment=''):
userid = user.userid
if userid is None:
userid = 0
initial_md5 = hashlib.md5(file_as_bytes(open('/etc/shorewall/rules', 'rb'))).hexdigest()
fd, tmpfile = mkstemp()
with open('/etc/shorewall/rules', 'r') as f, \
open(tmpfile, 'a+') as n:
for line in f:
if source_dip == '' and dest_ip == '':
if (fwtype == 'ACCEPT' and not port + ' # OMR open ' + name + ' port ' + proto + gencomment in line and not port + ' # OMR ' + user.username + ' open ' + name + ' port ' + proto + gencomment in line):
n.write(line)
elif fwtype == 'DNAT' and not port + ' # OMR redirect ' + name + ' port ' + proto + gencomment in line and not port + ' # OMR ' + user.username + ' redirect ' + name + ' port ' + proto + gencomment in line:
n.write(line)
else:
comment = ''
if source_dip != '':
comment = ' to ' + source_dip
if dest_ip != '':
comment = comment + ' from ' + dest_ip
if (fwtype == 'ACCEPT' and not '# OMR ' + user.username + ' open ' + name + ' port ' + proto + comment + gencomment in line):
n.write(line)
elif fwtype == 'DNAT' and not '# OMR ' + user.username + ' redirect ' + name + ' port ' + proto + comment + gencomment in line:
n.write(line)
if source_dip == '' and dest_ip == '':
if fwtype == 'ACCEPT':
n.write('ACCEPT net $FW ' + proto + ' ' + port + ' # OMR ' + user.username + ' open ' + name + ' port ' + proto + gencomment + "\n")
elif fwtype == 'DNAT' and userid == 0:
n.write('DNAT net vpn:$OMR_ADDR ' + proto + ' ' + port + ' # OMR ' + user.username + ' redirect ' + name + ' port ' + proto + gencomment + "\n")
elif fwtype == 'DNAT' and userid != 0:
n.write('DNAT net vpn:$OMR_ADDR_USER' + str(userid) + ' ' + proto + ' ' + port + ' # OMR ' + user.username + ' redirect ' + name + ' port ' + proto + gencomment + "\n")
else:
net = 'net'
comment = ''
if source_dip != '':
comment = ' to ' + source_dip
if dest_ip != '':
comment = comment + ' from ' + dest_ip
net = 'net:' + dest_ip
if fwtype == 'ACCEPT':
n.write('ACCEPT ' + net + ' $FW ' + proto + ' ' + port + ' - ' + source_dip + ' # OMR ' + user.username + ' open ' + name + ' port ' + proto + comment + gencomment + "\n")
elif fwtype == 'DNAT' and vpn != 'default':
n.write('DNAT ' + net + ' vpn:' + vpn + ' ' + proto + ' ' + port + ' - ' + source_dip + ' # OMR ' + user.username + ' redirect ' + name + ' port ' + proto + comment + gencomment + "\n")
#n.write('DNAT ' + net + ' vpn:$OMR_ADDR' + ' ' + proto + ' ' + port + ' - ' + source_dip + ' # OMR ' + user.username + ' redirect ' + name + ' port ' + proto + comment + "\n")
elif fwtype == 'DNAT' and userid == 0:
n.write('DNAT ' + net + ' vpn:$OMR_ADDR ' + proto + ' ' + port + ' - ' + source_dip + ' # OMR ' + user.username + ' redirect ' + name + ' port ' + proto + comment + gencomment + "\n")
elif fwtype == 'DNAT' and userid != 0:
n.write('DNAT ' + net + ' vpn:$OMR_ADDR_USER' + str(userid) + ' ' + proto + ' ' + port + ' - ' + source_dip + ' # OMR ' + user.username + ' redirect ' + name + ' port ' + proto + comment + gencomment + "\n")
os.close(fd)
move(tmpfile, '/etc/shorewall/rules')
final_md5 = hashlib.md5(file_as_bytes(open('/etc/shorewall/rules', 'rb'))).hexdigest()
if initial_md5 != final_md5:
os.system("systemctl -q reload shorewall")
def shorewall_del_port(username, port, proto, name, fwtype='ACCEPT', source_dip='', dest_ip='', gencomment=''):
initial_md5 = hashlib.md5(file_as_bytes(open('/etc/shorewall/rules', 'rb'))).hexdigest()
fd, tmpfile = mkstemp()
with open('/etc/shorewall/rules', 'r') as f, open(tmpfile, 'a+') as n:
for line in f:
if source_dip == '' and dest_ip == '':
if fwtype == 'ACCEPT' and not port + ' # OMR open ' + name + ' port ' + proto + gencomment in line and not port + ' # OMR ' + username + ' open ' + name + ' port ' + proto + gencomment in line:
n.write(line)
elif fwtype == 'DNAT' and not port + ' # OMR redirect ' + name + ' port ' + proto + gencomment in line and not port + ' # OMR ' + username + ' redirect ' + name + ' port ' + proto + gencomment in line:
n.write(line)
else:
comment = ''
if source_dip != '':
comment = ' to ' + source_dip
if dest_ip != '':
comment = comment + ' from ' + dest_ip
if fwtype == 'ACCEPT' and not '# OMR ' + username + ' open ' + name + ' port ' + proto + comment + gencomment in line:
n.write(line)
elif fwtype == 'DNAT' and not '# OMR ' + username + ' redirect ' + name + ' port ' + proto + comment + gencomment in line:
n.write(line)
os.close(fd)
move(tmpfile, '/etc/shorewall/rules')
final_md5 = hashlib.md5(file_as_bytes(open('/etc/shorewall/rules', 'rb'))).hexdigest()
if initial_md5 != final_md5:
os.system("systemctl -q reload shorewall")
def shorewall6_add_port(user, port, proto, name, fwtype='ACCEPT', source_dip='', dest_ip='', gencomment=''):
userid = user.userid
if userid is None:
userid = 0
initial_md5 = hashlib.md5(file_as_bytes(open('/etc/shorewall6/rules', 'rb'))).hexdigest()
fd, tmpfile = mkstemp()
with open('/etc/shorewall6/rules', 'r') as f, open(tmpfile, 'a+') as n:
for line in f:
if source_dip == '':
if fwtype == 'ACCEPT' and not port + ' # OMR open ' + name + ' port ' + proto + gencomment in line and not port + ' # OMR ' + user.username + ' open ' + name + ' port ' + proto + gencomment in line:
n.write(line)
elif fwtype == 'DNAT' and not port + ' # OMR redirect ' + name + ' port ' + proto + gencomment in line and not port + ' # OMR ' + user.username + ' redirect ' + name + ' port ' + proto + gencomment in line:
n.write(line)
else:
comment = ''
if source_dip != '':
comment = ' to ' + source_dip
if dest_ip != '':
comment = comment + ' from ' + dest_ip
if fwtype == 'ACCEPT' and not port + '# OMR ' + user.username + ' open ' + name + ' port ' + proto + comment + gencomment in line:
n.write(line)
elif fwtype == 'DNAT' and not port + '# OMR ' + user.username + ' redirect ' + name + ' port ' + proto + comment + gencomment in line:
n.write(line)
if source_dip == '':
if fwtype == 'ACCEPT':
n.write('ACCEPT net $FW ' + proto + ' ' + port + ' # OMR ' + user.username + ' open ' + name + ' port ' + proto + gencomment + "\n")
elif fwtype == 'DNAT' and userid == 0:
n.write('DNAT net vpn:$OMR_ADDR ' + proto + ' ' + port + ' # OMR ' + user.username + ' redirect ' + name + ' port ' + proto + gencomment + "\n")
elif fwtype == 'DNAT' and userid != 0:
n.write('DNAT net vpn:$OMR_ADDR_USER' + str(userid) + ' ' + proto + ' ' + port + ' # OMR ' + user.username + ' redirect ' + name + ' port ' + proto + gencomment + "\n")
else:
net = 'net'
comment = ''
if source_dip == '':
comment = ' to ' + source_dip
if dest_ip == '':
comment = comment + ' from ' + dest_ip
net = 'net:' + dest_ip
if fwtype == 'ACCEPT':
n.write('ACCEPT ' + net + ' $FW ' + proto + ' ' + port + ' - ' + source_dip + ' # OMR ' + user.username + ' open ' + name + ' port ' + proto + comment + gencomment + "\n")
elif fwtype == 'DNAT' and userid == 0:
n.write('DNAT ' + net + ' vpn:$OMR_ADDR ' + proto + ' ' + port + ' - ' + source_dip + ' # OMR ' + user.username + ' redirect ' + name + ' port ' + proto + comment + gencomment + "\n")
elif fwtype == 'DNAT' and userid != 0:
n.write('DNAT ' + net + ' vpn:$OMR_ADDR_USER' + str(userid) + ' ' + proto + ' ' + port + ' - ' + source_dip + ' # OMR ' + user.username + ' redirect ' + name + ' port ' + proto + comment + gencomment + "\n")
os.close(fd)
move(tmpfile, '/etc/shorewall6/rules')
final_md5 = hashlib.md5(file_as_bytes(open('/etc/shorewall6/rules', 'rb'))).hexdigest()
if initial_md5 != final_md5:
os.system("systemctl -q reload shorewall6")
def shorewall6_del_port(username, port, proto, name, fwtype='ACCEPT', source_dip='', dest_ip=''):
initial_md5 = hashlib.md5(file_as_bytes(open('/etc/shorewall6/rules', 'rb'))).hexdigest()
fd, tmpfile = mkstemp()
with open('/etc/shorewall6/rules', 'r') as f, open(tmpfile, 'a+') as n:
for line in f:
if source_dip == '':
if fwtype == 'ACCEPT' and not port + ' # OMR open ' + name + ' port ' + proto in line and not port + ' # OMR ' + username + ' open ' + name + ' port ' + proto + gencomment in line:
n.write(line)
elif fwtype == 'DNAT' and not port + ' # OMR redirect ' + name + ' port ' + proto in line and not port + ' # OMR ' + username + ' redirect ' + name + ' port ' + proto + gencomment in line:
n.write(line)
else:
if fwtype == 'ACCEPT' and not '# OMR ' + username + ' open ' + name + ' port ' + proto + ' to ' + source_dip + gencomment in line:
n.write(line)
elif fwtype == 'DNAT' and not '# OMR ' + username + ' redirect ' + name + ' port ' + proto + ' to ' + source_dip + gencomment in line:
n.write(line)
os.close(fd)
move(tmpfile, '/etc/shorewall6/rules')
final_md5 = hashlib.md5(file_as_bytes(open('/etc/shorewall6/rules', 'rb'))).hexdigest()
if initial_md5 != final_md5:
os.system("systemctl -q reload shorewall6")
def set_lastchange(sync=0):
with open('/etc/openmptcprouter-vps-admin/omr-admin-config.json') as f:
content = f.read()
content = re.sub(",\s*}", "}", content) # pylint: disable=W1401
try:
data = json.loads(content)
except ValueError as e:
return {'error': 'Config file not readable', 'route': 'lastchange'}
data["lastchange"] = time.time() + sync
if data:
with open('/etc/openmptcprouter-vps-admin/omr-admin-config.json', 'w') as outfile:
json.dump(data, outfile, indent=4)
else:
LOG.debug("Empty data for set_last_change")
with open('/etc/openmptcprouter-vps-admin/omr-admin-config.json') as f:
omr_config_data = json.load(f)
if 'debug' in omr_config_data and omr_config_data['debug']:
LOG.setLevel(logging.DEBUG)
fake_users_db = omr_config_data['users'][0]
def verify_password(plain_password, user_password):
if secrets.compare_digest(plain_password,user_password):
LOG.debug("password true")
return True
return False
def get_password_hash(password):
return password
def get_user(db, username: str):
if username in db:
user_dict = db[username]
return UserInDB(**user_dict)
def authenticate_user(fake_db, username: str, password: str):
user = get_user(fake_db, username)
if not user:
LOG.debug("user doesn't exist")
return False
if not verify_password(password, user.user_password):
LOG.debug("wrong password")
return False
return user
class Token(BaseModel):
access_token: str = None
token_type: str = None
class TokenData(BaseModel):
username: str = None
class User(BaseModel):
username: str
vpn: str = None
vpn_port: int = None
vpn_client_ip: str = None
permissions: str = 'rw'
shadowsocks_port: int = None
disabled: bool = 'false'
userid: int = None
class UserInDB(User):
user_password: str
# Add support for auth before seeing doc
class OAuth2PasswordBearerCookie(OAuth2):
def __init__(
self,
tokenUrl: str,
scheme_name: str = None,
scopes: dict = None,
auto_error: bool = True,
):
if not scopes:
scopes = {}
flows = OAuthFlowsModel(password={"tokenUrl": tokenUrl, "scopes": scopes})
super().__init__(flows=flows, scheme_name=scheme_name, auto_error=auto_error)
async def __call__(self, request: Request) -> Optional[str]:
header_authorization: str = request.headers.get("Authorization")
cookie_authorization: str = request.cookies.get("Authorization")
header_scheme, header_param = get_authorization_scheme_param(
header_authorization
)
cookie_scheme, cookie_param = get_authorization_scheme_param(
cookie_authorization
)
if header_scheme.lower() == "bearer":
authorization = True
scheme = header_scheme
param = header_param
elif cookie_scheme.lower() == "bearer":
authorization = True
scheme = cookie_scheme
param = cookie_param
else:
authorization = False
if not authorization or scheme.lower() != "bearer":
if self.auto_error:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
)
else:
return None
return param
class BasicAuth(SecurityBase):
def __init__(self, scheme_name: str = None, auto_error: bool = True):
self.scheme_name = scheme_name or self.__class__.__name__
self.model = SecurityBaseModel(type="http")
self.auto_error = auto_error
async def __call__(self, request: Request) -> Optional[str]:
authorization: str = request.headers.get("Authorization")
scheme, param = get_authorization_scheme_param(authorization)
if not authorization or scheme.lower() != "basic":
if self.auto_error:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
)
else:
return None
return param
basic_auth = BasicAuth(auto_error=False)
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearerCookie(tokenUrl="/token")
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None, title="OpenMPTCProuter Server API")
def create_access_token(*, data: dict, expires_delta: timedelta = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=60)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
async def get_current_user(token: str = Depends(oauth2_scheme)):
credentials_exception = HTTPException(
status_code=HTTP_403_FORBIDDEN,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
LOG.debug("get_current_user: Username not found")
raise credentials_exception
token_data = TokenData(username=username)
except PyJWTError:
raise credentials_exception
user = get_user(fake_users_db, username=token_data.username)
if user is None:
raise credentials_exception
return user
async def get_current_active_user(current_user: User = Depends(get_current_user)):
if current_user.disabled:
raise HTTPException(status_code=400, detail="Inactive user")
return current_user
# Show something at homepage
@app.get("/")
async def homepage():
return "Welcome to OpenMPTCProuter Server part"
# Provide a method to create access tokens. The create_jwt()
# function is used to actually generate the token
@app.post('/token', response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
user = authenticate_user(fake_users_db, form_data.username, form_data.password)
if not user:
LOG.debug("Incorrect username or password")
raise HTTPException(status_code=400, detail="Incorrect username or password")
# Identity can be any data that is json serializable
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": form_data.username}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
@app.get("/logout")
async def route_logout_and_remove_cookie():
response = RedirectResponse(url="/")
response.delete_cookie("Authorization")
return response
# Login for doc
@app.get("/login_basic")
async def login_basic(auth: BasicAuth = Depends(basic_auth)):
if not auth:
response = Response(headers={"WWW-Authenticate": "Basic"}, status_code=401)
return response
try:
decoded = base64.b64decode(auth).decode("ascii")
username, _, password = decoded.partition(":")
user = authenticate_user(fake_users_db, username, password)
if not user:
raise HTTPException(status_code=400, detail="Incorrect email or password")
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": username}, expires_delta=access_token_expires
)
token = jsonable_encoder(access_token)
response = RedirectResponse(url="/docs")
response.set_cookie(
"Authorization",
value=f"Bearer {token}",
httponly=True,
max_age=1800,
expires=1800,
)
return response
except:
response = Response(headers={"WWW-Authenticate": "Basic"}, status_code=401)
return response