Simple Linux Panel
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
mdserver-web/plugins/op_waf/index.py

1341 lines
33 KiB

6 years ago
# coding:utf-8
import sys
import io
import os
import time
import subprocess
import json
import re
6 years ago
sys.path.append(os.getcwd() + "/class/core")
import mw
6 years ago
app_debug = False
if mw.isAppleSystem():
6 years ago
app_debug = True
def getPluginName():
return 'op_waf'
6 years ago
def getPluginDir():
return mw.getPluginDir() + '/' + getPluginName()
6 years ago
def getServerDir():
return mw.getServerDir() + '/' + getPluginName()
6 years ago
def getArgs():
args = sys.argv[2:]
tmp = {}
args_len = len(args)
if args_len == 1:
t = args[0].strip('{').strip('}')
t = t.split(':')
tmp[t[0]] = t[1]
elif args_len > 1:
for i in range(len(args)):
t = args[i].split(':')
tmp[t[0]] = t[1]
return tmp
def checkArgs(data, ck=[]):
for i in range(len(ck)):
if not ck[i] in data:
return (False, mw.returnJson(False, '参数:(' + ck[i] + ')没有!'))
return (True, mw.returnJson(True, 'ok'))
3 years ago
sys.path.append(getPluginDir() + "/class")
from luamaker import luamaker
def listToLuaFile(path, lists):
content = luamaker.makeLuaTable(lists)
content = "return " + content
mw.writeFile(path, content)
3 years ago
def htmlToLuaFile(path, content):
content = "return [[" + content + "]]"
mw.writeFile(path, content)
6 years ago
def getConf():
path = mw.getServerDir() + "/openresty/nginx/conf/nginx.conf"
6 years ago
return path
3 years ago
def pSqliteDb(dbname='logs'):
3 years ago
name = "waf"
db_dir = getServerDir() + '/logs/'
if not os.path.exists(db_dir):
mw.execShell('mkdir -p ' + db_dir)
file = db_dir + name + '.db'
if not os.path.exists(file):
conn = mw.M(dbname).dbPos(db_dir, name)
sql = mw.readFile(getPluginDir() + '/conf/init.sql')
sql_list = sql.split(';')
for index in range(len(sql_list)):
conn.execute(sql_list[index])
else:
conn = mw.M(dbname).dbPos(db_dir, name)
conn.execute("PRAGMA synchronous = 0")
conn.execute("PRAGMA page_size = 4096")
conn.execute("PRAGMA journal_mode = wal")
conn.execute("PRAGMA journal_size_limit = 1073741824")
return conn
6 years ago
def initDomainInfo():
data = []
path_domains = getJsonPath('domains')
_list = mw.M('sites').field('id,name,path').where(
6 years ago
'status=?', ('1',)).order('id desc').select()
for i in range(len(_list)):
tmp = {}
tmp['name'] = _list[i]['name']
tmp['path'] = _list[i]['path']
_list_domain = mw.M('domain').field('name').where(
6 years ago
'pid=?', (_list[i]['id'],)).order('id desc').select()
tmp_j = []
for j in range(len(_list_domain)):
tmp_j.append(_list_domain[j]['name'])
tmp['domains'] = tmp_j
data.append(tmp)
cjson = mw.getJson(data)
mw.writeFile(path_domains, cjson)
6 years ago
def initSiteInfo():
data = []
path_domains = getJsonPath('domains')
6 years ago
path_config = getJsonPath('config')
6 years ago
path_site = getJsonPath('site')
config_contents = mw.readFile(path_config)
6 years ago
config_contents = json.loads(config_contents)
domain_contents = mw.readFile(path_domains)
6 years ago
domain_contents = json.loads(domain_contents)
try:
site_contents = mw.readFile(path_site)
6 years ago
except Exception as e:
site_contents = "{}"
site_contents = json.loads(site_contents)
6 years ago
site_contents_new = {}
6 years ago
for x in range(len(domain_contents)):
name = domain_contents[x]['name']
if name in site_contents:
6 years ago
site_contents_new[name] = site_contents[name]
6 years ago
else:
tmp = {}
3 years ago
tmp['cdn'] = True
6 years ago
tmp['log'] = True
tmp['get'] = True
tmp['post'] = True
3 years ago
tmp['open'] = True
6 years ago
6 years ago
tmp['cc'] = config_contents['cc']
6 years ago
tmp['retry'] = config_contents['retry']
tmp['get'] = config_contents['get']
tmp['post'] = config_contents['post']
tmp['user-agent'] = config_contents['user-agent']
tmp['cookie'] = config_contents['cookie']
tmp['scan'] = config_contents['scan']
tmp['safe_verify'] = config_contents['safe_verify']
6 years ago
6 years ago
cdn_header = ['x-forwarded-for',
3 years ago
'x-real-ip',
'x-forwarded',
'forwarded-for',
'forwarded',
'true-client-ip',
'client-ip',
'ali-cdn-real-ip',
'cdn-src-ip',
'cdn-real-ip',
'cf-connecting-ip',
'x-cluster-client-ip',
'wl-proxy-client-ip',
'proxy-client-ip',
'true-client-ip',
'HTTP_CF_CONNECTING_IP']
6 years ago
tmp['cdn_header'] = cdn_header
6 years ago
disable_upload_ext = ["php", "jsp"]
tmp['disable_upload_ext'] = disable_upload_ext
disable_path = ['sql']
6 years ago
tmp['disable_ext'] = disable_path
6 years ago
6 years ago
site_contents_new[name] = tmp
cjson = mw.getJson(site_contents_new)
mw.writeFile(path_site, cjson)
6 years ago
6 years ago
6 years ago
def initTotalInfo():
data = []
path_domains = getJsonPath('domains')
path_total = getJsonPath('total')
domain_contents = mw.readFile(path_domains)
6 years ago
domain_contents = json.loads(domain_contents)
try:
total_contents = mw.readFile(path_total)
6 years ago
except Exception as e:
total_contents = "{}"
total_contents = json.loads(total_contents)
total_contents_new = {}
for x in range(len(domain_contents)):
name = domain_contents[x]['name']
6 years ago
if 'sites' in total_contents and name in total_contents['sites']:
6 years ago
pass
else:
tmp = {}
tmp['cdn'] = 0
tmp['log'] = 0
tmp['get'] = 0
tmp['post'] = 0
tmp['total'] = 0
3 years ago
tmp['path'] = 0
tmp['php_path'] = 0
tmp['upload_ext'] = 0
6 years ago
_name = {}
_name[name] = tmp
total_contents['sites'] = _name
2 years ago
total_contents['start_time'] = str(time.time())
cjson = mw.getJson(total_contents)
mw.writeFile(path_total, cjson)
6 years ago
6 years ago
def dstWafConf():
return mw.getServerDir() + "/web_conf/nginx/vhost/opwaf.conf"
6 years ago
6 years ago
def contentReplace(content):
service_path = mw.getServerDir()
3 years ago
waf_root = getServerDir()
waf_path = waf_root + "/waf"
content = content.replace('{$ROOT_PATH}', mw.getRootDir())
6 years ago
content = content.replace('{$SERVER_PATH}', service_path)
content = content.replace('{$WAF_PATH}', waf_path)
3 years ago
content = content.replace('{$WAF_ROOT}', waf_root)
6 years ago
return content
3 years ago
def autoMakeLuaConfSingle(file):
# path = getPluginDir() + "/waf/rule/" + file + ".json"
3 years ago
path = getServerDir() + "/waf/rule/" + file + ".json"
3 years ago
to_path = getServerDir() + "/waf/conf/rule_" + file + ".lua"
3 years ago
content = mw.readFile(path)
# print(content)
content = json.loads(content)
listToLuaFile(to_path, content)
def autoMakeLuaImportSingle(file):
path = getServerDir() + "/waf/" + file + ".json"
3 years ago
to_path = getServerDir() + "/waf/conf/waf_" + file + ".lua"
3 years ago
content = mw.readFile(path)
# print(content)
content = json.loads(content)
listToLuaFile(to_path, content)
3 years ago
def autoMakeLuaHtmlSingle(file):
path = getServerDir() + "/waf/html/" + file + ".html"
to_path = getServerDir() + "/waf/html/html_" + file + ".lua"
content = mw.readFile(path)
htmlToLuaFile(to_path, content)
3 years ago
def autoMakeLuaConf():
conf_list = ['args', 'cookie', 'ip_black', 'ip_white',
'ipv6_black', 'post', 'scan_black', 'url',
'url_white', 'user_agent']
3 years ago
for x in conf_list:
autoMakeLuaConfSingle(x)
3 years ago
import_list = ['config', 'site', 'domains']
3 years ago
for x in import_list:
autoMakeLuaImportSingle(x)
3 years ago
html_list = ['get', 'post', 'safe_js', 'user_agent', 'cookie', 'other']
for x in html_list:
autoMakeLuaHtmlSingle(x)
3 years ago
3 years ago
def initDefaultInfo():
path = getServerDir()
djson = path + "/waf/domains.json"
default_json = path + "/waf/default.json"
if os.path.exists(djson):
content = mw.readFile(djson)
content = json.loads(content)
ddata = {}
dlist = []
for i in content:
dlist.append(i["name"])
dlist.append('unset')
ddata["list"] = dlist
if len(ddata["list"]) < 1:
ddata["default"] = "unset"
else:
ddata["default"] = dlist[0]
mw.writeFile(default_json, json.dumps(ddata))
3 years ago
def autoMakeConfig():
path = getServerDir()
initDomainInfo()
initSiteInfo()
initTotalInfo()
autoMakeLuaConf()
3 years ago
def restartWeb():
autoMakeConfig()
mw.opWeb('stop')
mw.opWeb('start')
3 years ago
6 years ago
def initDreplace():
2 years ago
root_worker_dir = mw.getServerDir() + '/web_conf/nginx/lua/init_worker_by_lua_file'
root_access_dir = mw.getServerDir() + '/web_conf/nginx/lua/access_by_lua_file'
3 years ago
path = getServerDir()
3 years ago
if not os.path.exists(path + '/waf/lua'):
6 years ago
sdir = getPluginDir() + '/waf'
cmd = 'cp -rf ' + sdir + ' ' + path
mw.execShell(cmd)
6 years ago
3 years ago
logs_path = path + '/logs'
if not os.path.exists(logs_path):
mw.execShell('mkdir -p ' + logs_path)
debug_log = path + '/debug.log'
if not os.path.exists(debug_log):
mw.execShell('echo "" > ' + debug_log)
3 years ago
config = path + '/waf/config.json'
4 years ago
content = mw.readFile(config)
content = json.loads(content)
3 years ago
wfDir = path + "/waf/html"
content['reqfile_path'] = wfDir
4 years ago
mw.writeFile(config, mw.getJson(content))
config_common = path + "/waf/lua/common.lua"
content = mw.readFile(config_common)
content = contentReplace(content)
mw.writeFile(config_common, content)
2 years ago
dst_init_worker = root_worker_dir + '/opwaf_init_worker.lua'
3 years ago
init_worker = path + "/waf/lua/init_worker.lua"
content = mw.readFile(init_worker)
content = contentReplace(content)
2 years ago
mw.writeFile(dst_init_worker, content)
access_file = root_access_dir + '/opwaf_init.lua'
config = path + "/waf/lua/init.lua"
content = mw.readFile(config)
content = contentReplace(content)
mw.writeFile(access_file, content)
3 years ago
waf_conf = dstWafConf()
if not os.path.exists(waf_conf):
waf_tpl = getPluginDir() + "/conf/luawaf.conf"
content = mw.readFile(waf_tpl)
content = contentReplace(content)
mw.writeFile(waf_conf, content)
6 years ago
4 years ago
initDomainInfo()
initSiteInfo()
initTotalInfo()
3 years ago
autoMakeLuaConf()
3 years ago
initDefaultInfo()
3 years ago
pSqliteDb()
3 years ago
if not mw.isAppleSystem():
mw.execShell("chown -R www:www " + path)
6 years ago
def status():
path = getConf()
if not os.path.exists(path):
return 'stop'
waf_conf = dstWafConf()
if not os.path.exists(waf_conf):
return 'stop'
return 'start'
6 years ago
def start():
6 years ago
initDreplace()
6 years ago
2 years ago
mw.opLuaInitWorkerFile()
mw.opLuaInitAccessFile()
3 years ago
3 years ago
import tool_task
tool_task.createBgTask()
restartWeb()
6 years ago
return 'ok'
6 years ago
6 years ago
def stop():
2 years ago
root_worker_dir = mw.getServerDir() + '/web_conf/nginx/lua/init_worker_by_lua_file'
root_access_dir = mw.getServerDir() + '/web_conf/nginx/lua/access_by_lua_file'
6 years ago
2 years ago
dst_init_worker = root_worker_dir + '/opwaf_init_worker.lua'
if os.path.exists(dst_init_worker):
os.remove(dst_init_worker)
access_file = root_access_dir + '/opwaf_init.lua'
if os.path.exists(access_file):
os.remove(access_file)
3 years ago
wafconf = dstWafConf()
if os.path.exists(wafconf):
os.remove(wafconf)
3 years ago
import tool_task
tool_task.removeBgTask()
2 years ago
mw.opLuaInitWorkerFile()
mw.opLuaInitAccessFile()
restartWeb()
6 years ago
return 'ok'
6 years ago
def restart():
restartWeb()
6 years ago
return 'ok'
6 years ago
def reload():
6 years ago
stop()
3 years ago
3 years ago
path = getServerDir()
path_tpl = getPluginDir()
config = path + "/waf/lua/common.lua"
config_tpl = path_tpl + "/waf/lua/common.lua"
content = mw.readFile(config_tpl)
content = contentReplace(content)
mw.writeFile(config, content)
config = path + "/waf/lua/init_worker.lua"
config_tpl = path_tpl + "/waf/lua/init_worker.lua"
content = mw.readFile(config_tpl)
content = contentReplace(content)
mw.writeFile(config, content)
3 years ago
config = path + "/waf/lua/init.lua"
config_tpl = path_tpl + "/waf/lua/init.lua"
content = mw.readFile(config_tpl)
content = contentReplace(content)
mw.writeFile(config, content)
3 years ago
errlog = mw.getServerDir() + "/openresty/nginx/logs/error.log"
mw.execShell('rm -rf ' + errlog)
6 years ago
start()
restartWeb()
6 years ago
return 'ok'
6 years ago
6 years ago
def getJsonPath(name):
3 years ago
path = getServerDir() + "/waf/" + name + ".json"
return path
6 years ago
def getRuleJsonPath(name):
3 years ago
path = getServerDir() + "/waf/rule/" + name + ".json"
6 years ago
return path
def getRule():
args = getArgs()
data = checkArgs(args, ['rule_name'])
if not data[0]:
return data[1]
rule_name = args['rule_name']
fpath = getRuleJsonPath(rule_name)
content = mw.readFile(fpath)
return mw.returnJson(True, 'ok', content)
6 years ago
6 years ago
def addRule():
args = getArgs()
data = checkArgs(args, ['ruleName', 'ruleValue', 'ps'])
if not data[0]:
return data[1]
ruleValue = args['ruleValue']
ruleName = args['ruleName']
ps = args['ps']
fpath = getRuleJsonPath(ruleName)
content = mw.readFile(fpath)
6 years ago
content = json.loads(content)
tmp_k = []
tmp_k.append(1)
tmp_k.append(ruleValue)
tmp_k.append(ps)
tmp_k.append(1)
content.append(tmp_k)
cjson = mw.getJson(content)
mw.writeFile(fpath, cjson)
3 years ago
restartWeb()
return mw.returnJson(True, '设置成功!', content)
6 years ago
6 years ago
def removeRule():
args = getArgs()
data = checkArgs(args, ['ruleName', 'index'])
if not data[0]:
return data[1]
index = int(args['index'])
ruleName = args['ruleName']
fpath = getRuleJsonPath(ruleName)
content = mw.readFile(fpath)
6 years ago
content = json.loads(content)
k = content[index]
content.remove(k)
cjson = mw.getJson(content)
mw.writeFile(fpath, cjson)
3 years ago
restartWeb()
return mw.returnJson(True, '设置成功!', content)
6 years ago
def setRuleState():
args = getArgs()
data = checkArgs(args, ['ruleName', 'index'])
if not data[0]:
return data[1]
index = int(args['index'])
ruleName = args['ruleName']
fpath = getRuleJsonPath(ruleName)
content = mw.readFile(fpath)
6 years ago
content = json.loads(content)
b = content[index][0]
if b == 1:
content[index][0] = 0
else:
content[index][0] = 1
cjson = mw.getJson(content)
mw.writeFile(fpath, cjson)
3 years ago
restartWeb()
return mw.returnJson(True, '设置成功!', content)
6 years ago
6 years ago
6 years ago
def modifyRule():
args = getArgs()
data = checkArgs(args, ['index', 'ruleName', 'ruleBody', 'rulePs'])
if not data[0]:
return data[1]
index = int(args['index'])
ruleName = args['ruleName']
ruleBody = args['ruleBody']
rulePs = args['rulePs']
fpath = getRuleJsonPath(ruleName)
content = mw.readFile(fpath)
6 years ago
content = json.loads(content)
tmp = content[index]
tmp_k = []
tmp_k.append(tmp[0])
tmp_k.append(ruleBody)
tmp_k.append(rulePs)
tmp_k.append(tmp[3])
content[index] = tmp_k
cjson = mw.getJson(content)
mw.writeFile(fpath, cjson)
3 years ago
restartWeb()
return mw.returnJson(True, '设置成功!', content)
6 years ago
6 years ago
def getSiteRule():
args = getArgs()
data = checkArgs(args, ['siteName', 'ruleName'])
if not data[0]:
return data[1]
siteName = args['siteName']
siteRule = args['ruleName']
path = getJsonPath('site')
content = mw.readFile(path)
6 years ago
content = json.loads(content)
r = content[siteName][siteRule]
cjson = mw.getJson(r)
return mw.returnJson(True, 'ok!', cjson)
6 years ago
6 years ago
def addSiteRule():
args = getArgs()
data = checkArgs(args, ['siteName', 'ruleName', 'ruleValue'])
if not data[0]:
return data[1]
siteName = args['siteName']
siteRule = args['ruleName']
ruleValue = args['ruleValue']
path = getJsonPath('site')
content = mw.readFile(path)
6 years ago
content = json.loads(content)
content[siteName][siteRule].append(ruleValue)
cjson = mw.getJson(content)
mw.writeFile(path, cjson)
3 years ago
restartWeb()
return mw.returnJson(True, '设置成功!')
6 years ago
6 years ago
6 years ago
def addIpWhite():
args = getArgs()
data = checkArgs(args, ['start_ip', 'end_ip'])
if not data[0]:
return data[1]
start_ip = args['start_ip']
end_ip = args['end_ip']
path = getRuleJsonPath('ip_white')
content = mw.readFile(path)
6 years ago
content = json.loads(content)
data = []
start_ip_list = start_ip.split('.')
tmp = []
for x in range(len(start_ip_list)):
tmp.append(int(start_ip_list[x]))
end_ip_list = end_ip.split('.')
tmp2 = []
for x in range(len(end_ip_list)):
tmp2.append(int(end_ip_list[x]))
data.append(tmp)
data.append(tmp2)
content.append(data)
cjson = mw.getJson(content)
mw.writeFile(path, cjson)
3 years ago
restartWeb()
return mw.returnJson(True, '设置成功!')
6 years ago
6 years ago
6 years ago
def removeIpWhite():
args = getArgs()
data = checkArgs(args, ['index'])
if not data[0]:
return data[1]
index = args['index']
path = getRuleJsonPath('ip_white')
content = mw.readFile(path)
6 years ago
content = json.loads(content)
6 years ago
k = content[int(index)]
content.remove(k)
6 years ago
cjson = mw.getJson(content)
mw.writeFile(path, cjson)
3 years ago
3 years ago
restartWeb()
return mw.returnJson(True, '设置成功!')
6 years ago
6 years ago
6 years ago
def addIpBlack():
args = getArgs()
data = checkArgs(args, ['start_ip', 'end_ip'])
if not data[0]:
return data[1]
start_ip = args['start_ip']
end_ip = args['end_ip']
path = getRuleJsonPath('ip_black')
content = mw.readFile(path)
6 years ago
content = json.loads(content)
data = []
start_ip_list = start_ip.split('.')
tmp = []
for x in range(len(start_ip_list)):
tmp.append(int(start_ip_list[x]))
end_ip_list = end_ip.split('.')
tmp2 = []
for x in range(len(end_ip_list)):
tmp2.append(int(end_ip_list[x]))
data.append(tmp)
data.append(tmp2)
content.append(data)
cjson = mw.getJson(content)
mw.writeFile(path, cjson)
3 years ago
3 years ago
restartWeb()
return mw.returnJson(True, '设置成功!')
6 years ago
6 years ago
6 years ago
def removeIpBlack():
args = getArgs()
data = checkArgs(args, ['index'])
if not data[0]:
return data[1]
index = args['index']
path = getRuleJsonPath('ip_black')
content = mw.readFile(path)
6 years ago
content = json.loads(content)
k = content[int(index)]
content.remove(k)
cjson = mw.getJson(content)
mw.writeFile(path, cjson)
3 years ago
3 years ago
restartWeb()
return mw.returnJson(True, '设置成功!')
6 years ago
6 years ago
6 years ago
def setIpv6Black():
args = getArgs()
data = checkArgs(args, ['addr'])
if not data[0]:
return data[1]
6 years ago
addr = args['addr'].replace('_', ':')
6 years ago
path = getRuleJsonPath('ipv6_black')
content = mw.readFile(path)
6 years ago
content = json.loads(content)
content.append(addr)
cjson = mw.getJson(content)
mw.writeFile(path, cjson)
3 years ago
restartWeb()
return mw.returnJson(True, '设置成功!')
6 years ago
6 years ago
6 years ago
def delIpv6Black():
args = getArgs()
data = checkArgs(args, ['addr'])
if not data[0]:
return data[1]
6 years ago
addr = args['addr'].replace('_', ':')
6 years ago
path = getRuleJsonPath('ipv6_black')
content = mw.readFile(path)
6 years ago
content = json.loads(content)
6 years ago
6 years ago
content.remove(addr)
cjson = mw.getJson(content)
mw.writeFile(path, cjson)
3 years ago
restartWeb()
return mw.returnJson(True, '设置成功!')
6 years ago
6 years ago
def removeSiteRule():
args = getArgs()
data = checkArgs(args, ['siteName', 'ruleName', 'index'])
if not data[0]:
return data[1]
siteName = args['siteName']
siteRule = args['ruleName']
index = args['index']
path = getJsonPath('site')
content = mw.readFile(path)
6 years ago
content = json.loads(content)
ruleValue = content[siteName][siteRule][int(index)]
content[siteName][siteRule].remove(ruleValue)
cjson = mw.getJson(content)
mw.writeFile(path, cjson)
3 years ago
3 years ago
restartWeb()
return mw.returnJson(True, '设置成功!')
6 years ago
def setObjStatus():
args = getArgs()
data = checkArgs(args, ['obj', 'statusCode'])
if not data[0]:
return data[1]
conf = getJsonPath('config')
content = mw.readFile(conf)
cobj = json.loads(content)
6 years ago
o = args['obj']
3 years ago
status = int(args['statusCode'])
cobj[o]['status'] = status
cjson = mw.getJson(cobj)
mw.writeFile(conf, cjson)
3 years ago
3 years ago
restartWeb()
return mw.returnJson(True, '设置成功!')
6 years ago
6 years ago
6 years ago
def setRetry():
6 years ago
args = getArgs()
6 years ago
data = checkArgs(args, ['retry', 'retry_time',
'retry_cycle', 'is_open_global'])
6 years ago
if not data[0]:
return data[1]
conf = getJsonPath('config')
content = mw.readFile(conf)
6 years ago
cobj = json.loads(content)
cobj['retry'] = args
cjson = mw.getJson(cobj)
mw.writeFile(conf, cjson)
3 years ago
3 years ago
restartWeb()
return mw.returnJson(True, '设置成功!', [])
6 years ago
6 years ago
def setSafeVerify():
args = getArgs()
data = checkArgs(args, ['auto', 'time', 'cpu'])
if not data[0]:
return data[1]
conf = getJsonPath('config')
content = mw.readFile(conf)
cobj = json.loads(content)
cobj['safe_verify']['time'] = args['time']
2 years ago
cobj['safe_verify']['cpu'] = int(args['cpu'])
if args['auto'] == '0':
cobj['safe_verify']['auto'] = False
else:
cobj['safe_verify']['auto'] = True
cjson = mw.getJson(cobj)
mw.writeFile(conf, cjson)
3 years ago
3 years ago
restartWeb()
return mw.returnJson(True, '设置成功!', [])
6 years ago
def setSiteRetry():
return mw.returnJson(True, '设置成功-?!', [])
6 years ago
def setCcConf():
args = getArgs()
data = checkArgs(args, ['siteName', 'cycle', 'limit',
3 years ago
'endtime', 'is_open_global'])
6 years ago
if not data[0]:
return data[1]
conf = getJsonPath('config')
content = mw.readFile(conf)
6 years ago
cobj = json.loads(content)
tmp = cobj['cc']
6 years ago
tmp['cycle'] = int(args['cycle'])
tmp['limit'] = int(args['limit'])
tmp['endtime'] = int(args['endtime'])
6 years ago
tmp['is_open_global'] = args['is_open_global']
tmp['increase'] = args['increase']
cobj['cc'] = tmp
cjson = mw.getJson(cobj)
mw.writeFile(conf, cjson)
3 years ago
3 years ago
restartWeb()
return mw.returnJson(True, '设置成功!', [])
6 years ago
6 years ago
def setSiteCcConf():
4 years ago
return mw.returnJson(False, '暂未开发!', [])
6 years ago
6 years ago
def saveScanRule():
args = getArgs()
6 years ago
data = checkArgs(args, ['header', 'cookie', 'args'])
6 years ago
if not data[0]:
return data[1]
6 years ago
path = getRuleJsonPath('scan_black')
cjson = mw.getJson(args)
mw.writeFile(path, cjson)
3 years ago
3 years ago
restartWeb()
return mw.returnJson(True, '设置成功!', [])
6 years ago
6 years ago
def getSiteConfig():
path = getJsonPath('site')
content = mw.readFile(path)
6 years ago
content = json.loads(content)
total = getJsonPath('total')
total_content = mw.readFile(total)
6 years ago
total_content = json.loads(total_content)
# print total_content
6 years ago
6 years ago
for x in content:
tmp = []
tmp_v = {}
if 'sites' in total_content and x in total_content['sites']:
6 years ago
tmp_v = total_content['sites'][x]
key_list = ['get', 'post', 'user-agent', 'cookie', 'cdn', 'cc']
6 years ago
for kx in range(len(key_list)):
ktmp = {}
6 years ago
if kx in tmp_v:
6 years ago
ktmp['value'] = tmp_v[key_list[kx]]
else:
6 years ago
ktmp['value'] = ''
6 years ago
ktmp['key'] = key_list[kx]
tmp.append(ktmp)
# print tmp
content[x]['total'] = tmp
content = mw.getJson(content)
return mw.returnJson(True, 'ok!', content)
6 years ago
6 years ago
3 years ago
def getSiteListData():
path = getServerDir() + "/waf/default.json"
data = mw.readFile(path)
return json.loads(data)
def setDefaultSite(name):
path = getServerDir() + "/waf/default.json"
data = mw.readFile(path)
data = json.loads(data)
data['default'] = name
mw.writeFile(path, json.dumps(data))
return mw.returnJson(True, 'OK')
def getDefaultSite():
data = getSiteListData()
return mw.returnJson(True, 'OK', data)
6 years ago
def getSiteConfigByName():
args = getArgs()
data = checkArgs(args, ['siteName'])
if not data[0]:
return data[1]
path = getJsonPath('site')
content = mw.readFile(path)
6 years ago
content = json.loads(content)
siteName = args['siteName']
retData = {}
if siteName in content:
retData = content[siteName]
return mw.returnJson(True, 'ok!', retData)
6 years ago
6 years ago
def addSiteCdnHeader():
args = getArgs()
data = checkArgs(args, ['siteName', 'cdn_header'])
if not data[0]:
return data[1]
path = getJsonPath('site')
content = mw.readFile(path)
6 years ago
content = json.loads(content)
siteName = args['siteName']
retData = {}
if siteName in content:
content[siteName]['cdn_header'].append(args['cdn_header'])
cjson = mw.getJson(content)
mw.writeFile(path, cjson)
3 years ago
3 years ago
restartWeb()
return mw.returnJson(True, '添加成功!')
6 years ago
def removeSiteCdnHeader():
args = getArgs()
data = checkArgs(args, ['siteName', 'cdn_header'])
if not data[0]:
return data[1]
path = getJsonPath('site')
content = mw.readFile(path)
6 years ago
content = json.loads(content)
siteName = args['siteName']
retData = {}
if siteName in content:
content[siteName]['cdn_header'].remove(args['cdn_header'])
cjson = mw.getJson(content)
mw.writeFile(path, cjson)
3 years ago
3 years ago
restartWeb()
return mw.returnJson(True, '删除成功!')
6 years ago
6 years ago
6 years ago
def outputData():
args = getArgs()
data = checkArgs(args, ['sname'])
6 years ago
if not data[0]:
return data[1]
path = getRuleJsonPath(args['sname'])
content = mw.readFile(path)
return mw.returnJson(True, 'ok', content)
6 years ago
6 years ago
6 years ago
def importData():
args = getArgs()
data = checkArgs(args, ['sname', 'pdata'])
6 years ago
if not data[0]:
return data[1]
path = getRuleJsonPath(args['sname'])
source_data = mw.readFile(path)
source_data = json.loads(source_data)
save_data = []
save_data.append(source_data[0])
pdata = args['pdata'].strip()
try:
pdata = json.loads(pdata)
mw.writeFile(path, json.dumps(pdata))
except Exception as e:
pdata = pdata.split("\\n")
for x in pdata:
pval = x.strip()
if pval != "":
vv = json.loads(pval)
save_data.append(vv[0])
mw.writeFile(path, json.dumps(save_data))
# restartWeb()
return mw.returnJson(True, '设置成功!')
6 years ago
6 years ago
6 years ago
def getLogsList():
args = getArgs()
3 years ago
data = checkArgs(args, ['site', 'page', 'page_size', 'tojs'])
6 years ago
if not data[0]:
return data[1]
3 years ago
page = int(args['page'])
page_size = int(args['page_size'])
domain = args['site']
tojs = args['tojs']
3 years ago
3 years ago
conn = pSqliteDb('logs')
field = 'time,ip,domain,server_name,method,uri,user_agent,rule_name,reason'
limit = str(page_size) + ' offset ' + str(page_size * (page - 1))
condition = ''
conn = conn.field(field)
conn = conn.where("1=1", ()).where("domain=?", (domain,))
clist = conn.limit(limit).order('time desc').inquiry()
count_key = "count(*) as num"
count = conn.field(count_key).limit('').order('').inquiry()
# print(count)
count = count[0][count_key]
3 years ago
3 years ago
data = {}
_page = {}
_page['count'] = count
_page['p'] = page
_page['row'] = page_size
_page['tojs'] = tojs
data['page'] = mw.getPage(_page)
data['data'] = clist
6 years ago
return mw.returnJson(True, 'ok!', data)
6 years ago
def getSafeLogs():
args = getArgs()
data = checkArgs(args, ['siteName', 'toDate', 'p'])
if not data[0]:
return data[1]
3 years ago
path = getServerDir() + '/logs'
6 years ago
file = path + '/' + args['siteName'] + '_' + args['toDate'] + '.log'
if not os.path.exists(file):
return mw.returnJson(False, "文件不存在!")
6 years ago
retData = []
file = open(file)
while 1:
lines = file.readlines(100000)
if not lines:
break
for line in lines:
retData.append(json.loads(line))
return mw.returnJson(True, '设置成功!', retData)
6 years ago
def setObjOpen():
args = getArgs()
data = checkArgs(args, ['obj'])
if not data[0]:
return data[1]
conf = getJsonPath('config')
content = mw.readFile(conf)
cobj = json.loads(content)
o = args['obj']
if cobj[o]["open"]:
cobj[o]["open"] = False
else:
cobj[o]["open"] = True
cjson = mw.getJson(cobj)
mw.writeFile(conf, cjson)
3 years ago
restartWeb()
return mw.returnJson(True, '设置成功!')
6 years ago
6 years ago
def setSiteObjOpen():
args = getArgs()
data = checkArgs(args, ['siteName', 'obj'])
if not data[0]:
return data[1]
siteName = args['siteName']
obj = args['obj']
path = getJsonPath('site')
content = mw.readFile(path)
6 years ago
content = json.loads(content)
6 years ago
if type(content[siteName][obj]) == bool:
6 years ago
if content[siteName][obj]:
content[siteName][obj] = False
else:
content[siteName][obj] = True
else:
if content[siteName][obj]['open']:
content[siteName][obj]['open'] = False
else:
content[siteName][obj]['open'] = True
cjson = mw.getJson(content)
mw.writeFile(path, cjson)
3 years ago
restartWeb()
return mw.returnJson(True, '设置成功!')
6 years ago
6 years ago
def getWafSrceen():
conf = getJsonPath('total')
return mw.readFile(conf)
6 years ago
6 years ago
def getWafConf():
conf = getJsonPath('config')
return mw.readFile(conf)
6 years ago
6 years ago
def cleanDropIp():
url = "http://127.0.0.1/clean_waf_drop_ip"
data = mw.httpGet(url)
return mw.returnJson(True, 'ok!', data)
def testRun():
# args = getArgs()
# data = checkArgs(args, ['siteName'])
# if not data[0]:
# return data[1]
conf_json = getServerDir() + "/waf/default.json"
data = mw.readFile(conf_json)
pdata = json.loads(data)
default_site = pdata['default']
url = "http://" + default_site + '/?t=../etc/passwd'
returnData = mw.httpGet(url, 10)
return mw.returnJson(True, '测试运行成功!', returnData)
3 years ago
def installPreInspection():
check_op = mw.getServerDir() + "/openresty"
if not os.path.exists(check_op):
return "请先安装OpenResty"
return 'ok'
6 years ago
6 years ago
6 years ago
if __name__ == "__main__":
func = sys.argv[1]
if func == 'status':
4 years ago
print(status())
6 years ago
elif func == 'start':
4 years ago
print(start())
6 years ago
elif func == 'stop':
4 years ago
print(stop())
6 years ago
elif func == 'restart':
4 years ago
print(restart())
6 years ago
elif func == 'reload':
4 years ago
print(reload())
3 years ago
elif func == 'install_pre_inspection':
print(installPreInspection())
6 years ago
elif func == 'conf':
4 years ago
print(getConf())
6 years ago
elif func == 'get_rule':
4 years ago
print(getRule())
6 years ago
elif func == 'add_rule':
4 years ago
print(addRule())
6 years ago
elif func == 'remove_rule':
4 years ago
print(removeRule())
6 years ago
elif func == 'set_rule_state':
4 years ago
print(setRuleState())
6 years ago
elif func == 'modify_rule':
4 years ago
print(modifyRule())
6 years ago
elif func == 'get_site_rule':
4 years ago
print(getSiteRule())
6 years ago
elif func == 'add_site_rule':
4 years ago
print(addSiteRule())
6 years ago
elif func == 'add_ip_white':
4 years ago
print(addIpWhite())
6 years ago
elif func == 'remove_ip_white':
4 years ago
print(removeIpWhite())
6 years ago
elif func == 'add_ip_black':
4 years ago
print(addIpBlack())
6 years ago
elif func == 'remove_ip_black':
4 years ago
print(removeIpBlack())
6 years ago
elif func == 'set_ipv6_black':
4 years ago
print(setIpv6Black())
6 years ago
elif func == 'del_ipv6_black':
4 years ago
print(delIpv6Black())
6 years ago
elif func == 'remove_site_rule':
4 years ago
print(removeSiteRule())
elif func == 'set_obj_status':
4 years ago
print(setObjStatus())
elif func == 'set_obj_open':
4 years ago
print(setObjOpen())
6 years ago
elif func == 'set_site_obj_open':
4 years ago
print(setSiteObjOpen())
6 years ago
elif func == 'set_cc_conf':
4 years ago
print(setCcConf())
6 years ago
elif func == 'set_site_cc_conf':
4 years ago
print(setSiteCcConf())
6 years ago
elif func == 'set_retry':
4 years ago
print(setRetry())
elif func == 'set_safe_verify':
print(setSafeVerify())
6 years ago
elif func == 'set_site_retry':
4 years ago
print(setSiteRetry())
6 years ago
elif func == 'save_scan_rule':
4 years ago
print(saveScanRule())
6 years ago
elif func == 'get_site_config':
4 years ago
print(getSiteConfig())
3 years ago
elif func == 'get_default_site':
print(getDefaultSite())
6 years ago
elif func == 'get_site_config_byname':
4 years ago
print(getSiteConfigByName())
6 years ago
elif func == 'add_site_cdn_header':
4 years ago
print(addSiteCdnHeader())
6 years ago
elif func == 'remove_site_cdn_header':
4 years ago
print(removeSiteCdnHeader())
6 years ago
elif func == 'get_logs_list':
4 years ago
print(getLogsList())
6 years ago
elif func == 'get_safe_logs':
4 years ago
print(getSafeLogs())
6 years ago
elif func == 'output_data':
4 years ago
print(outputData())
6 years ago
elif func == 'import_data':
4 years ago
print(importData())
elif func == 'waf_srceen':
4 years ago
print(getWafSrceen())
6 years ago
elif func == 'waf_conf':
4 years ago
print(getWafConf())
6 years ago
elif func == 'waf_site':
4 years ago
print(getWafSite())
3 years ago
elif func == 'clean_drop_ip':
print(cleanDropIp())
elif func == 'test_run':
print(testRun())
6 years ago
else:
4 years ago
print('error')