Skip to content

Commit 5217c1f

Browse files
author
jose
committed
update 6.3.3
1 parent e8aa95f commit 5217c1f

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+1066
-878
lines changed

BTPanel/__init__.py

+82-124
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import sys,json,os,time,logging,re
1010
if sys.version_info[0] != 2:
1111
from imp import reload
12-
sys.path.insert(0,'class/')
12+
sys.path.insert(0,'/www/server/panel/class/')
1313
import public
1414
from flask import Flask
1515
app = Flask(__name__,template_folder="templates/" + public.GetConfigValue('template'))
@@ -19,6 +19,7 @@
1919
from werkzeug.contrib.cache import SimpleCache
2020
from werkzeug.wrappers import Response
2121
from flask_socketio import SocketIO,emit,send
22+
from threading import Lock
2223
dns_client = None
2324
app.config['DEBUG'] = os.path.exists('data/debug.pl')
2425

@@ -37,11 +38,11 @@
3738
socketio = SocketIO()
3839
socketio.init_app(app)
3940

40-
import common,db,jobs,uuid
41+
import common,db,jobs,uuid,ssh_terminal
4142
jobs.control_init()
4243
app.secret_key = uuid.UUID(int=uuid.getnode()).hex[-12:]
4344
local_ip = None
44-
45+
my_terms = {}
4546

4647
try:
4748
from flask_sqlalchemy import SQLAlchemy
@@ -67,7 +68,10 @@
6768
app.config['PERMANENT_SESSION_LIFETIME'] = 86400
6869
Session(app)
6970

70-
if s_sqlite: sdb.create_all()
71+
72+
if s_sqlite:
73+
sdb.create_all()
74+
public.ExecShell("chmod 600 /dev/shm/session.db")
7175

7276
from datetime import datetime
7377
import socket
@@ -89,11 +93,67 @@ def service_status():
8993
return 'True'
9094

9195

96+
97+
@socketio.on('connect')
98+
def socket_connect(msg=None):
99+
if not check_login():
100+
emit('server_response',{'data':public.getMsg('111')})
101+
return False
102+
103+
@socketio.on('webssh')
104+
def webssh(msg):
105+
if not check_login():
106+
session.clear()
107+
emit('server_response',"Panel session is lost, please re-login panel!")
108+
return None
109+
if not 'ssh_obj' in session:
110+
session['ssh_obj'] = ssh_terminal.ssh_terminal()
111+
session['ssh_obj'].send(msg)
112+
113+
114+
@app.route('/term_open',methods=method_all)
115+
def term_open():
116+
comReturn = comm.local()
117+
if comReturn: return comReturn
118+
args = get_input()
119+
if 'get_ssh_info' in args:
120+
key = 'ssh_' + args['host']
121+
if key in session:
122+
return public.getJson(session[key]),json_header
123+
return public.returnMsg(False,'Acquisition failed!')
124+
session['ssh_info'] = json.loads(args.data)
125+
key = 'ssh_' + session['ssh_info']['host']
126+
session[key] = session['ssh_info']
127+
s_file = '/www/server/panel/config/t_info.json'
128+
if 'is_save' in session['ssh_info']:
129+
public.writeFile(s_file,public.de_hexb(json.dumps(session['ssh_info'])))
130+
public.set_mode(s_file,600)
131+
else:
132+
if os.path.exists(s_file): os.remove(s_file)
133+
return public.returnJson(True,'Successful setup!');
134+
135+
@app.route('/reload_mod',methods=method_all)
136+
def reload_mod():
137+
comReturn = comm.local()
138+
if comReturn: return comReturn
139+
args = get_input()
140+
mod_name = None
141+
if 'mod_name' in args:
142+
mod_name = args.mod_name
143+
result = public.reload_mod(mod_name)
144+
if result: return public.returnJson(True,result),json_header
145+
return public.returnJson(False,'Reload failure!'),json_header
146+
92147
@app.before_request
93148
def request_check():
94149
if not request.path in ['/safe','/hook','/public']:
95150
ip_check = public.check_ip_panel()
96151
if ip_check: return ip_check
152+
153+
if request.path.find('/static/') != -1 or request.path == '/code':
154+
if not 'login' in session and not 'admin_auth' in session:
155+
session.clear()
156+
return abort(401)
97157
domain_check = public.check_domain_panel()
98158
if domain_check: return domain_check
99159
if public.is_local():
@@ -120,7 +180,9 @@ def request_end(reques = None):
120180
def send_authenticated():
121181
global local_ip
122182
if not local_ip: local_ip = public.GetLocalIp()
123-
return Response('', 401,{'WWW-Authenticate': 'Basic realm="%s"' % local_ip.strip()})
183+
result = Response('', 401,{'WWW-Authenticate': 'Basic realm="%s"' % local_ip.strip()})
184+
if not 'login' in session and not 'admin_auth' in session: session.clear()
185+
return result
124186

