<commit_before># -*- coding: utf-8 -*-
'''
BurpExtender
~~~~~~~~~~~~

BurpExtender is a proxied class that implements the burp.IBurpExtender
interface. It is what makes Jython <-> Burp possible.
'''
from java.io import File
from java.lang import AbstractMethodError, System
from org.python.util import JLineConsole, PythonInterpreter
from burp import IBurpExtender, IMenuItemHandler

from threading import Thread
import inspect
import json
import logging
import os
import re
import signal
import site
import sys
import weakref

from gds.burp import HttpRequest
from gds.burp.config import Configuration, ConfigSection
from gds.burp.core import Component, ComponentManager
from gds.burp.decorators import callback
from gds.burp.dispatchers import NewScanIssueDispatcher, PluginDispatcher
from gds.burp.monitor import PluginMonitorThread

import gds.burp.settings as settings


logging._srcfile = None
logging.logThreads = 0
logging.logProcesses = 0


class BurpExtender(IBurpExtender, ComponentManager):

    _components = ConfigSection('components', '')
    _menus = ConfigSection('menus', '')

    def __init__(self):
        ComponentManager.__init__(self)
        self.log = logging.getLogger(self.__class__.__name__)
        self.monitoring = {}

    def __repr__(self):
        return '<BurpExtender at %#x>' % (id(self), )

    def __iter__(self):
        for request in self.getProxyHistory():
            yield request

    def _monitor_item(self, obj):
        # don't monitor objects initialized in the interpreter

        if obj.__module__ == '__main__':
            return

        mod = obj.__module__
        cls = obj.__class__.__name__

        # Monitor the actual configuration file rather than the
        # module the Configuration class is defined in

        if isinstance(obj, Configuration):
            filename = obj.filename

        elif isinstance(obj, (Component, IMenuItemHandler)):
            filename = inspect.getsourcefile(obj.__class__)

        elif isinstance(obj, type):
            filename = inspect.getsourcefile(obj)

        monitoring = self.monitoring.setdefault(filename, [])

        monitoring.append({
            'class': cls,
            'instance': weakref.ref(obj),
            'module': mod,
            })

        return

    def componentActivated(self, component):
        self.log.debug('Activating component: %r', component)
        component.burp = self
        component.config = self.config
        component.log = self.log

        return

    def applicationClosing(self):
        '''
        This method is invoked immediately before Burp Suite exits.
        '''
        self.log.debug('Shutting down Burp')
        return

    def registerExtenderCallbacks(self, callbacks):
        '''
        This method is invoked on startup.
        '''
        self._callbacks = callbacks

        try:
            self.setExtensionName(self.getExtensionName())
        except Exception:
            pass

        try:
            log_filename = self.loadExtensionSetting(*settings.LOG_FILENAME)
            log_format = self.loadExtensionSetting(*settings.LOG_FORMAT)
            log_level = self.loadExtensionSetting(*settings.LOG_LEVEL)

            self.log.setLevel(log_level)

            fileHandler = logging.FileHandler(
                    log_filename, encoding='utf-8', delay=True)

            streamHandler = logging.StreamHandler()

            formatter = logging.Formatter(fmt=log_format)

            fileHandler.setFormatter(formatter)
            streamHandler.setFormatter(formatter)

            self.log.addHandler(fileHandler)
            self.log.addHandler(streamHandler)

            self._handler = fileHandler
        except Exception:
            self.log.exception('Could not load extension logging settings')

        try:
            config = self.loadExtensionSetting(*settings.CONFIG_FILENAME)
            self.config = Configuration(os.path.abspath(config))
        except Exception:
            self.log.exception('Could not load extension config settings')

        try:
            from gds.burp.listeners import PluginListener, \
                    SaveConfigurationOnUnload, \
                    ScannerListener

            SaveConfigurationOnUnload(self)
            PluginListener(self)
            ScannerListener(self)
        except Exception:
            self.log.exception('Could not load extension listener')

        try:
            from gds.burp.ui import ConsoleTab
            self._console_tab = ConsoleTab(self)
            self.console = self._console_tab.interpreter
        except Exception as e:
            self.log.exception('Could not load console tab')

        for module, _ in self._menus.options():
            if self._menus.getbool(module) is True:
                for menu in _get_menus(module):
                    menu(self)

        for component, _ in self._components.options():
            if self._components.getbool(component) is True:
                _get_plugins(component)

        self._monitor_item(self.config)
        self.monitor = PluginMonitorThread(self)
        self.monitor.start()

        self.issueAlert('Burp extender ready...')
        return

    def _check_cb(self):
        if hasattr(self, '_callbacks'):
            return getattr(self, '_callbacks')

    def _check_and_callback(self, method, *args):
        cb = self._check_cb()

        if not hasattr(cb, method.__name__):
            raise Exception("%s() not available in your version of Burp" % (
                            method.__name__, ))

        try:
            return getattr(cb, method.__name__)(*args)
        except AbstractMethodError:
            raise Exception("%s() not available in your version of Burp" % (
                            method.__name__, ))

    cb = property(_check_cb)

    @callback<commit_msg>disable proxy interception at startup<commit_after># -*- coding: utf-8 -*-
