Exemplo n.º 1
0
 def _set_login_session(self, userInfo):
     try:
         session['login'] = True
         session['username'] = userInfo['username']
         session['uid'] = userInfo['id']
         public.WriteLog('TYPE_LOGIN', 'LOGIN_SUCCESS',
                         (userInfo['username'], public.GetClientIp()))
         self.limit_address('-')
         cache.delete('panelNum')
         cache.delete('dologin')
         sess_input_path = 'data/session_last.pl'
         public.writeFile(sess_input_path, str(int(time.time())))
         self.set_request_token()
         self.login_token()
         return public.returnJson(True, 'LOGIN_SUCCESS'), json_header
     except Exception as ex:
         stringEx = str(ex)
         if stringEx.find('unsupported') != -1 or stringEx.find('-1') != -1:
             os.system("rm -f /tmp/sess_*")
             os.system("rm -f /www/wwwlogs/*log")
             public.ServiceReload()
             return public.returnJson(False, 'USER_INODE_ERR'), json_header
         public.WriteLog('TYPE_LOGIN', 'LOGIN_ERR_PASS',
                         ('****', '******', public.GetClientIp()))
         num = self.limit_address('+')
         return public.returnJson(False, 'LOGIN_USER_ERR',
                                  (str(num), )), json_header
Exemplo n.º 2
0
 def request_temp(self, get):
     try:
         if not hasattr(get, 'tmp_token'):
             return public.getMsg('INIT_ARGS_ERR')
         if len(get.tmp_token) != 48: return public.getMsg('INIT_ARGS_ERR')
         if not re.match(r"^\w+$", get.tmp_token):
             return public.getMsg('INIT_ARGS_ERR')
         skey = public.GetClientIp() + '_temp_login'
         if not public.get_error_num(skey, 10):
             return public.getMsg('AUTH_FAILED')
         s_time = int(time.time())
         data = public.M('temp_login').where(
             'state=? and expire>?',
             (0, s_time)).field('id,token,salt,expire').find()
         if not data:
             public.set_error_num(skey)
             return public.getMsg('VERIFICATION_FAILED')
         if not isinstance(data, dict):
             public.set_error_num(skey)
             return public.getMsg('VERIFICATION_FAILED')
         r_token = public.md5(get.tmp_token + data['salt'])
         if r_token != data['token']:
             public.set_error_num(skey)
             return public.getMsg('VERIFICATION_FAILED')
         public.set_error_num(skey, True)
         userInfo = public.M('users').where(
             "id=?", (1, )).field('id,username').find()
         session['login'] = True
         session['username'] = public.getMsg('TEMPORARY_ID', (data['id'], ))
         session['tmp_login'] = True
         session['tmp_login_id'] = str(data['id'])
         session['tmp_login_expire'] = time.time() + 3600
         session['uid'] = data['id']
         sess_path = 'data/session'
         if not os.path.exists(sess_path):
             os.makedirs(sess_path, 384)
         public.writeFile(sess_path + '/' + str(data['id']), '')
         login_addr = public.GetClientIp() + ":" + str(
             request.environ.get('REMOTE_PORT'))
         public.WriteLog('TYPE_LOGIN', 'LOGIN_SUCCESS',
                         (userInfo['username'], login_addr))
         public.M('temp_login').where('id=?', (data['id'], )).update({
             "login_time":
             s_time,
             'state':
             1,
             'login_addr':
             login_addr
         })
         self.limit_address('-')
         cache.delete('panelNum')
         cache.delete('dologin')
         sess_input_path = 'data/session_last.pl'
         public.writeFile(sess_input_path, str(int(time.time())))
         self.set_request_token()
         self.login_token()
         self.set_cdn_host(get)
         return redirect('/')
     except:
         return public.getMsg('LOGIN_FAIL')
