def check_user(self): data = public.ExecShell( '''cat /etc/passwd | awk -F: '($3 == 0) { print $1 }'|grep -v '^root$' ''' ) data = data[0] if re.search("\w+", data): self.send_mail_data( public.GetLocalIp() + '服务器存在后门用户', public.GetLocalIp() + '服务器存在后门用户' + data + '检查/etc/passwd文件') return True else: return False
def check_user(self): data = public.ExecShell( '''cat /etc/passwd | awk -F: '($3 == 0) { print $1 }'|grep -v '^root$' ''' ) data = data[0] if re.search("\w+", data): self.send_mail_data( public.GetLocalIp() + 'There are backdoor users on the server', public.GetLocalIp() + 'There are backdoor users on the server' + data + 'Check the /etc/passwd file') return True else: return False
def set_two_step_auth(self,get): if not hasattr(get,"act") or not get.act: return public.returnMsg(False, "Please enter the operation mode") if get.act == "1": if not os.path.exists(self._core_fle_path): os.makedirs(self._core_fle_path) username = public.readFile(self._username_file) if not os.path.exists(self._bk_key_file): secret_key = public.readFile(self._key_file) if not secret_key or not username: self._create_key() else: os.rename(self._bk_key_file,self._key_file) secret_key = public.readFile(self._key_file) username = public.readFile(self._username_file) local_ip = public.GetLocalIp() if not secret_key: return public.returnMsg(False,"Failed to generate key or username. Please check if the hard disk space is insufficient or the directory cannot be written.[ {} ]".format(self._setup_path+"/data/")) try: data = pyotp.totp.TOTP(secret_key).provisioning_uri(username, issuer_name=str(local_ip)) public.writeFile(self._core_fle_path+'/qrcode.txt',str(data)) return public.returnMsg(True, "Open successfully") except Exception as e: return public.returnMsg(False, e) else: if os.path.exists(self._key_file): os.rename(self._key_file,self._bk_key_file) return public.returnMsg(True, "Closed successfully")
def generate_failture_notice(self, task_name, msg, remark): # from send_mail import send_mail # sm = send_mail() now = public.format_date(format="%Y-%m-%d %H:%M:%S") server_ip = public.GetLocalIp() if remark: remark = "\n* Task notes: {}".format(remark) notice_content = """Hello, aaPanel reminds you that the cron you set failed to execute: * Server IP: {} * Time: {} * Task name: {}{} * Error messages: <span style="color:red;"> {} </span> Please deal with it as soon as possible to avoid unnecessary trouble due to the failure of the backup task. -- Notification by aaPanel""".format( server_ip, now, task_name, remark, msg) tg_content = """📣‼*aaPanel reminds you that the cron failed to execute*‼ * Server IP*: {} * Time*: {} * Task name*: {} {} * Error messages*: {} -- Notification by aaPanel""".format( server_ip, now, task_name, remark, msg) return {'mail':notice_content,'tg':tg_content}
def generate_all_failture_notice(self, task_name, msg, backup_type, remark=""): # from send_mail import send_mail # sm = send_mail() now = public.format_date(format="%Y-%m-%d %H:%M:%S") server_ip = public.GetLocalIp() if remark: remark = "\n* Task notes: {}".format(remark) notice_content = """Hello, aaPanel reminds you that the cron you set failed to execute: * Server IP: {} * Time: {} * Task name: {} {} * The following is a list of {} that failed to backup: <table style="color:red;"> {} </table> Please deal with it as soon as possible to avoid unnecessary trouble due to the failure of the backup task. - Notification by aaPanel""".format( server_ip, now, task_name, remark, backup_type, msg) tg_content = """📣‼*aaPanel reminds you that the cron failed to execute*‼ * Server IP*: {} * Time*: {} * Task name*: {} {} * The following is a list of {} that failed to backup*: {} --Notification by aaPanel""".format( server_ip, now, task_name, remark, backup_type, msg) return {"mail":notice_content,"tg":tg_content}
def checkConfig(self): if not hasattr(web.ctx.session,'config'): web.ctx.session.config = public.M('config').where("id=?",('1',)).field('webserver,sites_path,backup_path,status,mysql_root').find(); if not hasattr(web.ctx.session.config,'email'): web.ctx.session.config['email'] = public.M('users').where("id=?",('1',)).getField('email'); if not hasattr(web.ctx.session,'address'): web.ctx.session.address = public.GetLocalIp()
def set_two_step_auth(self, get): if not hasattr(get, "act") or not get.act: return public.returnMsg(False, "请输入操作方式") if get.act == "1": if not os.path.exists(self._core_fle_path): os.makedirs(self._core_fle_path) username = public.readFile(self._username_file) if not os.path.exists(self._bk_key_file): secret_key = public.readFile(self._key_file) if not secret_key or not username: self._create_key() else: os.rename(self._bk_key_file, self._key_file) secret_key = public.readFile(self._key_file) username = public.readFile(self._username_file) local_ip = public.GetLocalIp() if not secret_key: return public.returnMsg( False, "生成key或username失败,请检查硬盘空间是否不足或目录无法写入[ {} ]".format( self._setup_path + "/data/")) try: data = pyotp.totp.TOTP(secret_key).provisioning_uri( username, issuer_name=local_ip) public.writeFile(self._core_fle_path + '/qrcode.txt', str(data)) return public.returnMsg(True, "开启成功") except Exception as e: return public.returnMsg(False, e) else: if os.path.exists(self._key_file): os.rename(self._key_file, self._bk_key_file) return public.returnMsg(True, "关闭成功")
def GetPanelInfo(self,get=None): #取面板配置 address = public.GetLocalIp() try: port = public.GetHost(True) except: port = '8888'; domain = '' if os.path.exists('data/domain.conf'): domain = public.readFile('data/domain.conf'); autoUpdate = '' if os.path.exists('data/autoUpdate.pl'): autoUpdate = 'checked'; limitip = '' if os.path.exists('data/limitip.conf'): limitip = public.readFile('data/limitip.conf'); admin_path = '/' if os.path.exists('data/admin_path.pl'): admin_path = public.readFile('data/admin_path.pl').strip() templates = [] #for template in os.listdir('BTPanel/templates/'): # if os.path.isdir('templates/' + template): templates.append(template); template = public.GetConfigValue('template') check502 = ''; if os.path.exists('data/502Task.pl'): check502 = 'checked'; return {'port':port,'address':address,'domain':domain,'auto':autoUpdate,'502':check502,'limitip':limitip,'templates':templates,'template':template,'admin_path':admin_path}
def checkConfig(self): if not 'config' in session: session['config'] = public.M('config').where("id=?",('1',)).field('webserver,sites_path,backup_path,status,mysql_root').find(); if not 'email' in session['config']: session['config']['email'] = public.M('users').where("id=?",('1',)).getField('email'); if not 'address' in session: session['address'] = public.GetLocalIp()
def CreateSSL(): import OpenSSL key = OpenSSL.crypto.PKey() key.generate_key(OpenSSL.crypto.TYPE_RSA, 2048) cert = OpenSSL.crypto.X509() cert.set_serial_number(0) cert.get_subject().CN = public.GetLocalIp() cert.set_issuer(cert.get_subject()) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60) cert.set_pubkey(key) cert.sign(key, 'md5') cert_ca = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert) private_key = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key) if isinstance(cert_ca, bytes): cert_ca = bytes.decode(cert_ca) private_key = bytes.decode(private_key) if len(cert_ca) > 100 and len(private_key) > 100: public.writeFile('ssl/certificate.pem', cert_ca) public.writeFile('ssl/privateKey.pem', private_key) public.writeFile('/www/server/panel/data/ssl.pl', '') print('success') return print('error')
def GetPanelInfo(self, get=None): #取面板配置 address = public.GetLocalIp() try: port = web.ctx.host.split(':')[1] except: port = '80' domain = '' if os.path.exists('data/domain.conf'): domain = public.readFile('data/domain.conf') autoUpdate = '' if os.path.exists('data/autoUpdate.pl'): autoUpdate = 'checked' limitip = '' if os.path.exists('data/limitip.conf'): limitip = public.readFile('data/limitip.conf') templates = [] for template in os.listdir('templates/'): if os.path.isdir('templates/' + template): templates.append(template) template = public.readFile('data/templates.pl') check502 = '' if os.path.exists('data/502Task.pl'): check502 = 'checked' return { 'port': port, 'address': address, 'domain': domain, 'auto': autoUpdate, '502': check502, 'limitip': limitip, 'templates': templates, 'template': template }
def send_baota2(self, filename): cloudUrl = 'http://www.bt.cn/api/panel/btwaf_submit' pdata = { 'codetxt': public.ReadFile(filename), 'md5': self.read_file_md5(filename), 'type': '0', 'host_ip': public.GetLocalIp(), 'size': os.path.getsize(filename) } ret = public.httpPost(cloudUrl, pdata) return True
def send_baota(self, filename): if not os.path.exists(filename): return False cloudUrl = 'http://www.bt.cn/api/panel/btwaf_submit' pdata = {'codetxt': public.ReadFile(filename), 'md5': self.read_file_md5(filename), 'type': '0', 'host_ip': public.GetLocalIp(), 'size': os.path.getsize(filename)} ret = public.httpPost(cloudUrl, pdata) if ret == '1': return self.check_webshell(filename) elif ret == '-1': return self.check_webshell(filename) else: return False
def BT_index(self, get): BTIndex = {} BTIndex['siteCount'] = public.M('sites').count() BTIndex['ftpCount'] = public.M('ftps').count() BTIndex['databaseCount'] = public.M('databases').count() BTIndex['BTTitle'] = public.GetConfigValue('title') BTIndex['time'] = self.GetBootTime() BTIndex['version'] = session['version'] BTIndex['system'] = self.GetSystemVersion() BTIndex['check'] = self.is_pro() BTIndex['ip'] = public.GetLocalIp() return BTIndex
def login(self): self.check_files() if not self.__mail_config['user_mail']['user_name']: return False self.check_user() self.__ip_data = json.loads(public.ReadFile(self.__ClIENT_IP)) ip = self.get_ip() if not ip: ip = ["127.0.0.1"] if len(ip[0]) == 0: return False try: import time mDate = time.strftime('%Y-%m-%d %X', time.localtime()) if ip[0] in self.__ip_data: if public.M('logs').where('type=? addtime', ( 'SSH security', mDate, )).count(): return False public.WriteLog( 'SSH security', 'The server {} login IP is {}, login user is root'.format( public.GetLocalIp(), ip[0])) return False else: if public.M('logs').where('type=? addtime', ( 'SSH security', mDate, )).count(): return False self.send_mail_data( 'Server {} login alarm'.format(public.GetLocalIp()), 'There is a login alarm on the server {}, the login IP is {}, the login user is root' .format(public.GetLocalIp(), ip[0])) public.WriteLog( 'SSH security', 'There is a login alarm on the server {}, the login IP is {}, login user is root' .format(public.GetLocalIp(), ip[0])) return True except: pass
def login(self): self.check_files() if not self.__mail_config['user_mail']['user_name']: return False self.check_user() self.__ip_data = json.loads(public.ReadFile(self.__ClIENT_IP)) ip = self.get_ip() if len(ip[0]) == 0: return False try: import time mDate = time.strftime('%Y-%m-%d %X', time.localtime()) if ip[0] in self.__ip_data: if public.M('logs').where('type=? addtime', ( 'SSH安全', mDate, )).count(): return False public.WriteLog( 'SSH安全', self.get_server_ip() + '服务器登陆登陆IP为' + ip[0] + '登陆用户为root') return False else: if public.M('logs').where('type=? addtime', ( 'SSH安全', mDate, )).count(): return False self.send_mail_data( self.get_server_ip() + '服务器异常登陆', public.GetLocalIp() + '服务器存在异常登陆登陆IP为' + ip[0] + '登陆用户为root') public.WriteLog( 'SSH安全', public.GetLocalIp() + '服务器存在异常登陆登陆IP为' + ip[0] + '登陆用户为root') return True except: pass
def login(self): self.check_files() if not self.__mail_config['user_mail']['user_name']:return False self.check_user() self.__ip_data = json.loads(public.ReadFile(self.__ClIENT_IP)) ip=self.get_ip() if not ip: ip = ["127.0.0.1"] if len(ip[0])==0:return False if ip[0] in self.__ip_data: public.WriteLog('SSH security', 'The server {} login IP is {}, login user is root'.format(public.GetLocalIp(),ip[0])) return False else: self.send_mail_data('Server {} login alarm'.format(public.GetLocalIp()),'There is a login alarm on the server {}, the login IP is {}, the login user is root'.format(public.GetLocalIp(),ip[0])) public.WriteLog('SSH security','There is a login alarm on the server {}, the login IP is {}, login user is root'.format(public.GetLocalIp(),ip [0])) return True
def BT_index(self, get): v_info = sys.version_info BTIndex = {} BTIndex['siteCount'] = public.M('sites').count() BTIndex['ftpCount'] = public.M('ftps').count() BTIndex['databaseCount'] = public.M('databases').count() BTIndex['BTTitle'] = public.GetConfigValue('title') BTIndex['time'] = self.GetBootTime() BTIndex['version'] = session['version'] BTIndex['system'] = self.GetSystemVersion() BTIndex['webserver'] = session['webserver'] BTIndex['py'] = str(v_info.major) + '.' + str( v_info.minor) + '.' + str(v_info.micro) BTIndex['check'] = self.is_pro() BTIndex['ip'] = public.GetLocalIp() return BTIndex
def __SendMail(self,email_data,even,warningUrl): serverip = "\nServer IP: 【 %s 】 " % public.GetLocalIp() if "title" not in email_data.keys() or "body" not in email_data.keys(): email_data["title"] = serverip + even email_data["body"] = serverip +even email_data = base64.b64encode(json.dumps(email_data)) data = {"access_key": self.GetAccessKey(), "data": email_data, "token": self.SetToken(email_data)} res = self.__send_mail(warningUrl, data) # print(res) if res == "1": if even: public.WriteLog('消息推送', "告警邮件发送成功") else: public.WriteLog('消息推送', "报表发送成功") return True
def CreateSSL(self): if os.path.exists('ssl/input.pl'): return True; import OpenSSL key = OpenSSL.crypto.PKey() key.generate_key(OpenSSL.crypto.TYPE_RSA, 2048) cert = OpenSSL.crypto.X509() cert.set_serial_number(0) cert.get_subject().CN = public.GetLocalIp() cert.set_issuer(cert.get_subject()) cert.gmtime_adj_notBefore( 0 ) cert.gmtime_adj_notAfter(86400 * 3650) cert.set_pubkey( key ) cert.sign( key, 'md5' ) cert_ca = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert) private_key = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key) if len(cert_ca) > 100 and len(private_key) > 100: public.writeFile('ssl/certificate.pem',cert_ca,'wb+') public.writeFile('ssl/privateKey.pem',private_key,'wb+') return True return False
def CheckPort(self, port): import socket IP = public.GetLocalIp() localIP = '127.0.0.1' temp = {} temp['port'] = port temp['local'] = True try: s = socket.socket() s.settimeout(0.15) s.connect((IP, port)) temp['status'] = True s.close() except Exception, ex: temp['status'] = False try: s = socket.socket() s.connect((localIP, port)) s.close() except: temp['local'] = False
def CreateSSL(): import OpenSSL key = OpenSSL.crypto.PKey() key.generate_key(OpenSSL.crypto.TYPE_RSA, 2048) cert = OpenSSL.crypto.X509() cert.set_serial_number(0) cert.get_subject().CN = public.GetLocalIp() cert.set_issuer(cert.get_subject()) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60) cert.set_pubkey(key) cert.sign(key, 'md5') cert_ca = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert) private_key = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key) if len(cert_ca) > 100 and len(private_key) > 100: public.writeFile('ssl/certificate.pem', cert_ca) public.writeFile('ssl/privateKey.pem', private_key) print '完成' return print '失败'
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.GetLocalIp()) if result == 0: return True, 'Risk-free' fail2ban_file = '/www/server/panel/plugin/fail2ban/config.json' if os.path.exists(fail2ban_file): try: fail2ban_config = json.loads(public.readFile(fail2ban_file)) if 'mysql' in fail2ban_config.keys(): if fail2ban_config['mysql']['act'] == 'true': return True, 'Fail2ban is enabled' except: pass return False, '当前MySQL端口: {},可被任意服务器访问,这可能导致MySQL被暴力破解,存在安全隐患'.format( port_tmp[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)) ''' file = '/etc/ssh/sshd_config' conf = public.readFile(file) if not conf: conf = '' rep = r"#*Port\s+([0-9]+)\s*\n" tmp1 = re.search(rep, conf) port = '22' if tmp1: port = tmp1.groups(0)[0] version = public.readFile('/etc/redhat-release') if not version: version = public.readFile('/etc/issue').strip().split("\n")[0].replace( '\\n', '').replace('\l', '').strip() else: version = version.replace('release ', '').replace('Linux', '').replace('(Core)', '').strip() if os.path.exists('/usr/bin/apt-get'): if os.path.exists('/etc/init.d/sshd'): status = public.ExecShell( "service sshd status | grep -P '(dead|stop)'|grep -v grep") else: status = public.ExecShell( "service ssh status | grep -P '(dead|stop)'|grep -v grep") else: if version.find(' 7.') != -1 or version.find( ' 8.') != -1 or version.find('Fedora') != -1: status = public.ExecShell( "systemctl status sshd.service | grep 'dead'|grep -v grep") else: status = public.ExecShell( "/etc/init.d/sshd status | grep -e 'stopped' -e '已停'|grep -v grep" ) fail2ban_file = '/www/server/panel/plugin/fail2ban/config.json' if os.path.exists(fail2ban_file): try: fail2ban_config = json.loads(public.readFile(fail2ban_file)) if 'sshd' in fail2ban_config.keys(): if fail2ban_config['sshd']['act'] == 'true': return True, 'Fail2ban is enable' except: pass if len(status[0]) > 3: status = False else: status = True if not status: return True, 'SSH service is not enabled' if port != '22': return True, 'The default SSH port has been modified' result = public.check_port_stat(int(port), public.GetLocalIp()) if result == 0: return True, 'Rick-free' return False, 'The default SSH port ({}) has not been modified, and the access IP limit configuration has not been done, there is a risk of SSH breaching'.format( port)
def get_ip(self, get): IP = public.GetLocalIp() if IP == '0.0.0.0': return '' return IP
def send_authenticated(): global local_ip if not local_ip: local_ip = public.GetLocalIp() result = Response('', 401,{'WWW-Authenticate': 'Basic realm="%s"' % local_ip.strip()}) if not 'login' in session and not 'admin_auth' in session: session.clear() return result
def send_authenticated(): global local_ip if not local_ip: local_ip = public.GetLocalIp() return Response('', 401,{'WWW-Authenticate': 'Basic realm="%s"' % local_ip})
def GetAllSiteReport(self,report_type,report,email_data,warningUrl): serverip = "\nServer IP: 【 %s 】 " % public.GetLocalIp() sites = self.GetNameOfSites() hourList = self.GetTimeStamp() sites_data = {} r_file = "%s/plugin/msg_push/rsc.txt" % self.setpath rsc = public.readFile(r_file) if not rsc: rsc = {"day":"","month":""} public.writeFile(r_file,json.dumps(rsc)) rsc = json.loads(rsc) #将前端传入的时间小于10的加前面加0 list = [] if "," in report: report = report.split(",") for i in report: if int(i) < 10: i = "0"+str(i) list.append(str(i)) report = list else: try: if int(report) < 10: report = "0"+str(report) except: pass now = time.time() for i in sites: if report_type == "hour": sites_data[i] = self.GetSiteReport(i, self.GetTime("lastHour")) else: sites_data[i] = self.GetSiteReport(i, report_type) print(self.hour) if report_type == "hour": for h in hourList: if h < now < h + 300: if self.hour == 0: email_data["title"] = "监控报表时报表" email_data["body"] = serverip+self.FormatHtml(sites_data) # print("监控报表时报表" + str(email_data)) even = "" # if self.__send_mail(warningUrl, email_data) == "1": # public.WriteLog('消息推送', "时报表发送成功") if self.__SendMail(email_data,even,warningUrl): self.hour += 1 break else: if h + 300 < now < h + 500: self.hour = 0 elif report_type == "daily": if report == self.GetTime("hour"): if not rsc["day"]: yesterday = "%s-%s-%s" % (self.GetTime("year"),self.GetTime("month"),self.GetTime("yesterday")) email_data["title"] = "监控报表日报表 %s" % yesterday email_data["body"] = serverip+self.FormatHtml(sites_data) even = "" if self.__SendMail(email_data,even,warningUrl): rsc["day"] = "1" public.writeFile(r_file, json.dumps(rsc)) # print("监控报表日报表"+str(email_data)) else: if rsc["day"]: rsc["day"] = "" public.writeFile(r_file, json.dumps(rsc)) else: if report[0] == self.GetTime("day") and self.GetTime("hour") == report[1]: if not rsc["month"]: lastMonth = "%s-%s" % (self.GetTime("year"),self.GetTime("lastMonth")) email_data["title"] = "报表监控月报表 %s" % lastMonth email_data["body"] = serverip+self.FormatHtml(sites_data) even = "" public.writeFile("/tmp/month.html",str(email_data["body"])) # print("监控报表月报表" + str(email_data)) if self.__SendMail(email_data,even,warningUrl): rsc["month"] = "1" public.writeFile(r_file, json.dumps(rsc)) else: if rsc["month"]: rsc["month"] = "" public.writeFile(r_file, json.dumps(rsc))