125187
@app.route('/',methods=method_all)
126188
def home():
@@ -462,7 +524,7 @@ def config(pdata = None):
462524
if public.is_local(): data['is_local'] = 'checked'
463525
return render_template( 'config.html',data=data)
464526
import config
465-
defs = ('get_qrcode_data','check_two_step','set_two_step_auth','get_key','get_php_session_path','set_php_session_path','get_cert_source','set_local','set_debug','get_panel_error_logs','clean_panel_error_logs','get_basic_auth_stat','set_basic_auth','get_cli_php_version','get_tmp_token','set_cli_php_version','DelOldSession', 'GetSessionCount', 'SetSessionConf', 'GetSessionConf','get_ipv6_listen','set_ipv6_status','GetApacheValue','SetApacheValue','GetNginxValue','SetNginxValue','get_token','set_token','set_admin_path','is_pro','get_php_config','get_config','SavePanelSSL','GetPanelSSL','GetPHPConf','SetPHPConf','GetPanelList','AddPanelInfo','SetPanelInfo','DelPanelInfo','ClickPanelInfo','SetPanelSSL','SetTemplates','Set502','setPassword','setUsername','setPanel','setPathInfo','setPHPMaxSize','getFpmConfig','setFpmConfig','setPHPMaxTime','syncDate','setPHPDisable','SetControl','ClosePanel','AutoUpdatePanel','SetPanelLock')
527+
defs = ('set_coll_open','get_qrcode_data','check_two_step','set_two_step_auth','get_key','get_php_session_path','set_php_session_path','get_cert_source','set_local','set_debug','get_panel_error_logs','clean_panel_error_logs','get_basic_auth_stat','set_basic_auth','get_cli_php_version','get_tmp_token','set_cli_php_version','DelOldSession', 'GetSessionCount', 'SetSessionConf', 'GetSessionConf','get_ipv6_listen','set_ipv6_status','GetApacheValue','SetApacheValue','GetNginxValue','SetNginxValue','get_token','set_token','set_admin_path','is_pro','get_php_config','get_config','SavePanelSSL','GetPanelSSL','GetPHPConf','SetPHPConf','GetPanelList','AddPanelInfo','SetPanelInfo','DelPanelInfo','ClickPanelInfo','SetPanelSSL','SetTemplates','Set502','setPassword','setUsername','setPanel','setPathInfo','setPHPMaxSize','getFpmConfig','setFpmConfig','setPHPMaxTime','syncDate','setPHPDisable','SetControl','ClosePanel','AutoUpdatePanel','SetPanelLock')
466528
return publicObject(config.config(),defs,None,pdata);
467529

468530
@app.route('/ajax',methods=method_all)
@@ -570,6 +632,7 @@ def panel_public():
570632
if not public.path_safe_check("%s/%s" % (get.name,get.fun)): return abort(404)
571633
if get.fun in ['scan_login', 'login_qrcode', 'set_login', 'is_scan_ok', 'blind','static']:
572634
if get.fun == 'static':
635+
if not 'filename' in get: return abort(404)
573636
if not public.path_safe_check("%s" % (get.filename)): return abort(404)
574637
s_file = '/www/server/panel/BTPanel/static/' + get.filename
575638
if s_file.find('..') != -1 or s_file.find('./') != -1: return abort(404)
@@ -598,6 +661,7 @@ def panel_public():
598661
comm.checkWebType()
599662
comm.GetOS()
600663
result = plu.a(get)
664+
session.clear()
601665
return public.getJson(result),json_header
602666