Exemplo n.º 3
0
    def request_post(self,post):
        if not hasattr(post, 'username') or not hasattr(post, 'password'):
            return public.returnJson(False,'LOGIN_USER_EMPTY'),json_header
        
        self.error_num(False)
        if self.limit_address('?') < 1: return public.returnJson(False,'LOGIN_ERR_LIMIT'),json_header
        
        post.username = post.username.strip();
        password = public.md5(post.password.strip());
        sql = db.Sql();
        userInfo = sql.table('users').where("id=?",(1,)).field('id,username,password').find()
        m_code = cache.get('codeStr')
        if 'code' in session:
            if session['code'] and not 'is_verify_password' in session:
                if not hasattr(post, 'code'): return public.returnJson(False,'验证码不能为空!'),json_header
                if not public.checkCode(post.code):
                    public.WriteLog('TYPE_LOGIN','LOGIN_ERR_CODE',('****','****',public.GetClientIp()));
                    return public.returnJson(False,'CODE_ERR'),json_header
        try:
            s_pass = public.md5(public.md5(userInfo['password'] + '_bt.cn'))
            if userInfo['username'] != post.username or s_pass != password:
                public.WriteLog('TYPE_LOGIN','LOGIN_ERR_PASS',('****','******',public.GetClientIp()));
                num = self.limit_address('+');
                return public.returnJson(False,'LOGIN_USER_ERR',(str(num),)),json_header
            _key_file = "/www/server/panel/data/two_step_auth.txt"
            if hasattr(post,'vcode'):
                if self.limit_address('?',v="vcode") < 1: return public.returnJson(False,'您多次验证失败,禁止10分钟'),json_header
                import pyotp
                secret_key = public.readFile(_key_file)
                if not secret_key:
                    return public.returnJson(False, "没有找到key,请尝试在命令行关闭谷歌验证后在开启"),json_header
                t = pyotp.TOTP(secret_key)
                result = t.verify(post.vcode)
                if not result:
                    if public.sync_date(): result = t.verify(post.vcode)
                    if not result:
                        num = self.limit_address('++',v="vcode")
                        return public.returnJson(False, '验证失败,您还可以尝试[{}]次!'.format(num)), json_header
                now = int(time.time())
                public.writeFile("/www/server/panel/data/dont_vcode_ip.txt",json.dumps({"client_ip":public.GetClientIp(),"add_time":now}))
                self.limit_address('--',v="vcode")
                return self._set_login_session(userInfo)

            acc_client_ip = self.check_two_step_auth()

            if not os.path.exists(_key_file) or acc_client_ip:
                return self._set_login_session(userInfo)
            self.limit_address('-')
            session['is_verify_password'] = True
            return "1"
        except Exception as ex:
            stringEx = str(ex)
            if stringEx.find('unsupported') != -1 or stringEx.find('-1') != -1: 
                os.system("rm -f /tmp/sess_*")
                os.system("rm -f /www/wwwlogs/*log")
                public.ServiceReload()
                return public.returnJson(False,'USER_INODE_ERR'),json_header
            public.WriteLog('TYPE_LOGIN','LOGIN_ERR_PASS',('****','******',public.GetClientIp()));
            num = self.limit_address('+');
            return public.returnJson(False,'LOGIN_USER_ERR',(str(num),)),json_header
Exemplo n.º 4
0
    def set_login(self, get):
        session_id = public.get_session_id()
        if cache.get(session_id) == 'True':
            return self.check_app_login(get)

        if os.path.exists(self.app_path + "login.pl"):
            data = public.readFile(self.app_path + 'login.pl')
            public.ExecShell('rm ' + self.app_path + "login.pl")
            secret_key, init_time = data.split(':')
            if time.time() - float(init_time) < 60 and get[
                    'secret_key'] == secret_key:
                sql = db.Sql()
                userInfo = sql.table('users').where(
                    "id=?", (1, )).field('id,username,password').find()
                session['login'] = True
                session['username'] = userInfo['username']
                cache.delete('panelNum')
                cache.delete('dologin')
                public.WriteLog(
                    'TYPE_LOGIN', 'LOGIN_SUCCESS',
                    ('WeChat scan code login', public.GetClientIp() + ":" +
                     str(request.environ.get('REMOTE_PORT'))))
                login_type = 'data/app_login.pl'
                self.set_request_token()
                import config
                config.config().reload_session()
                public.writeFile(login_type, 'True')
                public.login_send_body("Wechat program", userInfo['username'],
                                       public.GetClientIp(),
                                       str(request.environ.get('REMOTE_PORT')))
                return public.returnMsg(True, 'login successful')
        return public.returnMsg(False, 'Login failed')
Exemplo n.º 5
0
 def _set_login_session(self, userInfo):
     try:
         session['login'] = True
         session['username'] = userInfo['username']
         session['uid'] = userInfo['id']
         session['login_user_agent'] = public.md5(
             request.headers.get('User-Agent', ''))
         public.WriteLog('TYPE_LOGIN', 'LOGIN_SUCCESS',
                         (userInfo['username'], public.GetClientIp() + ":" +
                          str(request.environ.get('REMOTE_PORT'))))
         self.limit_address('-')
         cache.delete('panelNum')
         cache.delete('dologin')
         session['session_timeout'] = time.time(
         ) + public.get_session_timeout()
         self.set_request_token()
         self.login_token()
         login_type = 'data/app_login.pl'
         if os.path.exists(login_type):
             os.remove(login_type)
         return public.returnJson(True, 'LOGIN_SUCCESS'), json_header
     except Exception as ex:
         stringEx = str(ex)
         if stringEx.find('unsupported') != -1 or stringEx.find('-1') != -1:
             public.ExecShell("rm -f /tmp/sess_*")
             public.ExecShell("rm -f /www/wwwlogs/*log")
             public.ServiceReload()
             return public.returnJson(False, 'USER_INODE_ERR'), json_header
         public.WriteLog('TYPE_LOGIN', 'LOGIN_ERR_PASS',
                         ('****', '******', public.GetClientIp()))
         num = self.limit_address('+')
         return public.returnJson(False, 'LOGIN_USER_ERR',
                                  (str(num), )), json_header