'''
BurpExtender
~~~~~~~~~~~~

BurpExtender is a proxied class that implements the burp.IBurpExtender
interface. It is what makes Jython <-> Burp possible.
'''
from java.io import File
from java.lang import AbstractMethodError, System
from org.python.util import JLineConsole, PythonInterpreter
from burp import IBurpExtender, IMenuItemHandler

from threading import Thread
import inspect
import json
import logging
import os
import re
import signal
import site
import sys
import weakref

from gds.burp import HttpRequest
from gds.burp.config import Configuration, ConfigSection
from gds.burp.core import Component, ComponentManager
from gds.burp.decorators import callback
from gds.burp.dispatchers import NewScanIssueDispatcher, PluginDispatcher
from gds.burp.monitor import PluginMonitorThread

import gds.burp.settings as settings


logging._srcfile = None
logging.logThreads = 0
logging.logProcesses = 0


class BurpExtender(IBurpExtender, ComponentManager):

    _components = ConfigSection('components', '')
    _menus = ConfigSection('menus', '')

    def __init__(self):
        ComponentManager.__init__(self)
        self.log = logging.getLogger(self.__class__.__name__)
        self.monitoring = {}

    def __repr__(self):
        return '<BurpExtender at %#x>' % (id(self), )

    def __iter__(self):
        for request in self.getProxyHistory():
            yield request

    def _monitor_item(self, obj):
        # don't monitor objects initialized in the interpreter

        if obj.__module__ == '__main__':
            return

        mod = obj.__module__
        cls = obj.__class__.__name__

        # Monitor the actual configuration file rather than the
        # module the Configuration class is defined in

        if isinstance(obj, Configuration):
            filename = obj.filename

        elif isinstance(obj, (Component, IMenuItemHandler)):
            filename = inspect.getsourcefile(obj.__class__)

        elif isinstance(obj, type):
            filename = inspect.getsourcefile(obj)

        monitoring = self.monitoring.setdefault(filename, [])

        monitoring.append({
            'class': cls,
            'instance': weakref.ref(obj),
            'module': mod,
            })

        return

    def componentActivated(self, component):
        self.log.debug('Activating component: %r', component)
        component.burp = self
        component.config = self.config
        component.log = self.log

        return

    def applicationClosing(self):
        '''
        This method is invoked immediately before Burp Suite exits.
        '''
        self.log.debug('Shutting down Burp')
        return

    def registerExtenderCallbacks(self, callbacks):
        '''
        This method is invoked on startup.
        '''
        self._callbacks = callbacks

        try:
            self.setExtensionName(self.getExtensionName())
        except Exception:
            pass

        try:
            log_filename = self.loadExtensionSetting(*settings.LOG_FILENAME)
            log_format = self.loadExtensionSetting(*settings.LOG_FORMAT)
            log_level = self.loadExtensionSetting(*settings.LOG_LEVEL)

            self.log.setLevel(log_level)

            fileHandler = logging.FileHandler(
                    log_filename, encoding='utf-8', delay=True)

            streamHandler = logging.StreamHandler()

            formatter = logging.Formatter(fmt=log_format)

            fileHandler.setFormatter(formatter)
            streamHandler.setFormatter(formatter)

            self.log.addHandler(fileHandler)
            self.log.addHandler(streamHandler)

            self._handler = fileHandler
        except Exception:
            self.log.exception('Could not load extension logging settings')

        try:
            config = self.loadExtensionSetting(*settings.CONFIG_FILENAME)
            self.config = Configuration(os.path.abspath(config))
        except Exception:
            self.log.exception('Could not load extension config settings')

        try:
            from gds.burp.listeners import PluginListener, \
                    SaveConfigurationOnUnload, \
                    ScannerListener

            SaveConfigurationOnUnload(self)
            PluginListener(self)
            ScannerListener(self)
        except Exception:
            self.log.exception('Could not load extension listener')

        try:
            from gds.burp.ui import ConsoleTab
            self._console_tab = ConsoleTab(self)
            self.console = self._console_tab.interpreter
        except Exception as e:
            self.log.exception('Could not load console tab')

        for module, _ in self._menus.options():
            if self._menus.getbool(module) is True:
                for menu in _get_menus(module):
                    menu(self)

        for component, _ in self._components.options():
            if self._components.getbool(component) is True:
                _get_plugins(component)

        self._monitor_item(self.config)
        self.monitor = PluginMonitorThread(self)
        self.monitor.start()

        # because I'm tired of disabling Burp Proxy Interception at startup
        self.setProxyInterceptionEnabled(False)

        self.issueAlert('Burp extender ready...')
        return

    def _check_cb(self):
        if hasattr(self, '_callbacks'):
            return getattr(self, '_callbacks')

    def _check_and_callback(self, method, *args):
        cb = self._check_cb()

        if not hasattr(cb, method.__name__):
            raise Exception("%s() not available in your version of Burp" % (
                            method.__name__, ))

        try:
            return getattr(cb, method.__name__)(*args)
        except AbstractMethodError:
            raise Exception("%s() not available in your version of Burp" % (
                            method.__name__, ))

    cb = property(_check_cb)

    @callback
{'fraction_non_alphanumeric': 0.08409953606073386, 'fraction_numerical': 0.0006748207507380852, 'mean_word_length': 2.3145093653899917, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '192594', 'n_tokens_mistral': 3116, 'n_tokens_neox': 2982, 'n_words': 788}