#!/usr/bin/python
# coding: utf-8

import os, sys, public
import re

_title = 'Check if nginx configuration files are infected with malware'
_version = 1.0  # 版本
_ps = "Check if nginx configuration files are infected with malware"  # 描述
_level = 3  # 风险级别： 1.提示(低)  2.警告(中)  3.危险(高)
_date = '2023-11-21'  # 最后更新时间
_ignore = os.path.exists("data/warning/ignore/sw_nginx_malware.pl")
_tips = [
    "According to the prompt, find the nginx configuration file, delete the JS malware content, or click the [Fix] button",
    "Restart nginx service"
]
_help = ''
_remind = 'It is recommended to back up the configuration file before manual repair to prevent service failure due to operational errors; or use one-click repair'


def check_run():
    '''
        @name Start detection
        @author lwh<2023-11-21>
        @return tuple (status<bool>,msg<string>)
    '''
    try:
        import glob
        path = '/www/server/panel/vhost/nginx/'
        if not os.path.exists(path):
            return True, 'No risk'
        risk_files = []
        # 检测规则
        malware_patterns = [
            r'(?mi)^\s*(?!#)\s*sub_filter\s+.*<script.*?;'
        ]
        patterns = [re.compile(pattern) for pattern in malware_patterns]

        for filename in glob.glob(os.path.join(path, '*.conf')):
            try:
                if os.path.isdir(filename):
                    continue
                content = public.ReadFile(filename)
                if not content:
                    continue
                # 检查文件大小 10MB
                if len(content) > 10 * 1024 * 1024:
                    continue
                # 检测恶意文件特征
                for pattern in patterns:
                    matches = pattern.findall(content)
                    if matches:
                        risk_files.append({
                            'file': filename,
                            'content': matches[0].strip()
                        })
                        break
                # 原
                # if "sub_filter" in output:
                #     risk_file.append(filename)
            except Exception as e:
                continue
        if risk_files:
            # 生成简单的报告
            report = ["Found {} configuration files with suspicious content:".format(len(risk_files))]

            for i, risk in enumerate(risk_files, 1):
                report.append("{}. File: {} ".format(
                    i,
                    risk['file']
                    # risk['content']
                ))

            return False, '<br />' + ('<br />'.join(report))

        # if len(risk_file) > 0:
        #     return False, '以下nginx文件存在挂马内容：{}'.format('、'.join(risk_file))
        return True, 'No risk'
    except Exception as e:
        return True, 'No risk'


def _get_context(content, match, context_lines=2):
    """Get context of matched content"""
    try:
        lines = content.split('\n')
        for i, line in enumerate(lines):
            if match in line:
                start = max(0, i - context_lines)
                end = min(len(lines), i + context_lines + 1)
                return '\n'.join(lines[start:end])
    except:
        return match
    return match