Exemplo n.º 6
0
 def check_app_login(self, get):
     #判断是否存在绑定
     btapp_info = json.loads(
         public.readFile('/www/server/panel/config/api.json'))
     if not btapp_info: return public.returnMsg(False, 'Unbound')
     if not btapp_info['open']:
         return public.returnMsg(False, 'API is not turned on')
     if not 'apps' in btapp_info:
         return public.returnMsg(False, 'Unbound phone')
     if not btapp_info['apps']:
         return public.returnMsg(False, 'Unbound phone')
     try:
         session_id = public.get_session_id()
         if not os.path.exists(self.app_path + 'app_login_check.pl'):
             return public.returnMsg(False,
                                     'Waiting for APP scan code login 1')
         data = public.readFile(self.app_path + 'app_login_check.pl')
         public.ExecShell('rm ' + self.app_path + "app_login_check.pl")
         secret_key, init_time = data.split(':')
         if len(session_id) != 64:
             return public.returnMsg(False,
                                     'Waiting for APP scan code login 2')
         if len(secret_key) != 64:
             return public.returnMsg(False,
                                     'Waiting for APP scan code login 2')
         if time.time() - float(init_time) > 60:
             return public.returnMsg(False,
                                     'Waiting for APP scan code login')
         if session_id != secret_key:
             return public.returnMsg(False,
                                     'Waiting for APP scan code login')
         cache.delete(session_id)
         userInfo = public.M('users').where(
             "id=?", (1, )).field('id,username').find()
         session['login'] = True
         session['username'] = userInfo['username']
         session['tmp_login'] = True
         public.WriteLog(
             'TYPE_LOGIN',
             'APP scan code login, account: {}, login IP: {}'.format(
                 userInfo['username'],
                 public.GetClientIp() + ":" +
                 str(request.environ.get('REMOTE_PORT'))))
         cache.delete('panelNum')
         cache.delete('dologin')
         session['session_timeout'] = time.time(
         ) + public.get_session_timeout()
         login_type = 'data/app_login.pl'
         self.set_request_token()
         import config
         config.config().reload_session()
         public.writeFile(login_type, 'True')
         public.login_send_body("aaPanel Mobile", userInfo['username'],
                                public.GetClientIp(),
                                str(request.environ.get('REMOTE_PORT')))
         return public.returnMsg(True, 'login successful!')
     except:
         return public.returnMsg(False, 'Login failed 2')
Exemplo n.º 7
0
    def request_get(self, get):
        #if os.path.exists('/www/server/panel/install.pl'): raise redirect('/install');
        if not 'title' in session: session['title'] = public.getMsg('NAME')
        domain = public.readFile('data/domain.conf')

        if domain:
            if (public.GetHost().lower() != domain.strip().lower()):

                errorStr = '''
<meta charset="utf-8">
<title>%s</title>
</head><body>
<h1>%s</h1>
    <p>%s</p>
    <p>%s</p>
    <p>%s</p>
<hr>
<address>%s 6.x <a href="http://www.bt.cn/bbs" target="_blank">%s</a></address>
</body></html>
    ''' % (public.getMsg('PAGE_ERR_TITLE'),
                public.getMsg('PAGE_ERR_DOMAIN_H1'),
                public.getMsg('PAGE_ERR_DOMAIN_P1'),
                public.getMsg('PAGE_ERR_DOMAIN_P2'),
                public.getMsg('PAGE_ERR_DOMAIN_P3'), public.getMsg('NAME'),
                public.getMsg('PAGE_ERR_HELP'))
                return errorStr
        if os.path.exists('data/limitip.conf'):
            iplist = public.readFile('data/limitip.conf')
            if iplist:
                iplist = iplist.strip()
                if not public.GetClientIp() in iplist.split(','):
                    errorStr = '''
<meta charset="utf-8">
<title>%s</title>
</head><body>
<h1>%s</h1>
    <p>%s</p>
    <p>%s</p>
    <p>%s</p>
<hr>
<address>%s 6.x <a href="http://www.bt.cn/bbs" target="_blank">%s</a></address>
</body></html>
''' % (public.getMsg('PAGE_ERR_TITLE'), public.getMsg('PAGE_ERR_IP_H1'),
                    public.getMsg('PAGE_ERR_IP_P1', (public.GetClientIp(), )),
                    public.getMsg('PAGE_ERR_IP_P2'), public.getMsg('PAGE_ERR_IP_P3'),
                    public.getMsg('NAME'), public.getMsg('PAGE_ERR_HELP'))
                    return errorStr

        sql = db.Sql()

        if 'login' in session:
            if session['login'] == True:
                return redirect('/')

        if not 'code' in session:
            session['code'] = False
        self.error_num(False)