603667
@app.route('/favicon.ico',methods=method_get)
@@ -661,7 +725,9 @@ def panel_other(name=None,fun = None,stype=None):
661725
comReturn = comm.local()
662726
if comReturn:
663727
if not is_php:
664-
if not hasattr(plu,'_check'): return public.returnJson(False,'SPECIFY_PLUG_ERR'),json_header
728+
if not hasattr(plu,'_check'):
729+
session.clear()
730+
return public.returnJson(False,'SPECIFY_PLUG_ERR'),json_header
665731
checks = plu._check(args)
666732
r_type = type(checks)
667733
if r_type == Response: return checks
@@ -738,6 +804,7 @@ def panel_hook():
738804
if not os.path.exists('plugin/webhook'): return public.getJson(public.returnMsg(False,'INIT_WEBHOOK_ERR'));
739805
sys.path.append('plugin/webhook');
740806
import webhook_main
807+
session.clear()
741808
return public.getJson(webhook_main.webhook_main().RunHook(get));
742809

743810
@app.route('/safe',methods=method_all)
@@ -760,13 +827,16 @@ def panel_safe():
760827
if not hasattr(s,get.data['action']): return public.returnJson(False,'INIT_FUN_NOT_EXISTS');
761828
defs = ('GetServerInfo','add_ssh_limit','remove_ssh_limit','get_ssh_limit','get_login_log','get_panel_limit','add_panel_limit','remove_panel_limit','close_ssh_limit','close_panel_limit','get_system_info','get_service_info','get_ssh_errorlogin')
762829
if not get.data['action'] in defs: return 'False';
763-
return public.getJson(eval('s.' + get.data['action'] + '(get)'));
830+
result = public.getJson(eval('s.' + get.data['action'] + '(get)'));
831+
session.clear()
832+
return result
764833

765834

766835
@app.route('/install',methods=method_all)
767836
def install():
768837
if public.M('config').where("id=?",('1',)).getField('status') == 1:
769838
if os.path.exists('install.pl'): os.remove('install.pl');
839+
session.clear()
770840
return redirect('/login')
771841
ret_login = os.path.join('/',admin_path)
772842
if admin_path == '/' or admin_path == '/bt': ret_login = '/login'
@@ -863,122 +933,6 @@ def panel_cloud():
863933
if download_url.find('http') != 0:download_url = 'http://' + download_url
864934
return redirect(download_url)
865935

