def admin_cdn_domain_conf(request): """ 修改cdn域名 """ msg = '' status = False res = {'status': status, 'msg': msg} user_id = request.POST.get('user_id', '') domain = request.POST.get('domain', '') provider = request.POST.get('provider', 'CC') # user_id = '93' # domain = 'itestxz0021.chinacache.com' user_id = int_check(user_id) try: domain_obj_list = Domain.objects.filter(domain=domain) if not domain_obj_list: assert False msg = af.DOMAIN_EXIST protocol = CDNConf.HTTP_TYPE for domain_obj in domain_obj_list: if domain_obj.protocol == CDNConf.HTTPS_TYPE: protocol = CDNConf.HTTPS_TYPE break user_id = int_check(user_id) if user_id is None: msg = af.PARAME_ERROR assert False body = { 'user_id': user_id, 'protocol': protocol, 'domain': domain, 'provider': provider } api_res = APIUrl.post_link('cdn_domain_sync_conf', body) return_code = api_res.get('return_code', 0) if return_code != 0: assert False res['domain_conf'] = api_res['domain_conf'] status = True except Exception as e: print(e) res['msg'] = _(msg) res['status'] = status return json_response(res)
def parent_set_defense_mode(request): """父账号自己设置规则防御模式""" msg = '' status = False res = {'status': status, 'msg': msg} provider = 'QINGSONG' domain_id = request.POST.get('domain_id', '') default_waf_mode = request.POST.get('default_waf_mode', '') self_waf_mode = request.POST.get('self_waf_mode', '') try: domain_obj = Domain.objects.filter(id=domain_id).first() if not domain_obj: msg = af.DOMAIN_NOT_EXIST assert False body = { 'channel': '%s://%s' % (domain_obj.protocol, domain_obj.domain), } if default_waf_mode: default_waf_mode = int_check(default_waf_mode) if default_waf_mode is None: msg = af.PARAME_ERROR assert False body['default'] = 1 body['switch'] = default_waf_mode log_msg = om.SET_DEFAULT_RULE_MODE % ( request.user.username, domain_obj.domain, default_waf_mode) elif self_waf_mode: self_waf_mode = int_check(self_waf_mode) if self_waf_mode is None: msg = af.PARAME_ERROR assert False body['default'] = 0 body['switch'] = self_waf_mode log_msg = om.SET_SELF_RULE_MODE % ( request.user.username, domain_obj.domain, self_waf_mode) api_res = APIUrl.post_link('set_defense_mode', body) if api_res[provider]['return_code'] == 0: status = True OperateLog.write_operate_log(request, om.SECURITY, log_msg) except AssertionError: res['msg'] = _(msg) res['status'] = status return json_response(res)
def user_domain_refresh_status(request, user): """用户刷新查询""" start_time = request.POST.get('start_time', 0) end_time = request.POST.get('end_time', 0) url = request.POST.get('url', '') refresh_type = request.POST.get('refresh_type', '') refresh_status = request.POST.get('refresh_status', '') msg = '' result_list = [] pagination = {} try: start_time = int_check(start_time) if start_time is None: msg = af.PARAME_ERROR assert False end_time = int_check(end_time) if end_time is None: msg = af.PARAME_ERROR assert False body = { 'username': user.username, 'start_time': start_time, 'end_time': end_time, 'url': url, 'type': refresh_type, 'status': refresh_status, } api_res = APIUrl.post_link('cdn_domain_refresh_status', body) return_code = api_res.get('return_code', 0) if return_code != 0: assert False result_list = api_res.get('result_list', []) check_msg, result_list, pagination = data_pagination( request, result_list) if check_msg: msg = check_msg assert False except AssertionError: pass return msg, result_list, pagination
def _get_opt_log_list(request, user_type): start_time = request.POST.get('start_time', 0) end_time = request.POST.get('end_time', 0) username = request.POST.get('username', '') size = request.POST.get('size', PAGE_SIZE) page = request.POST.get('page', '1') msg = '' pagination = None try: msg, start_time, end_time = handle_req_time(start_time, end_time) if msg: assert False if start_time and end_time: try: start_time = timestamp_to_datetime(start_time) end_time = timestamp_to_datetime(end_time) except TypeError: msg = af.PARAME_ERROR assert False log_list = OperateLog.get_operator_logs(user_type=user_type, username=username, start_time=start_time, end_time=end_time) size = int_check(size) page = int_check(page) if size is None or page is None or page == 0: msg = af.PARAME_ERROR assert False start = (page - 1) * size end = page * size total = len(log_list) pagination = get_pagination(page, total, size) result_list = log_list[start:end] except AssertionError: result_list = [] return msg, result_list, pagination
def _get_user_list(request, group_ids): """检查获取用户列表参数""" msg = '' username = request.POST.get('username', '').strip() is_active = request.POST.get('is_active', '') check_filter = {} if username: check_filter['username'] = username if group_ids: check_filter['groups__id__in'] = group_ids user_list = UserProfile.objects.filter(**check_filter).order_by('-id') try: if is_active: is_active = int_check(is_active) if is_active is None: msg = af.PARAME_ERROR assert False user_list = user_list.filter(is_active=is_active) except AssertionError: user_list = [] return msg, user_list
def set_user_api_status(request, user): """用户设置api状态""" msg = '' try: api_status = request.POST.get('status', '') api_status = int_check(api_status) if api_status is None: af.PARAME_ERROR assert False body = { 'username': user.username, 'status': api_status } api_res = APIUrl.post_link('set_api_status', body) result = api_res.get('return_code', 0) if result != 0: msg = af.SEND_ERROR assert False except AssertionError: pass return msg
def admin_get_cms_channel_list(request): """管理员获取cms频道""" msg = '' status = False res = { 'status': status, 'msg': msg } cms_username = request.POST.get('cms_username', '') user_id = request.POST.get('user_id', '') try: user_id = int_check(user_id) if user_id is None: assert False msg = af.USER_NOT_EXIST body = { 'user_id_list': [int(user_id)], 'return_type': 'is_list' } api_res = APIUrl.post_link('domain_query', body) domain_query = api_res.get('domain_query', []) url_list = [ '%s://%s' % (i['protocol'], i['domain']) for i in domain_query] cms_channel_list = ChinaCacheAPI.get_channel_by_cms(cms_username) channel_list = [] for i in cms_channel_list: channel_name = i.get('channel_name', '') channel_info = copy.deepcopy(i) has_create = True if channel_name in url_list else False channel_info['has_create'] = has_create channel_list.append(channel_info) channel_list = sorted( channel_list, key=lambda x: urlparse(x['channel_name']).netloc) res['cms_channel_list'] = channel_list status = True except AssertionError: res['msg'] = _(msg) res['status'] = status return json_response(res)
def admin_cdn_flux_data(request): """管理员查看计费统计数据""" msg = '' status = False res = {'status': status, 'msg': msg} start_time = request.POST.get('start_time', 0) end_time = request.POST.get('end_time', 0) user_id = request.POST.get('user_id', '') domain_ids = request.POST.get('domain_list', '[]') opts = request.POST.get('opts', '[]') all_flux_list = [] # 计费图表数据 sum_cdn_flux = 0 # 总计费数据(MB) sum_src_flux = 0 # 总回源数据(MB) max_cdn = 0 # 峰值计费值(M/bps) table_data = [] # 每日表格数据 try: user_id = int_check(user_id) if user_id is None: msg = af.PARAME_ERROR assert False msg, start_time, end_time = handle_req_time(start_time, end_time) if msg: assert False domain_ids = handle_list(domain_ids, dec_int=True) if domain_ids: opts = handle_list(opts) domain_query = Domain.objects.filter(id__in=domain_ids) domain_list = [i.domain for i in domain_query] (all_flux_list, sum_cdn_flux, sum_src_flux, max_cdn, max_src, table_data, opt_result) = get_domain_flux(user_id, domain_list, start_time, end_time, opts) status = True except Exception as e: print(e) res['msg'] = _(msg) res['status'] = status res['domain_flux'] = all_flux_list res['sum_cdn_flux'] = sum_cdn_flux res['sum_src_flux'] = sum_src_flux res['max_cdn'] = max_cdn res['table_data'] = table_data return json_response(res)
def user_enable_self_rule(request): msg = '' status = False res = { 'status': status, 'msg': msg } provider = 'QINGSONG' domain_id = request.POST.get('domain_id', '') rule_id = request.POST.get('rule_id', 0) enable = request.POST.get('enable', 0) try: domain_obj = Domain.objects.filter(id=domain_id).first() if not domain_obj: msg = af.DOMAIN_NOT_EXIST assert False enable = int_check(enable) if enable is None: msg = af.PARAME_ERROR assert False rule_id = int(rule_id) if rule_id is None: msg = af.PARAME_ERROR assert False body = { 'channel': '%s://%s' % (domain_obj.protocol, domain_obj.domain), 'enable': enable, 'rule_id': rule_id } api_res = APIUrl.post_link('enable_self_rule', body) print(api_res) if api_res[provider]['return_code'] == 0: status = True opt_msg = '开启' if enable else '关闭' log_msg = om.ENABLE_SELF_RULE % ( request.user.username, rule_id, opt_msg) OperateLog.write_operate_log(request, om.SECURITY, log_msg) except AssertionError: res['msg'] = _(msg) res['status'] = status return json_response(res)
def edit_admin_user(request): """修改管理员账号用户""" msg = '' status = False res = {'status': status, 'msg': msg} username = request.POST.get('username', '') group_id = request.POST.get('group_id', '') is_active = request.POST.get('is_active', '') try: if not username: msg = af.USERNAME_EMPTY assert False check_user = UserProfile.objects.filter(username=username).first() if not check_user: msg = af.USER_NOT_EXIST assert False if is_active: is_active = int_check(is_active) if is_active is None: msg = af.PARAME_ERROR assert False check_user.is_active = True if is_active else False if group_id: group = Group.objects.filter(id=group_id).first() if not group: msg = af.GROUP_EMPTY assert False check_user.groups.clear() check_user.groups.add(group) check_user.save() except AssertionError: res['msg'] = _(msg) return json_response(res) creator_username = request.user.username log_msg = om.EDIT_USER % (creator_username, username) OperateLog.write_operate_log(request, om.ACCOUNTS, log_msg) status = True res['status'] = status return json_response(res)
def admin_domain_set_waf(request): """管理员启用waf""" msg = '' status = False res = { 'status': status, 'msg': msg } provider = 'QINGSONG' domain_id = request.POST.get('domain_id', '') switch = request.POST.get('switch', '') try: domain_obj = Domain.objects.filter(id=domain_id).first() if not domain_obj: msg = af.DOMAIN_NOT_EXIST assert False domain = domain_obj.domain switch = int_check(switch) if switch is None: msg = af.PARAME_ERROR assert False body = { 'channel': '%s://%s' % (domain_obj.protocol, domain), "switch": switch } api_res = APIUrl.post_link('domain_waf_opt_waf', body) message = api_res[provider].get('message', 'success') msg = '' if message == 'success' else message if api_res[provider]['return_code'] == 0: status = True switch_name = '开启' if switch else '关闭' log_msg = om.SET_WAF_STATUS % ( request.user.username, domain, switch_name) OperateLog.write_operate_log( request, om.SECURITY, log_msg) except Exception as e: print(traceback.format_exc()) res['msg'] = _(msg) res['msg'] = msg res['status'] = status return json_response(res)
def admin_get_domain_list(request): """管理员获取列表""" msg = '' status = False res = {'status': status, 'msg': msg} user = request.user domain = request.POST.get('domain', '') user_id = request.POST.get('user_id', '') cdn_type = request.POST.get('cdn_type', '') domain_status = request.POST.get('domain_status', '[]') domain_query = Domain.get_domain_query_by_user(user) try: domain_status = handle_list(domain_status, dec_int=True) if user_id: user_id = int_check(user_id) if user_id is None: msg = af.PARAM_ERROR assert False domain_query = domain_query.filter(user__id=user_id) if domain: domain_query = domain_query.filter(domain=domain) domain_query = domain_query.order_by('-protocol') check_msg, domain_dict_list, pagination = get_domain_list( request, domain_query, cdn_type, domain_status) if check_msg: res['msg'] = check_msg return json_response(res) res['domain_list'] = domain_dict_list res['page_info'] = pagination status = True except AssertionError: res['msg'] = msg return json_response(res) res['status'] = status return json_response(res)
def admin_cdn_domain_active(request): """管理员域名激活""" msg = '' status = False res = {'status': status, 'msg': msg} user = request.user user_id = request.POST.get('user_id', '') domain_list = request.POST.get('domain', '[]') # user_id = 93 # domain = '[itestxz0018.chinacache.com]' domain_list = json.loads(domain_list) try: user_id = int_check(user_id) if user_id is None: msg = af.PARAME_ERROR assert False edit_user = UserProfile.objects.filter(id=user_id).first() body = { 'domain': domain_list, 'user_id': user_id, } api_res = APIUrl.post_link('cdn_domain_active', body) assert api_res return_code = api_res.get('return_code', 0) if return_code != 0: assert False status = True domain_str = ','.join(domain_list) log_msg = om.ACTIVE_CDN_DOMAIN % (user.username, edit_user.username, domain_str) OperateLog.write_operate_log(request, om.ACCOUNTS, log_msg) except Exception as e: print(e) res['msg'] = _(msg) res['status'] = status return json_response(res)
def user_get_log_detail(request): """父账号查看日志详情""" msg = '' status = False res = { 'status': status, 'msg': msg } provider = 'QINGSONG' domain_id = request.POST.get('domain_id', '') log_id = request.POST.get('log_id', 0) log_time = request.POST.get('log_time', '') try: domain_obj = Domain.objects.filter(id=domain_id).first() if not domain_obj: msg = af.DOMAIN_NOT_EXIST assert False log_id = int_check(log_id) if log_id is None: msg = af.PARAME_ERROR assert False body = { 'channel': '%s://%s' % (domain_obj.protocol, domain_obj.domain), 'log_id': log_id, 'log_time': log_time } api_res = APIUrl.post_link('waf_log_detail', body) if api_res[provider]['return_code'] == 0: api_res = api_res[provider] status = True detail_data = api_res.get('data', {}) res['detail_data'] = detail_data except AssertionError: res['msg'] = _(msg) res['status'] = status return json_response(res)
def client_cdn_get_cert(request): """客户端获取证书列表""" msg = '' status = False res = {'status': status, 'msg': msg} user_id = request.POST.get('user_id', '') # user_id = 93 try: user_id = int_check(user_id) if user_id is None: msg = af.PARAME_ERROR assert False body = {'user_id': user_id, 'status': [CertConf.CERT_SUCCESS]} api_res = APIUrl.post_link('ssl_cert_query', body) return_code = api_res.get('return_code', 0) if return_code != 0: assert False cert_list = api_res.get('cert_list', []) result_list = [] for i in cert_list: cert_dict = { 'create_time': i.get('create_time', ''), 'cert_name': i.get('cert_name', ''), 'issued_to': i.get('issued_to', '') } result_list.append(cert_dict) result_list = sorted(result_list, key=lambda x: x['create_time'], reverse=True) res['cert_list'] = result_list status = True except Exception as e: print(e) res['msg'] = _(msg) res['status'] = status return json_response(res)
def admin_cdn_request_data(request): """管理员查看请求量统计数据""" msg = '' status = False res = {'status': status, 'msg': msg} start_time = request.POST.get('start_time', 0) end_time = request.POST.get('end_time', 0) user_id = request.POST.get('user_id', '') domain_ids = request.POST.get('domain_list', '[]') opts = request.POST.get('opts', '[]') request_ratio = 0 # 请求命中率(%) try: user_id = int_check(user_id) if user_id is None: msg = af.PARAME_ERROR assert False msg, start_time, end_time = handle_req_time(start_time, end_time) if msg: assert False domain_ids = handle_list(domain_ids, dec_int=True) if domain_ids: opts = handle_list(opts) domain_query = Domain.objects.filter(id__in=domain_ids) domain_list = [i.domain for i in domain_query] request_ratio = get_domain_request(user_id, domain_list, start_time, end_time, opts) status = True except Exception as e: print(e) res['msg'] = _(msg) res['status'] = status res['request_ratio'] = request_ratio return json_response(res)
def user_reset_default_rule(request): msg = '' status = False res = { 'status': status, 'msg': msg } provider = 'QINGSONG' domain_id = request.POST.get('domain_id', '') enable = request.POST.get('enable', 0) try: domain_obj = Domain.objects.filter(id=domain_id).first() if not domain_obj: msg = af.DOMAIN_NOT_EXIST assert False body = { 'channel': '%s://%s' % (domain_obj.protocol, domain_obj.domain), } enable = int_check(enable) if enable is None: msg = af.PARAME_ERROR assert False body['enable'] = enable api_res = APIUrl.post_link('reset_default_rule', body) if api_res[provider]['return_code'] == 0: status = True opt_msg = '全部开启' if enable else '全部关闭' log_msg = om.RESET_DEFAULT_RULE % ( request.user.username, domain_obj.domain, opt_msg) OperateLog.write_operate_log(request, om.SECURITY, log_msg) except AssertionError: res['msg'] = _(msg) res['status'] = status return json_response(res)
def admin_cert_delete(request): """证书删除""" msg = '' status = False res = {'status': status, 'msg': msg} cert_name = request.POST.get('cert_name', '') user_id = request.POST.get('user_id', '') # print(1111111, request.POST) # cert_name = 'xz_test_0009' # user_id = 93 try: if user_id: user_id = int_check(user_id) if user_id is None: msg = af.PARAME_ERROR assert False body = {'cert_name': cert_name, 'user_id': user_id} api_res = APIUrl.post_link('ssl_cert_delete', body) assert api_res return_code = api_res.get('return_code', 0) if return_code != 0: msg = api_res.get('err_msg', '') assert False status = True except Exception as e: print(e) res['msg'] = _(msg) res['status'] = status return json_response(res)
def get_user_perm_strategy_list(request): """获取用户权限列表""" name = request.POST.get('name', '') strategy_type = request.POST.get('strategy_type', '') perm_strategy_list = PermStrategy.objects.filter( Q(creator_username=request.user.username) | Q(strategy_type=PermStrategy.SYSTEM_NUM)) if name: perm_strategy_list = PermStrategy.objects.filter(name=name) msg = '' perm_strategy_dict_list = [] try: if strategy_type: strategy_type = int_check(strategy_type) if strategy_type is None: msg = af.PARAME_ERROR assert False perm_strategy_list = perm_strategy_list.filter( strategy_type=strategy_type) for i in perm_strategy_list: strategy_dict = { 'id': i.id, 'name': i.name, 'strategy_type_name': i.strategy_type_name, 'remark': i.remark } perm_strategy_dict_list.append(strategy_dict) except AssertionError: pass return msg, perm_strategy_dict_list
def edit_child_user(request): """修改子账号""" msg = '' status = False res = { 'status': status, 'msg': msg } obj_id = request.POST.get('obj_id', 0) password = request.POST.get('password', '') is_api = request.POST.get('is_api', '') reset_password = request.POST.get('reset_password', '') email = request.POST.get('email', '') mobile = request.POST.get('mobile', '') remark = request.POST.get('remark', '') is_active = request.POST.get('is_active', '') perm_strategy_ids = request.POST.getlist('perm_strategy[]', '') try: check_user = UserProfile.objects.filter(id=obj_id).first() if not check_user: msg = af.USER_NOT_EXIST assert False if is_api: is_api = int_check(is_api) if is_api is None: msg = af.PARAM_ERROR assert False # TODO 通信api 实现key的删除 if reset_password: reset_password = int_check(reset_password) if reset_password is None: msg = af.PARAM_ERROR assert False check_user.reset_password = True if reset_password else False if is_active: is_active = int_check(is_active) if is_api is None: msg = af.PARAM_ERROR assert False check_user.is_active = True if is_active else False except AssertionError: res['msg'] = _(msg) return json_response(res) if email: check_user.email = email if mobile: check_user.mobile = mobile if remark: check_user.remark = remark if password: check_user.set_password(password) check_user.save() if perm_strategy_ids: user_perm = UserPermStrategy.objects.filter(user=check_user).first() user_perm.perm_strategy.clear() UserPermStrategy.assign_perm(perm_strategy_ids, check_user) log_msg = om.EDIT_USER % (request.user.username, check_user.username) OperateLog.write_operate_log(request, om.ACCOUNTS, log_msg) status = True res['status'] = status return json_response(res)
def create_child_user(request): """创建子账号号用户""" msg = '' status = False res = { 'status': status, 'msg': msg } username = request.POST.get('username', '') password = request.POST.get('password', '') is_api = request.POST.get('is_api', 0) reset_password = request.POST.get('reset_password', 0) email = request.POST.get('email', '') mobile = request.POST.get('mobile', '') remark = request.POST.get('remark', '') perm_strategy_ids = request.POST.getlist('perm_strategy[]', '') try: if not username: msg = af.USERNAME_EMPTY assert False check_user = UserProfile.objects.filter(username=username) if check_user: msg = af.USER_EXIST assert False if not password: msg = af.PASSWORD_EMPTY assert False is_api = int_check(is_api) if is_api is None: msg = af.PARAM_ERROR assert False reset_password = int_check(reset_password) if reset_password is None: msg = af.PARAM_ERROR assert False except AssertionError: res['msg'] = _(msg) return json_response(res) if is_api: print('给api通信') identity = 'is_child' group = Group.objects.filter(id=GroupProfile.CUSTOMER_CHILD_ID).first() creator_username = request.user.username param = { 'username': username, 'password': password, 'group': group, 'identity': identity, 'email': email, 'mobile': mobile, 'remark': remark, 'reset_password': True if reset_password else False, 'creator_username': creator_username } user = create_user(**param) if not user: res['msg'] = _(af.PARAM_ERROR) return json_response(res) UserPermStrategy.assign_perm(perm_strategy_ids, user) log_msg = om.CREATE_USER % (creator_username, identity, username) OperateLog.write_operate_log(request, om.ACCOUNTS, log_msg) status = True res['status'] = status return json_response(res)
def user_download_ip_list(request, domain_id, start_time, end_time): """父账号下载拦截攻击来源""" msg = '' status = False is_en = False if request.LANGUAGE_CODE == 'en': is_en = True res = { 'status': status, 'msg': msg } provider = 'QINGSONG' try: start_time = int_check(start_time) if start_time is None: msg = af.PARAME_ERROR assert False end_time = int_check(end_time) if end_time is None: msg = af.PARAME_ERROR assert False start_time = timestamp_to_str(start_time, _format='%Y-%m-%d') end_time = timestamp_to_str(end_time, _format='%Y-%m-%d') domain_obj = Domain.objects.filter(id=domain_id).first() if not domain_obj: msg = af.DOMAIN_NOT_EXIST assert False channel = '%s://%s' % (domain_obj.protocol, domain_obj.domain) body = { 'channel': channel, 'start_day': start_time, 'end_day': end_time, } api_res = APIUrl.post_link('waf_defense_statistics', body) excel_name = '%s-ip_list.xls' % domain_obj.domain if api_res[provider]['return_code'] == 0: api_res = api_res[provider] detail_data = api_res.get('data', {}) ip_list = detail_data.get('ip_list', []) sheet_name = 'ip-list' row, excel_path, worksheet, workbook = make_base_excel( excel_name, sheet_name, channel, start_time, end_time) row += 3 worksheet.write(row, 0, label='ip_address') worksheet.write(row, 1, label='count') for v in ip_list: row += 1 ip = v.get('ip', '') ip_address = v.get('ip_address', '') if is_en: if ip_address in COUNTRY_NAME_CONF: ip_address = COUNTRY_NAME_CONF[ip_address] else: ip_address = 'Unknown' cnt = v.get('cnt', '') worksheet.write(row, 0, label=ip) worksheet.write(row, 1, label=ip_address) worksheet.write(row, 2, label=cnt) workbook.save(excel_path) except AssertionError: excel_name = 'error_documents' excel_path = make_error_file(excel_name, _(msg)) response = StreamingHttpResponse(file_iterator(excel_path)) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="{0}"'.format( excel_name) return response
def user_download_time_cnt(request, domain_id, start_time, end_time): """父账号下载拦截攻击次数excel""" msg = '' status = False res = { 'status': status, 'msg': msg } provider = 'QINGSONG' domain_obj = Domain.objects.filter(id=domain_id).first() try: if not domain_obj: msg = af.DOMAIN_NOT_EXIST assert False excel_name = '%s-time_cut.xls' % domain_obj.domain start_time = int_check(start_time) if start_time is None: msg = af.PARAME_ERROR assert False end_time = int_check(end_time) if end_time is None: msg = af.PARAME_ERROR assert False start_time = timestamp_to_str(start_time, _format='%Y-%m-%d') end_time = timestamp_to_str(end_time, _format='%Y-%m-%d') channel = '%s://%s' % (domain_obj.protocol, domain_obj.domain) body = { 'channel': channel, 'start_day': start_time, 'end_day': end_time, } api_res = APIUrl.post_link('waf_defense_statistics', body) if api_res[provider]['return_code'] == 0: api_res = api_res[provider] sheet_name = 'time-cut' row, excel_path, worksheet, workbook = make_base_excel( excel_name, sheet_name, channel, start_time, end_time) detail_data = api_res.get('data', {}) time_cnt_data = detail_data.get('time_cnt', []) row += 3 worksheet.write(row, 0, label='time') worksheet.write(row, 1, label='count') time_str_list = list(time_cnt_data.keys()) time_str_list.sort() for time_key in time_str_list: data_list = time_cnt_data[time_key] day_str = '%s-%s-%s' % ( time_key[:4], time_key[4:6], time_key[6:8]) for v in data_list: row += 1 cnt = v.get('cnt', 0) name = int(v.get('name')) name = '0%s' % name if name < 10 else str(name) start = '%s:00' % name end = '%s:59' % name time_str = '%s %s - %s %s' % (day_str, start, day_str, end) worksheet.write(row, 0, label=time_str) worksheet.write(row, 1, label=cnt) workbook.save(excel_path) except AssertionError: excel_name = 'error_documents' excel_path = make_error_file(excel_name, _(msg)) response = StreamingHttpResponse(file_iterator(excel_path)) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="{0}"'.format( excel_name) return response
def user_download_log(request, domain_id, atk_ip, start_time, end_time, log_rows): """父账号下载日志 {'action': 'waf_report', 'message': 'success', 'data': {'cur_page': 70, 'log_rows': 1381, 'waf_log': [], 'page_cnt': 70}, 'return_code': 0} """ msg = '' status = False page_size = 2000 log_list = [] is_en = False if request.LANGUAGE_CODE == 'en': is_en = True provider = 'QINGSONG' try: log_rows = int_check(log_rows) if log_rows is None: msg = af.PARAME_ERROR assert False page_count = log_rows // page_size domain_id = int(domain_id) domain_obj = Domain.objects.filter(id=domain_id).first() if not domain_obj: msg = af.DOMAIN_NOT_EXIST assert False channel = '%s://%s' % (domain_obj.protocol, domain_obj.domain) body = { 'channel': channel, } if start_time and end_time: start_time = int_check(start_time) if start_time is None: msg = af.PARAME_ERROR assert False end_time = int_check(end_time) if end_time is None: msg = af.PARAME_ERROR assert False base_format = '%Y-%m-%d %H:%M' start_time = timestamp_to_str(start_time, _format=base_format) end_time = timestamp_to_str(end_time, _format=base_format) body['start_time'] = start_time body['end_time'] = end_time if atk_ip != '-': body['atk_ip'] = atk_ip body_list = [] for count in range(0, page_count+1): body['page'] = count body['page_size'] = page_size body_list.append(deepcopy(body)) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) p0 = time.time() r = loop.run_until_complete(asyncio.wait([APIUrl.doPostAio('waf_log_list', b) for b in body_list])) p1 = time.time() print(f'user_download_log[len: {len(body_list)}.] takeTime: {p1-p0}') results = r[0] n = 0 for i in results: try: result = json.loads(i.result()) data = result.get(provider).get('data') if result.get(provider).get('return_code') == 0: log_list.extend(data['waf_log']) print(f'user_download_log[No.{n}] cur_page: {data["cur_page"]}|| log_rows: {data["log_rows"]}') except json.decoder.JSONDecodeError: print(f'user_download_log[jsonError.] error: {i.result()}|| info: {r[1]}|| traceback: {traceback.format_exc()}') # api_res = APIUrl.post_link('waf_log_list', body) # if api_res[provider]['return_code'] == 0: # api_res = api_res[provider] # waf_log = api_res.get('data', {}).get('waf_log', []) # log_list.extend(waf_log) n += 1 loop.close() # api_res = APIUrl.post_link('waf_log_list', body) # if api_res[provider]['return_code'] == 0: # api_res = api_res[provider] # waf_log = api_res.get('data', {}).get('waf_log', []) # log_list.extend(waf_log) # ---origins as below # for count in range(0, page_count+1): # body['page'] = count # body['page_size'] = page_size # api_res = APIUrl.post_link('waf_log_list', body) # if api_res[provider]['return_code'] == 0: # api_res = api_res[provider] # waf_log = api_res.get('data', {}).get('waf_log', []) # log_list.extend(waf_log) # excel_name = '%s-log.xlsx' % domain_obj.domain # sheet_name = 'log_data' # row, excel_path, worksheet, workbook = make_base_excel(excel_name, sheet_name, channel, start_time, end_time) csv_rows = [['waf_channel:', channel], ['start_time:', start_time], ['end_time:', end_time], [], []] csv_header = ['log_time', 'atk_ip', 'tar_url', 'atk_url', 'rule_id'] csv_rows.append(csv_header) csv_name = '%s-log.csv' % domain_obj.domain for v in log_list: log_time = v.get('log_time', '') atk_ip = v.get('atk_ip', '') target_url = v.get('target_url', '') # target_url = unquote(target_url) atk_type = v.get('atk_type', '') # if not is_en: # # atk_type = WAF_ATTACK_TYPE[atk_type].encode('utf-8').decode('gb18030') # atk_type = WAF_ATTACK_TYPE[atk_type] # # try: # # atk_type = WAF_ATTACK_TYPE[atk_type].encode('utf-8').decode('GB2312') # # except UnicodeDecodeError: # # print(f'\n---atk_type(Error.)---\n{atk_type}') # # atk_type = WAF_ATTACK_TYPE[atk_type] rule_id = v.get('ruleid', '') csv_rows.append([log_time, atk_ip, target_url, atk_type, rule_id]) csv_path = make_base_csv(csv_name, csv_rows) # print(f'\n---"Done."---\n{"Done."}') # assert False # row += 3 # worksheet.write(row, 0, label='log_time') # worksheet.write(row, 1, label='atk_ip') # worksheet.write(row, 2, label='tar_url') # worksheet.write(row, 3, label='atk_type') # worksheet.write(row, 4, label='rule_id') # base_rote = 40 # for v in log_list: # row += 1 # log_time = v.get('log_time', '') # atk_ip = v.get('atk_ip', '') # target_url = v.get('target_url', '') # target_url = unquote(target_url) # atk_type = v.get('atk_type', '') # if not is_en: # atk_type = WAF_ATTACK_TYPE[atk_type] # rule_id = v.get('ruleid', '') # if len(target_url) > base_rote: # first_col = worksheet.col(2) # first_col.width = 100 * len(target_url) if 100 * len(target_url) < 65536 else 60000 # base_rote = len(target_url) # worksheet.write(row, 0, label=log_time) # worksheet.write(row, 1, label=atk_ip) # worksheet.write(row, 2, label=target_url) # worksheet.write(row, 3, label=atk_type) # worksheet.write(row, 4, label=rule_id) # workbook.save(excel_path) except AssertionError: csv_name = 'error_documents' csv_path = make_error_file(csv_name, _(msg)) # response = StreamingHttpResponse(file_iterator(csv_path)) try: response = FileResponse(open(csv_path, 'rb')) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = f'attachment;filename="{csv_name}"' os.remove(csv_path) print(f'user_download_log[FileDeleteDone.] csv_path: {csv_path}') return response except Exception: print(f'user_download_log[Error.] error: {traceback.format_exc()}') raise Http404
def admin_create_parent_user(request): """创建父账号用户""" msg = '' status = False res = {'status': status, 'msg': msg} username = request.POST.get('username', '') password = request.POST.get('password', '') company = request.POST.get('company', '') linkman = request.POST.get('linkman', '') email = request.POST.get('email', '') mobile = request.POST.get('mobile', '') is_api = request.POST.get('is_api', '') is_active = request.POST.get('is_active', '1') perm_list = request.POST.getlist('perm[]', []) try: if not username: msg = af.USERNAME_EMPTY assert False check_user = UserProfile.objects.filter(username=username) if check_user: msg = af.USER_EXIST assert False if not password: msg = af.PASSWORD_EMPTY assert False if not company: msg = af.COMPANY_EMPTY assert False is_api = int(is_api) if is_api is None: msg = af.PARAM_ERROR assert False is_active = int_check(is_active) if is_active is None: msg = af.PARAM_ERROR assert False except AssertionError: res['msg'] = _(msg) return json_response(res) identity = 'is_parent' group = Group.objects.filter(id=GroupProfile.CUSTOMER_ID).first() creator_username = request.user.username param = { 'username': username, 'password': password, 'group': group, 'identity': identity, 'company': company, 'linkman': linkman, 'email': email, 'mobile': mobile, 'creator_username': creator_username, 'is_api': True if is_api else False } user = create_user(**param) if not user: res['msg'] = _(af.PARAM_ERROR) return json_response(res) if not is_active: user.is_active = False user.save() for perm_code in perm_list: PermUser.assign_perm(perm_code, user) if perm_code == 'client_cdn_menu': cdn_product = Product.objects.filter(code='CDN').first() cdn_strategy = Strategy.get_obj_from_property('CC', 'CDN', 'CDN') user.product_list.add(cdn_product) user.strategy_list.add(cdn_strategy) user.save() # elif perm_code == 'client_security_menu': # sec_product = Product.objects.filter(code='SECURITY').first() # sec_strategy = Strategy.get_obj_from_property( # 'QINGSONG', 'SECURITY', 'WAF') # user.product_list.add(sec_product) # user.strategy_list.add(sec_strategy) # user.save() log_msg = om.CREATE_USER % (creator_username, identity, username) OperateLog.write_operate_log(request, om.ACCOUNTS, log_msg) status = True res['status'] = status return json_response(res)
def user_get_waf_default_rule(request): msg = '' status = False res = { 'status': status, 'msg': msg } provider = 'QINGSONG' domain_id = request.POST.get('domain_id', '') check_rule_id = request.POST.get('rule_id', '') check_rule_info = request.POST.get('rule_info', '') check_rule_status = request.POST.get('rule_status', '') is_en = False if request.LANGUAGE_CODE == 'en': is_en = True rule_list = [] try: check_rule_info = check_rule_info.lower() if check_rule_id: check_rule_id = int_check(check_rule_id) if check_rule_id is None: msg = af.PARAME_ERROR assert False domain_obj = Domain.objects.filter(id=domain_id).first() if not domain_obj: msg = af.DOMAIN_NOT_EXIST assert False body = { 'channel': '%s://%s' % (domain_obj.protocol, domain_obj.domain) } api_res = APIUrl.post_link('get_waf_default_rule', body) if api_res[provider]['return_code'] == 0: api_res = api_res[provider] rule_dict_list = api_res.get('data', []) for i in rule_dict_list: rule_id = int(i.get('rule_id', '')) if is_en: temp_str = i['rule_info'].replace('\n', '').replace(' ', '') i['rule_info'] = DEFAULT_RULE_CONF[ temp_str] if temp_str in DEFAULT_RULE_CONF else temp_str rule_info = i.get('rule_info', '') rule_info = rule_info.lower() rule_status = str(i.get('rule_status', '0')) if check_rule_id and check_rule_id != rule_id: continue if check_rule_info and check_rule_info not in rule_info: continue if check_rule_status and rule_status != check_rule_status: continue rule_list.append(i) status = True except AssertionError: res['msg'] = _(msg) res['rule_list'] = rule_list res['status'] = status return json_response(res)
def user_get_log_list(request): """父账号自己查看日志""" msg = '' status = False res = { 'status': status, 'msg': msg } is_en = False if request.LANGUAGE_CODE == 'en': is_en = True provider = 'QINGSONG' domain_id = request.POST.get('domain_id', '') atk_ip = request.POST.get('atk_ip', '') start_time = request.POST.get('start_time', 0) end_time = request.POST.get('end_time', 0) page = request.POST.get('page', 1) page_size = request.POST.get('size', 20) try: page = int_check(page) if page is None: msg = af.PARAME_ERROR assert False page = page - 1 if page < 0: msg = af.PARAME_ERROR assert False domain_obj = Domain.objects.filter(id=domain_id).first() if not domain_obj: msg = af.DOMAIN_NOT_EXIST assert False body = { 'channel': '%s://%s' % (domain_obj.protocol, domain_obj.domain), 'start_time': start_time if start_time else None, 'end_time': end_time if end_time else None, 'atk_ip': atk_ip if atk_ip else None, 'page': page, 'page_size': page_size } api_res = APIUrl.post_link('waf_log_list', body) if api_res[provider]['return_code'] == 0: api_res = api_res[provider] status = True log_data = api_res.get('data', {}) page_count = log_data.get('cur_page', 0) page_count += 1 total = log_data.get('log_rows', 0) page_nums = log_data.get('page_cnt', 0) pagination = { 'page_count': page_count, 'page_nums': page_nums, 'total': total } waf_log = log_data.get('waf_log', []) new_log_list = [] for i in waf_log: atk_type = i.get('atk_type', '') if not is_en: atk_type = WAF_ATTACK_TYPE[atk_type] i['atk_type'] = atk_type new_log_list.append(i) res['log_list'] = new_log_list res['page_info'] = pagination res['log_rows'] = log_data.get('log_rows', []) except AssertionError: res['msg'] = _(msg) res['status'] = status return json_response(res)
def admin_edit_parent_user(request): """修改父账号用户""" msg = '' status = False res = {'status': status, 'msg': msg} username = request.POST.get('username', '') company = request.POST.get('company', '') user_type = request.POST.get('user_type', '') linkman = request.POST.get('linkman', '') email = request.POST.get('email', '') mobile = request.POST.get('mobile', '') is_active = request.POST.get('is_active', '') password = request.POST.get('password', '') reset_password = request.POST.get('reset_password', '0') perm_list = request.POST.getlist('perm[]', []) try: check_user = UserProfile.objects.filter(username=username).first() if not check_user: msg = af.USER_NOT_EXIST assert False if is_active: is_active = int_check(is_active) if is_active is None: msg = af.PARAME_ERROR assert False check_user.is_active = True if is_active else False if password: check_user.set_password(password) if reset_password: reset_password = int_check(reset_password) check_user.reset_password = True if reset_password else False except AssertionError: res['msg'] = _(msg) return json_response(res) creator_username = request.user.username if company: check_user.company = company if user_type == 'is_parent': check_user.is_parent = True check_user.is_agent = False if user_type == 'is_agent': check_user.is_parent = False check_user.is_agent = True if linkman: check_user.linkman = linkman if email: check_user.email = email if mobile: check_user.mobile = mobile user_perm, is_new = PermUser.objects.get_or_create(user=check_user) if is_new: user_perm.save() user_perm.perm.clear() # check_user.product_list.clear() # check_user.strategy_list.clear() for perm_code in perm_list: PermUser.assign_perm(perm_code, check_user) if perm_code == 'client_cdn_menu': cdn_product = Product.objects.filter(code='CDN').first() cdn_strategy = Strategy.get_obj_from_property('CC', 'CDN', 'CDN') check_user.product_list.add(cdn_product) check_user.strategy_list.add(cdn_strategy) check_user.save() # elif perm_code == 'client_security_menu': # sec_product = Product.objects.filter(code='SECURITY').first() # sec_strategy = Strategy.get_obj_from_property( # 'QINGSONG', 'SECURITY', 'WAF') # check_user.product_list.add(sec_product) # check_user.strategy_list.add(sec_strategy) # check_user.save() check_user.save() log_msg = om.EDIT_USER % (creator_username, username) OperateLog.write_operate_log(request, om.ACCOUNTS, log_msg) status = True res['status'] = status return json_response(res)
def user_download_rule_list(request, domain_id, start_time, end_time): """父账号下载攻击方式""" msg = '' status = False res = { 'status': status, 'msg': msg } provider = 'QINGSONG' try: start_time = int_check(start_time) if start_time is None: msg = af.PARAME_ERROR assert False end_time = int_check(end_time) if end_time is None: msg = af.PARAME_ERROR assert False start_time = timestamp_to_str(start_time, _format='%Y-%m-%d') end_time = timestamp_to_str(end_time, _format='%Y-%m-%d') domain_obj = Domain.objects.filter(id=domain_id).first() if not domain_obj: msg = af.DOMAIN_NOT_EXIST assert False channel = '%s://%s' % (domain_obj.protocol, domain_obj.domain) body = { 'channel': channel, 'start_day': start_time, 'end_day': end_time, } api_res = APIUrl.post_link('waf_defense_statistics', body) excel_name = '%s-rule_list.xls' % domain_obj.domain if api_res[provider]['return_code'] == 0: api_res = api_res[provider] detail_data = api_res.get('data', {}) sheet_name = 'rule-list' url_list = detail_data.get('url_list', []) row, excel_path, worksheet, workbook = make_base_excel( excel_name, sheet_name, channel, start_time, end_time) row += 3 worksheet.write(row, 0, label='type') worksheet.write(row, 1, label='count') worksheet.write(row, 2, label='proportion(%)') rule_list = detail_data.get('rule_list', []) for v in rule_list: row += 1 name = v.get('name', '') cnt = v.get('cnt', '') pro = v.get('pro', '') worksheet.write(row, 0, label=name) worksheet.write(row, 1, label=cnt) worksheet.write(row, 2, label=pro) row += 5 worksheet.write(row, 0, label='url') worksheet.write(row, 1, label='count') base_rote = 40 for v in url_list: row += 1 site_url = v.get('site_url', '') site_url = unquote(site_url) if len(site_url) > base_rote: first_col = worksheet.col(0) first_col.width = 256 * len(site_url) base_rote = len(site_url) cnt = v.get('cnt', '') worksheet.write(row, 0, label=site_url) worksheet.write(row, 1, label=cnt) workbook.save(excel_path) except AssertionError: excel_name = 'error_documents' excel_path = make_error_file(excel_name, _(msg)) response = StreamingHttpResponse(file_iterator(excel_path)) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="{0}"'.format( excel_name) return response
def client_cert_create_or_edit(request): """客户端证书上传与修改""" msg = '' status = False res = { 'status': status, 'msg': msg } user = request.user cert_name = request.POST.get('cert_name', '') remark = request.POST.get('remark', '') email = request.POST.get('email', '') cert_from = request.POST.get('cert_from', 0) period = request.POST.get('period', 0) is_update = request.POST.get('is_update', 0) key = request.POST.get('csrfmiddlewaretoken', '')[:16] vi = request.POST.get('csrfmiddlewaretoken', '')[-16:] cert_value = request.POST.get('cert_value', '') dec_cert_value = decrypt_to(cert_value, key, vi) cert_pl = request.POST.get('cert_pl', '0') key_value = request.POST.get('key_value', '') dec_key_value = decrypt_to(key_value, key, vi) key_pl = request.POST.get('key_pl', '0') # cert_name = 'xz_test_0009' # username = '******' # remark = '备注备注' # email = '*****@*****.**' # cert_value = '--------字符串省略' # key_value = '--------字符串省略' # cert_from = 0 # period = 0 # is_update = 0 try: if not cert_name: msg = af.CERT_NAME_EMPTY assert False if not email: msg = af.CERT_EMAIL_EMPTY assert False if period: period = int_check(period) if period is None: msg = af.PARAME_ERROR assert False if cert_from: cert_from = int_check(cert_from) if cert_from is None: msg = af.PARAME_ERROR assert False if is_update: is_update = int_check(is_update) if is_update is None: msg = af.PARAME_ERROR assert False if not cert_value or not cert_value: msg = af.CERT_VALUE_OR_KEY_EMPTY assert False cert_pl = int_check(cert_pl) if cert_pl is None: msg = af.PARAME_ERROR assert False key_pl = int_check(key_pl) if key_pl is None: msg = af.PARAME_ERROR assert False cert_value = dec_cert_value[:cert_pl] key_value = dec_key_value[:key_pl] body = { 'cert_name': cert_name, 'username': user.username, 'remark': remark, 'email': email, 'cert_value': cert_value, 'key_value': key_value, 'cert_from': cert_from, 'period': period, 'is_update': is_update, 'opt_username': request.user.username } print(11111111111, body) api_res = APIUrl.post_link('ssl_cert_create_or_edit', body) return_code = api_res.get('return_code', 0) print(2222222222, api_res) if return_code != 0: res['msg'] = api_res.get('err_msg', '') assert False status = True except Exception as e: print(e) res['msg'] = _(msg) res['status'] = status return json_response(res)