Exemplo n.º 8
0
    def request_post(self, post):
        if not (hasattr(post, 'username') or hasattr(post, 'password')
                or hasattr(post, 'code')):
            return public.returnJson(False, 'LOGIN_USER_EMPTY'), json_header

        self.error_num(False)
        if self.limit_address('?') < 1:
            return public.returnJson(False, 'LOGIN_ERR_LIMIT'), json_header

        post.username = post.username.strip()
        password = public.md5(post.password.strip())
        sql = db.Sql()
        userInfo = sql.table('users').where(
            "id=?", (1, )).field('id,username,password').find()
        m_code = cache.get('codeStr')
        if 'code' in session:
            if session['code']:
                if not public.checkCode(post.code):
                    public.WriteLog('TYPE_LOGIN', 'LOGIN_ERR_CODE',
                                    ('****', '****', public.GetClientIp()))
                    return public.returnJson(False, 'CODE_ERR'), json_header
        try:
            s_pass = public.md5(public.md5(userInfo['password'] + '_bt.cn'))
            if userInfo['username'] != post.username or s_pass != password:
                public.WriteLog('TYPE_LOGIN', 'LOGIN_ERR_PASS',
                                ('****', '******', public.GetClientIp()))
                num = self.limit_address('+')
                return public.returnJson(False, 'LOGIN_USER_ERR',
                                         (str(num), )), json_header

            session['login'] = True
            session['username'] = userInfo['username']
            public.WriteLog('TYPE_LOGIN', 'LOGIN_SUCCESS',
                            (userInfo['username'], public.GetClientIp()))
            self.limit_address('-')
            cache.delete('panelNum')
            cache.delete('dologin')
            sess_input_path = 'data/session_last.pl'
            public.writeFile(sess_input_path, str(int(time.time())))
            self.set_request_token()
            self.login_token()
            return public.returnJson(True, 'LOGIN_SUCCESS'), json_header
        except Exception as ex:
            stringEx = str(ex)
            if stringEx.find('unsupported') != -1 or stringEx.find('-1') != -1:
                os.system("rm -f /tmp/sess_*")
                os.system("rm -f /www/wwwlogs/*log")
                public.ServiceReload()
                return public.returnJson(False, 'USER_INODE_ERR'), json_header
            public.WriteLog('TYPE_LOGIN', 'LOGIN_ERR_PASS',
                            ('****', '******', public.GetClientIp()))
            num = self.limit_address('+')
            return public.returnJson(False, 'LOGIN_USER_ERR',
                                     (str(num), )), json_header
Exemplo n.º 9
0
    def request_get(self, get):
        #if os.path.exists('/www/server/panel/install.pl'): raise redirect('/install');
        if not 'title' in session: session['title'] = public.getMsg('NAME')
        domain = public.readFile('data/domain.conf')

        if domain:
            if (public.GetHost().lower() != domain.strip().lower()):
                errorStr = public.ReadFile('./BTPanel/templates/' +
                                           public.GetConfigValue('template') +
                                           '/error2.html')
                try:
                    errorStr = errorStr.format(
                        public.getMsg('PAGE_ERR_TITLE'),
                        public.getMsg('PAGE_ERR_DOMAIN_H1'),
                        public.getMsg('PAGE_ERR_DOMAIN_P1'),
                        public.getMsg('PAGE_ERR_DOMAIN_P2'),
                        public.getMsg('PAGE_ERR_DOMAIN_P3'),
                        public.getMsg('NAME'), public.getMsg('PAGE_ERR_HELP'))
                except IndexError:
                    pass
                return errorStr
        if os.path.exists('data/limitip.conf'):
            iplist = public.readFile('data/limitip.conf')
            if iplist:
                iplist = iplist.strip()
                if not public.GetClientIp() in iplist.split(','):
                    errorStr = public.ReadFile(
                        './BTPanel/templates/' +
                        public.GetConfigValue('template') + '/error2.html')
                    try:
                        errorStr = errorStr.format(
                            public.getMsg('PAGE_ERR_TITLE'),
                            public.getMsg('PAGE_ERR_IP_H1'),
                            public.getMsg('PAGE_ERR_IP_P1',
                                          (public.GetClientIp(), )),
                            public.getMsg('PAGE_ERR_IP_P2'),
                            public.getMsg('PAGE_ERR_IP_P3'),
                            public.getMsg('NAME'),
                            public.getMsg('PAGE_ERR_HELP'))
                    except IndexError:
                        pass
                    return errorStr

        sql = db.Sql()

        if 'login' in session:
            if session['login'] == True:
                return redirect('/')

        if not 'code' in session:
            session['code'] = False
        self.error_num(False)
Exemplo n.º 10
0
    def request_tmp(self,get):
        try:
            if not hasattr(get,'tmp_token'): return public.returnJson(False,'错误的参数!'),json_header
            if len(get.tmp_token) != 64: return public.returnJson(False,'错误的参数!'),json_header
            if not re.match(r"^\w+$",get.tmp_token):return public.returnJson(False,'错误的参数!'),json_header

            save_path = '/www/server/panel/config/api.json'
            data = json.loads(public.ReadFile(save_path))
            if not 'tmp_token' in data or not 'tmp_time' in data: return public.returnJson(False,'验证失败!'),json_header
            if (time.time() - data['tmp_time']) > 120: return public.returnJson(False,'过期的Token'),json_header
            if get.tmp_token != data['tmp_token']: return public.returnJson(False,'错误的Token'),json_header
            userInfo = public.M('users').where("id=?",(1,)).field('id,username').find()
            session['login'] = True
            session['username'] = userInfo['username']
            session['tmp_login'] = True
            public.WriteLog('TYPE_LOGIN','LOGIN_SUCCESS',(userInfo['username'],public.GetClientIp()+ ":" + str(request.environ.get('REMOTE_PORT'))))
            self.limit_address('-')
            cache.delete('panelNum')
            cache.delete('dologin')
            sess_input_path = 'data/session_last.pl'
            public.writeFile(sess_input_path,str(int(time.time())))
            del(data['tmp_token'])
            del(data['tmp_time'])
            public.writeFile(save_path,json.dumps(data))
            self.set_request_token()
            self.login_token()
            self.set_cdn_host(get)
            return redirect('/')
        except:
            return public.returnJson(False,'登录失败,' + public.get_error_info()),json_header