866-
ssh = None
867-
shell = None
868-
try:
869-
import paramiko
870-
ssh = paramiko.SSHClient()
871-
except:
872-
public.ExecShell('pip install paramiko==2.0.2 &')
873-
874-
@socketio.on('connect')
875-
def socket_connect(msg=None):
876-
if not check_login():
877-
emit('server_response',{'data':public.getMsg('111')})
878-
return False
879-
880-
@socketio.on('webssh')
881-
def webssh(msg):
882-
if not check_login(msg['x_http_token']):
883-
emit('server_response',{'data':public.getMsg('INIT_WEBSSH_LOGOUT')})
884-
return None
885-
886-
global shell,ssh
887-
ssh_success = True
888-
if type(msg['data']) == dict:
889-
if 'ssh_user' in msg['data']:
890-
connect_ssh(msg['data']['ssh_user'].strip(),msg['data']['ssh_passwd'].strip())
891-
if not shell: ssh_success = connect_ssh()
892-
if not shell:
893-
emit('server_response',{'data':public.getMsg('INIT_WEBSSH_CONN_ERR')})
894-
return;
895-
if shell.exit_status_ready(): ssh_success = connect_ssh()
896-
if not ssh_success:
897-
emit('server_response',{'data':public.getMsg('INIT_WEBSSH_CONN_ERR')})
898-
return;
899-
shell.send(msg['data'])
900-
time.sleep(0.005)
901-
recv = shell.recv(4096)
902-
emit('server_response',{'data':recv.decode("utf-8")})
903-
904-
def connect_ssh(user=None,passwd=None):
905-
global shell,ssh
906-
pkey = '/root/.ssh/id_rsa_bt'
907-
if not os.path.exists('/root/.ssh/authorized_keys') or not os.path.exists(pkey):
908-
create_rsa()
909-
try:
910-
if not user:
911-
key=paramiko.RSAKey.from_private_key_file(pkey)
912-
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
913-
try:
914-
if not user:
915-
ssh.connect('127.0.0.1', public.GetSSHPort(),pkey=key)
916-
else:
917-
ssh.connect('127.0.0.1', public.GetSSHPort(),username=user,password=passwd)
918-
except:
919-
if public.GetSSHStatus():
920-
try:
921-
if not user:
922-
ssh.connect('localhost', public.GetSSHPort(),pkey=key)
923-
else:
924-
ssh.connect('localhost', public.GetSSHPort(),username=user,password=passwd)
925-
except:
926-
create_rsa()
927-
return False;
928-
import firewalls
929-
fw = firewalls.firewalls()
930-
get = common.dict_obj()
931-
ssh_status = fw.GetSshInfo(get)['status']
932-
if not ssh_status:
933-
get.status = '0';
934-
fw.SetSshStatus(get)
935-
936-
if not user:
937-
ssh.connect('127.0.0.1', public.GetSSHPort(),pkey=key)
938-
else:
939-
ssh.connect('127.0.0.1', public.GetSSHPort(),username=user,password=passwd)
940-
941-
if not ssh_status:
942-
get.status = '1';
943-
fw.SetSshStatus(get);
944-
shell = ssh.invoke_shell(term='xterm', width=100, height=29)
945-
shell.setblocking(0)
946-
return True
947-
except:
948-
shell = None
949-
return False
950-
951-
def create_rsa():
952-
id_ras = '/root/.ssh/id_rsa_bt'
953-
a_keys = '/root/.ssh/authorized_keys'
954-
if not os.path.exists(a_keys) or not os.path.exists(id_ras):
955-
public.ExecShell("rm -f /root/.ssh/id_rsa_bt*")
956-
public.ExecShell('ssh-keygen -q -t rsa -P "" -f /root/.ssh/id_rsa_bt')
957-
public.ExecShell('cat /root/.ssh/id_rsa_bt.pub >> /root/.ssh/authorized_keys')
958-
else:
959-
id_ras_pub = '/root/.ssh/id_rsa_bt.pub'
960-
if os.path.exists(id_ras_pub):
961-
pub_body = public.readFile(id_ras_pub)
962-
keys_body = public.readFile(a_keys)
963-
if keys_body.find(pub_body) == -1:
964-
public.ExecShell('cat /root/.ssh/id_rsa_bt.pub >> /root/.ssh/authorized_keys')
965-
public.ExecShell('chmod 600 /root/.ssh/authorized_keys')
966-
967-
@socketio.on('connect_event')
968-
def connected_msg(msg):
969-
if not check_login():
970-
emit('server_response',{'data':public.getMsg('INIT_WEBSSH_LOGOUT')})
971-
return None
972-
global shell
973-
if not shell: connect_ssh()
974-
if shell:
975-
try:
976-
recv = shell.recv(8192)
977-
emit('server_response',{'data':recv.decode("utf-8")})
978-
except:
979-
pass
980-
981-
982936
def check_csrf():
983937
if app.config['DEBUG']: return True
984938
request_token = request.cookies.get('request_token')
@@ -1002,6 +956,10 @@ def publicObject(toObject,defs,action=None,get = None):
1002956
if get.path.find('./') != -1: return public.ReturnJson(False,public.GetMsg("UNSAFE_PATH")),json_header
1003957
if get.path.find('->') != -1:
1004958
get.path = get.path.split('->')[0].strip();
959+
if hasattr(get,'sfile'):
960+
get.sfile = get.sfile.replace('//','/').replace('\\','/');
961+
if hasattr(get,'dfile'):
962+
get.dfile = get.dfile.replace('//','/').replace('\\','/');
1005963

1006964
if hasattr(toObject,'site_path_check'):
1007965
if not toObject.site_path_check(get): return public.ReturnJson(False,'Excessive operation!'),json_header

0 commit comments

Comments
 (0)