Exemplo n.º 11
0
 def _check(self, get):
     token_data = public.readFile(self.app_path + 'token.pl')
     if not token_data:
         token_data = public.readFile(self.app_path_p + 'token.pl')
     if hasattr(SelfModule, get['fun']):
         return False
     elif get['fun'] in ['set_login', 'is_scan_ok', 'login_qrcode']:
         return True
     elif get['fun'] == 'blind':
         if not token_data:
             return public.returnMsg(False, 'QRCORE_EXPIRE', ("1", ))
         token_data = token_data.replace('\n', '')
         password, expiration_time = token_data.split(':')
         # return True
         if time.time() - int(expiration_time) > 8 * 60:
             return public.returnMsg(False, 'QRCORE_EXPIRE', ("2", ))
         elif get['panel_token'] != password:
             return public.returnMsg(False, 'SK_NOT_INCORRECT')
         return True
     else:
         # 是否在白名单ip    sgin 是否正确
         if hasattr(get, 'uid') and hasattr(get, 'sgin') and hasattr(
                 get, 'fun') and get['uid'] in self.user_info.keys():
             encryption_str = self.user_info[
                 get['uid']]['token'] + get['fun'] + get['uid']
             if sys.version_info[0] == 3:
                 if type(encryption_str) == str:
                     encryption_str = encryption_str.encode()
         if get['sgin'] == public.md5(
                 binascii.hexlify(base64.b64encode(encryption_str))):
             if public.GetClientIp() in ['47.52.194.186']:
                 return True
         return public.returnMsg(False, 'UNAUTHORIZED')
Exemplo n.º 12
0
 def request_tmp(self,get):
     try:
         if not hasattr(get,'tmp_token'): return public.returnJson(False,'INIT_ARGS_ERR'),json_header
         save_path = '/www/server/panel/config/api.json'
         data = json.loads(public.ReadFile(save_path))
         if not 'tmp_token' in data or not 'tmp_time' in data: return public.returnJson(False,'VERIFICATION_FAILED'),json_header
         if (time.time() - data['tmp_time']) > 120: return public.returnJson(False,'EXPIRED_TOKEN'),json_header
         if get.tmp_token != data['tmp_token']: return public.returnJson(False,'INIT_TOKEN_ERR'),json_header
         userInfo = public.M('users').where("id=?",(1,)).field('id,username').find()
         session['login'] = True
         session['username'] = userInfo['username']
         session['tmp_login'] = True
         public.WriteLog('TYPE_LOGIN','LOGIN_SUCCESS',(userInfo['username'],public.GetClientIp()))
         self.limit_address('-')
         cache.delete('panelNum')
         cache.delete('dologin')
         sess_input_path = 'data/session_last.pl'
         public.writeFile(sess_input_path,str(int(time.time())))
         del(data['tmp_token'])
         del(data['tmp_time'])
         public.writeFile(save_path,json.dumps(data))
         self.set_request_token()
         self.login_token()
         self.set_cdn_host(get)
         return redirect('/')
     except:
         return public.returnJson(False,'Login failed,' + public.get_error_info()),json_header
Exemplo n.º 13
0
def panel_public():
    get = get_input();
    get.client_ip = public.GetClientIp();

    if get.fun in ['scan_login','login_qrcode','set_login','is_scan_ok','blind']:
        #检查是否验证过安全入口
        if get.fun in ['login_qrcode','is_scan_ok']:
            global admin_check_auth,admin_path,route_path,admin_path_file
            if admin_path != '/bt' and os.path.exists(admin_path_file) and  not 'admin_auth' in session: return 'False'
        import wxapp
        pluwx = wxapp.wxapp()
        checks = pluwx._check(get)
        if type(checks) != bool or not checks: return public.getJson(checks),json_header
        data = public.getJson(eval('pluwx.'+get.fun+'(get)'))
        return data,json_header
    
    import panelPlugin
    plu = panelPlugin.panelPlugin()
    get.s = '_check';
        
    checks = plu.a(get)
    if type(checks) != bool or not checks: return public.getJson(checks),json_header
    get.s = get.fun
    comm.setSession()
    comm.init()
    comm.checkWebType()
    comm.GetOS()
    result = plu.a(get)
    return public.getJson(result),json_header
Exemplo n.º 14
0
 def checkLimitIp(self):
     if os.path.exists('data/limitip.conf'):
         iplist = public.ReadFile('data/limitip.conf')
         if iplist:
             iplist = iplist.strip()
             if not public.GetClientIp() in iplist.split(','):
                 return redirect('/login')
Exemplo n.º 15
0
def check_run():
    '''
        @name 开始检测
        @author hwliang<2020-08-03>
        @return tuple (status<bool>,msg<string>)

        @example   
            status, msg = check_run()
            if status:
                print('OK')
            else:
                print('Warning: {}'.format(msg))
        
    '''
    mycnf_file = '/etc/my.cnf'
    if not os.path.exists(mycnf_file):
        return True,'MySQL is not installed'
    mycnf = public.readFile(mycnf_file)
    port_tmp = re.findall(r"port\s*=\s*(\d+)",mycnf)
    if not port_tmp:
        return True,'MySQL is not installed'
    if not public.ExecShell("lsof -i :{}".format(port_tmp[0]))[0]:
        return True,'MySQL is not installed'
    result = public.check_port_stat(int(port_tmp[0]),public.GetClientIp())
    if result == 0:
        return True,'Risk-free'

    return False,'The current MySQL port: {}, which can be accessed by any server, which may cause MySQL to be cracked by brute force, posing security risks'.format(port_tmp[0])
Exemplo n.º 16
0
 def check_app_login(self, get):
     session_id = public.get_session_id()
     if cache.get(session_id) != 'True':
         return public.returnMsg(
             False, 'Wait for the app to scan the code and log in')
     cache.delete(session_id)
     userInfo = public.M('users').where("id=?",
                                        (1, )).field('id,username').find()
     session['login'] = True
     session['username'] = userInfo['username']
     session['tmp_login'] = True
     public.WriteLog(
         'TYPE_LOGIN',
         'APP scan code login, account: {}, login IP: {}'.format(
             userInfo['username'],
             public.GetClientIp() + ":" +
             str(request.environ.get('REMOTE_PORT'))))
     cache.delete('panelNum')
     cache.delete('dologin')
     sess_input_path = 'data/session_last.pl'
     public.writeFile(sess_input_path, str(int(time.time())))
     login_type = 'data/app_login.pl'
     self.set_request_token()
     import config
     config.config().reload_session()
     public.writeFile(login_type, 'True')
     return public.returnMsg(True, 'login successful!')
Exemplo n.º 17
0
def panel_public():
    get = get_input()
    get.client_ip = public.GetClientIp()
    if get.fun in [
            'scan_login', 'login_qrcode', 'set_login', 'is_scan_ok', 'blind'
    ]:
        import wxapp
        pluwx = wxapp.wxapp()
        checks = pluwx._check(get)
        if type(checks) != bool or not checks:
            return public.getJson(checks), json_header
        data = public.getJson(eval('pluwx.' + get.fun + '(get)'))
        return data, json_header

    import panelPlugin
    plu = panelPlugin.panelPlugin()
    get.s = '_check'

    checks = plu.a(get)
    if type(checks) != bool or not checks:
        return public.getJson(checks), json_header
    get.s = get.fun
    comm.setSession()
    comm.init()
    comm.checkWebType()
    comm.GetOS()
    result = plu.a(get)
    return public.getJson(result), json_header
Exemplo n.º 18
0
    def limit_address(self, type):
        import time
        clientIp = public.GetClientIp()
        numKey = 'limitIpNum_' + clientIp
        limit = 6
        outTime = 600
        try:
            #初始化
            num1 = cache.get(numKey)
            if not num1:
                cache.set(numKey, 1, outTime)
                num1 = 1

            #计数
            if type == '+':
                cache.inc(numKey, 1)
                self.error_num()
                session['code'] = True
                return limit - (num1 + 1)

            #清空
            if type == '-':
                cache.delete(numKey)
                session['code'] = False
                return 1
            return limit - num1
        except:
            return limit
Exemplo n.º 19
0
    def get_sk(self):
        save_path = '/www/server/panel/config/api.json'
        if not os.path.exists(save_path):
            return redirect('/login')
        try:
            api_config = json.loads(public.ReadFile(save_path))
        except:
            os.remove(save_path)
            return redirect('/login')

        if not api_config['open']:
            return redirect('/login')
        from BTPanel import get_input
        get = get_input()
        client_ip = public.GetClientIp()
        if not 'client_bind_token' in get:
            if not 'request_token' in get or not 'request_time' in get:
                return redirect('/login')

            num_key = client_ip + '_api'
            if not public.get_error_num(num_key,20):
                return public.returnJson(False,'AUTH_FAILED1')


            if not client_ip in api_config['limit_addr']:
                public.set_error_num(num_key)
                return public.returnJson(False,'%s[' % public.GetMsg("AUTH_FAILED1")+client_ip+']')
        else:
            num_key = client_ip + '_app'
            if not public.get_error_num(num_key,20):
                return public.returnJson(False,'AUTH_FAILED1')
            a_file = '/dev/shm/' + get.client_bind_token
            if not os.path.exists(a_file):
                import panelApi
                if not panelApi.panelApi().get_app_find(get.client_bind_token):
                    public.set_error_num(num_key)
                    return public.returnJson(False,'UNBOUND_DEVICE')
                public.writeFile(a_file,'')

            if not 'key' in api_config:
                public.set_error_num(num_key)
                return public.returnJson(False, 'KEY_ERR')
            if not 'form_data' in get:
                public.set_error_num(num_key)
                return public.returnJson(False, 'FORM_DATA_ERR')

            g.form_data = json.loads(public.aes_decrypt(get.form_data, api_config['key']))

            get = get_input()
            if not 'request_token' in get or not 'request_time' in get:
                return redirect('/login')
            g.is_aes = True
            g.aes_key = api_config['key']
        request_token = public.md5(get.request_time + api_config['token'])
        if get.request_token == request_token:
            public.set_error_num(num_key,True)
            return False
        public.set_error_num(num_key)
        return public.returnJson(False,'SECRET_KEY_CHECK_FALSE')
Exemplo n.º 20
0
 def __write_args(self, args):
     if os.path.exists(self.__args_tmp): os.remove(self.__args_tmp)
     self.__clean_args_file()
     data = {}
     data['GET'] = request.args.to_dict()
     data['POST'] = request.form.to_dict()
     data['POST']['client_ip'] = public.GetClientIp()
     data = json.dumps(data)
     public.writeFile(self.__args_tmp, data)
Exemplo n.º 21
0
 def check_two_step_auth(self):
     dont_vcode_ip_info = public.readFile("/www/server/panel/data/dont_vcode_ip.txt")
     acc_client_ip = False
     if dont_vcode_ip_info:
         dont_vcode_ip_info = json.loads(dont_vcode_ip_info)
         ip = dont_vcode_ip_info["client_ip"] == public.GetClientIp()
         now = int(time.time())
         v_time = now - int(dont_vcode_ip_info["add_time"])
         if ip and v_time < 86400:
             acc_client_ip = True
     return acc_client_ip
Exemplo n.º 22
0
def panel_yield():
    get = get_input()
    import panelPlugin
    plu = panelPlugin.panelPlugin()
    get.s = '_check';
    get.client_ip = public.GetClientIp()
    checks = plu.a(get)
    if type(checks) != bool or not checks: return
    get.s = get.fun
    filename = plu.a(get);
    mimetype = 'application/octet-stream'
    return send_file(filename,mimetype=mimetype, as_attachment=True,attachment_filename=os.path.basename(filename))
Exemplo n.º 23
0
 def get_sk(self,):
     save_path = '/www/server/panel/config/api.json'
     if not os.path.exists(save_path): return redirect('/login')
     api_config = json.loads(public.ReadFile(save_path))
     if not api_config['open']: return redirect('/login')
     from BTPanel import get_input
     get = get_input()
     if not 'request_token' in get or not 'request_time' in get: return redirect('/login')
     client_ip = public.GetClientIp()
     if not client_ip in api_config['limit_addr']: return public.returnJson(False,'IP校验失败,您的访问IP为['+client_ip+']')
     request_token = public.md5(get.request_time + api_config['token'])
     if get.request_token == request_token: return False
     return public.returnJson(False,'密钥校验失败')
Exemplo n.º 24
0
 def get_sk(self, ):
     save_path = '/www/server/panel/config/api.json'
     if not os.path.exists(save_path): return False
     api_config = json.loads(public.ReadFile(save_path))
     if not api_config['open']: return False
     from BTPanel import get_input
     get = get_input()
     if not 'request_token' in get: return False
     if not 'request_time' in get: return False
     client_ip = public.GetClientIp()
     if not client_ip in api_config['limit_addr']: return False
     request_token = public.md5(get.request_time + api_config['token'])
     if get.request_token == request_token:
         return True
     return False
Exemplo n.º 25
0
    def get_sk(self):
        save_path = '/www/server/panel/config/api.json'
        if not os.path.exists(save_path):
            return redirect('/login')
        try:
            api_config = json.loads(public.ReadFile(save_path))
        except:
            os.remove(save_path)
            return redirect('/login')

        if not api_config['open']:
            return redirect('/login')
        from BTPanel import get_input
        get = get_input()

        if not 'client_bind_token' in get:
            if not 'request_token' in get or not 'request_time' in get:
                return redirect('/login')
            client_ip = public.GetClientIp()
            if not client_ip in api_config['limit_addr']:
                return public.returnJson(False,
                                         'IP校验失败,您的访问IP为[' + client_ip + ']')
        else:
            a_file = '/dev/shm/' + get.client_bind_token
            if not os.path.exists(a_file):
                import panelApi
                if not panelApi.panelApi().get_app_find(get.client_bind_token):
                    return public.returnMsg(False, '未绑定的设备')
                public.writeFile(a_file, '')

            if not 'key' in api_config:
                return public.returnJson(False, '密钥校验失败')
            if not 'form_data' in get:
                return public.returnJson(False, '没有找到form_data数据')

            g.form_data = json.loads(
                public.aes_decrypt(get.form_data, api_config['key']))

            get = get_input()
            if not 'request_token' in get or not 'request_time' in get:
                return redirect('/login')
            g.is_aes = True
            g.aes_key = api_config['key']

        request_token = public.md5(get.request_time + api_config['token'])
        if get.request_token == request_token:
            return False
        return public.returnJson(False, '密钥校验失败')
Exemplo n.º 26
0
    def get_sk(self):
        save_path = '/www/server/panel/config/api.json'
        if not os.path.exists(save_path):
            return redirect('/login')
        try:
            api_config = json.loads(public.ReadFile(save_path))
        except:
            os.remove(save_path)
            return redirect('/login')

        if not api_config['open']:
            return redirect('/login')
        from BTPanel import get_input
        get = get_input()

        if not 'client_bind_token' in get:
            if not 'request_token' in get or not 'request_time' in get:
                return redirect('/login')
            client_ip = public.GetClientIp()
            if not client_ip in api_config['limit_addr']:
                return public.returnJson(
                    False,
                    '%s[' % public.GetMsg("CHECK_IP_FALSE") + client_ip + ']')
        else:
            a_file = '/dev/shm/' + get.client_bind_token
            if not os.path.exists(a_file):
                import panelApi
                if not panelApi.panelApi().get_app_find(get.client_bind_token):
                    return public.returnMsg(False, 'Unbound device')
                public.writeFile(a_file, '')

            if not 'key' in api_config:
                return public.returnJson(False, 'Key verification failed')
            if not 'form_data' in get:
                return public.returnJson(False, 'No form_data data found')

            g.form_data = json.loads(
                public.aes_decrypt(get.form_data, api_config['key']))

            get = get_input()
            if not 'request_token' in get or not 'request_time' in get:
                return redirect('/login')
            g.is_aes = True
            g.aes_key = api_config['key']
        request_token = public.md5(get.request_time + api_config['token'])
        if get.request_token == request_token:
            return False
        return public.returnJson(False, 'SECRET_KEY_CHECK_FALSE')
Exemplo n.º 27
0
 def set_login(self, get):
     if os.path.exists(self.app_path+"login.pl"):
         data = public.readFile(self.app_path+'login.pl')
         public.ExecShell('rm ' + self.app_path+"login.pl")
         secret_key, init_time = data.split(':')
         if time.time() - float(init_time) < 60 and get['secret_key'] == secret_key:
             sql = db.Sql()
             userInfo = sql.table('users').where(
                 "id=?", (1,)).field('id,username,password').find()
             session['login'] = True
             session['username'] = userInfo['username']
             cache.delete('panelNum')
             cache.delete('dologin')
             public.WriteLog('TYPE_LOGIN', 'LOGIN_SUCCESS1',
                             (public.GetMsg("WECHAT_SCAN_QRCORE"), public.GetClientIp()))
             return public.returnMsg(True, 'LOGIN_SUCCESS')
     return public.returnMsg(False, 'LOGIN_FAIL')
Exemplo n.º 28
0
 def __write_args(self,args):
     from BTPanel import request
     if os.path.exists(self.__args_tmp): os.remove(self.__args_tmp)
     self.__clean_args_file()
     data = {}
     data['GET'] = request.args.to_dict()
     data['POST'] = {}
     x_token = request.headers.get('x-http-token')
     if x_token:
         aes_pwd = x_token[:8] + x_token[40:48]
     for key in request.form.keys():
         data['POST'][key] = str(request.form.get(key,''))
         if x_token:
             if len(data['POST'][key]) > 5:
                 if data['POST'][key][:6] == 'BT-CRT':
                     data['POST'][key] = public.aes_decrypt(data['POST'][key][6:],aes_pwd)
     data['POST']['client_ip'] = public.GetClientIp()
     data = json.dumps(data)
     public.writeFile(self.__args_tmp,data)
Exemplo n.º 29
0
    def limit_address(self,type,v=""):
        import time
        clientIp = public.GetClientIp();
        numKey = 'limitIpNum_' + v + clientIp
        limit = 6;
        outTime = 600;
        try:
            #初始化
            num1 = cache.get(numKey)
            if not num1:
                cache.set(numKey,1,outTime);
                num1 = 1;
                        
            #计数
            if type == '+':
                cache.inc(numKey,1)
                self.error_num();
                session['code'] = True;
                return limit - (num1+1);

            #计数验证器
            if type == '++':
                cache.inc(numKey,1)
                self.error_num();
                session['code'] = False;
                return limit - (num1+1);

            #清空
            if type == '-':
                cache.delete(numKey);
                session['code'] = False;
                return 1;

            #清空验证器
            if type == '--':
                cache.delete(numKey);
                session['code'] = False;
                return 1;
            return limit - num1;
        except:
            return limit;
Exemplo n.º 30
0
def panel_public():
    get = get_input();
    get.client_ip = public.GetClientIp();
    if not hasattr(get,'name'): get.name = ''
    if not hasattr(get,'fun'): return abort(404)
    if not public.path_safe_check("%s/%s" % (get.name,get.fun)): return abort(404)
    if get.fun in ['scan_login', 'login_qrcode', 'set_login', 'is_scan_ok', 'blind','static']:
        if get.fun == 'static':
            if not 'filename' in get: return abort(404)
            if not public.path_safe_check("%s" % (get.filename)): return abort(404)
            s_file = '/www/server/panel/BTPanel/static/' + get.filename
            if s_file.find('..') != -1 or s_file.find('./') != -1: return abort(404)
            if not os.path.exists(s_file): return abort(404)
            return send_file(s_file, conditional=True, add_etags=True)

        #检查是否验证过安全入口
        if get.fun in ['login_qrcode','is_scan_ok']:
            global admin_check_auth,admin_path,route_path,admin_path_file
            if admin_path != '/bt' and os.path.exists(admin_path_file) and  not 'admin_auth' in session: return 'False'
        import wxapp
        pluwx = wxapp.wxapp()
        checks = pluwx._check(get)
        if type(checks) != bool or not checks: return public.getJson(checks),json_header
        data = public.getJson(eval('pluwx.'+get.fun+'(get)'))
        return data,json_header
    
    import panelPlugin
    plu = panelPlugin.panelPlugin()
    get.s = '_check';
    checks = plu.a(get)
    if type(checks) != bool or not checks: return public.getJson(checks),json_header
    get.s = get.fun
    comm.setSession()
    comm.init()
    comm.checkWebType()
    comm.GetOS()
    result = plu.a(get)
    session.clear()
    return public.getJson(result),json_header