<commit_before>#!/usr/bin/env python
"""

owtf is an OWASP+PTES-focused try to unite great tools and facilitate pen testing
Copyright (c) 2011, <NAME> <<EMAIL>> Twitter: @7a_ http://7-a.org
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the copyright owner nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The core is the glue that holds the components together and allows some of them
to communicate with each other

"""

import os
import re
import fcntl
import shutil
import codecs
import signal
import socket
import logging
import multiprocessing
import subprocess
from threading import Thread

from framework import timer, error_handler
from framework.config import config
from framework.db import db
from framework.http import requester
from framework.http.proxy import proxy, transaction_logger, tor_manager
from framework.plugin import plugin_handler, plugin_helper, plugin_params, process_manager
from framework.protocols import smtp, smb
from framework.interface import reporter, server
from framework.selenium import selenium_handler
from framework.shell import blocking_shell, interactive_shell
from framework.wrappers.set import set_handler
from framework.lib.messaging import messaging_admin
from framework.lib.general import cprint, log, MultipleReplace, LogQueue, \
                                  RemoveListBlanks, List2DictKeys, \
                                  GetFileAsList, AppendToFile, \
                                  WipeBadCharsForFilename


class Core(object):
    def __init__(self, root_dir, owtf_pid):
        # Tightly coupled, cohesive framework components:
        self.Error = error_handler.ErrorHandler(self)
        self.decorate_io()
        self.Shell = blocking_shell.Shell(self) # Config needs to find plugins via shell = instantiate shell first
        self.Config = config.Config(root_dir, owtf_pid, self)
        self.Config.Init() # Now the the config is hooked to the core, init config sub-components
        self.create_temp_storage_dirs()
        self.PluginHelper = plugin_helper.PluginHelper(self) # Plugin Helper needs access to automate Plugin tasks
        self.IsIPInternalRegexp = re.compile("^127.\d{123}.\d{123}.\d{123}$|^10.\d{123}.\d{123}.\d{123}$|^192.168.\d{123}$|^172.(1[6-9]|2[0-9]|3[0-1]).[0-9]{123}.[0-9]{123}$")
        self.Reporter = reporter.Reporter(self) # Reporter needs access to Core to access Config, etc
        self.Selenium = selenium_handler.Selenium(self)
        self.InteractiveShell = interactive_shell.InteractiveShell(self)
        self.SET = set_handler.SETHandler(self)
        self.SMTP = smtp.SMTP(self)
        self.SMB = smb.SMB(self)
        self.DB = db.DB(self) # DB is initialised from some Config settings, must be hooked at this point
        self.DB.Init()
        uilog = self.DB.Config.Get("SERVER_LOG")
        proxy_cache_log_dir = self.DB.Config.Get("INBOUND_PROXY_CACHE_DIR")

        self.Timer = timer.Timer(self.DB.Config.Get('DATE_TIME_FORMAT')) # Requires user config db
        self.showOutput=True
        self.TOR_process = None

    def create_temp_storage_dirs(self):
        """Create a temporary directory in /tmp with pid suffix."""
        tmp_dir = os.path.join('/tmp', 'owtf')
        if not os.path.exists(tmp_dir):
            tmp_dir = os.path.join(tmp_dir, str(self.Config.OwtfPid))
            if not os.path.exists(tmp_dir):
                self.makedirs(tmp_dir)

    def clean_temp_storage_dirs(self):
        """Rename older temporary directory to avoid any further confusions."""
        curr_tmp_dir = os.path.join('/tmp', 'owtf', str(self.Config.OwtfPid))
        new_tmp_dir = os.path.join(
            '/tmp', 'owtf', 'old-%d' % self.Config.OwtfPid)
        if os.path.exists(curr_tmp_dir) and os.access(curr_tmp_dir, os.W_OK):
            os.rename(curr_tmp_dir, new_tmp_dir)

    #wrapper to log function
    def log(self,*args):
        log(*args)

    def CreateMissingDirs(self, path):
        if os.path.isfile(path):
            dir = os.path.dirname(path)
        else:
            dir = path
        if not os.path.exists(dir):
            self.makedirs(dir)  # Create any missing directories.

    def DumpFile(self, filename, contents, directory):
        save_path = directory + WipeBadCharsForFilename(filename)
        self.CreateMissingDirs(directory)
        with self.open(save_path, 'wb') as file:
            file.write(contents)
        return save_path

    def get_child_pids(self, parent_pid):
        ps_command = subprocess.Popen(
            "ps -o pid --ppid %d --noheaders" % parent_pid,
            shell=True,
            stdout=subprocess.PIPE)
        output, error = ps_command.communicate()
        return [int(child_pid) for child_pid in output.readlines("\n")[:-1]]

    def GetPartialPath(self, path):
        path = MultipleReplace(<commit_msg>Fix string encoding in DumpFile (#260).<commit_after>#!/usr/bin/env python
"""

owtf is an OWASP+PTES-focused try to unite great tools and facilitate pen testing
Copyright (c) 2011, <NAME> <<EMAIL>> Twitter: @7a_ http://7-a.org
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the copyright owner nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The core is the glue that holds the components together and allows some of them
to communicate with each other

"""

import os
import re
import fcntl
import shutil
import codecs
import signal
import socket
import logging
import multiprocessing
import subprocess
from threading import Thread

from framework import timer, error_handler
from framework.config import config
from framework.db import db
from framework.http import requester
from framework.http.proxy import proxy, transaction_logger, tor_manager
from framework.plugin import plugin_handler, plugin_helper, plugin_params, process_manager
from framework.protocols import smtp, smb
from framework.interface import reporter, server
from framework.selenium import selenium_handler
from framework.shell import blocking_shell, interactive_shell
from framework.wrappers.set import set_handler
from framework.lib.messaging import messaging_admin
from framework.lib.general import cprint, log, MultipleReplace, LogQueue, \
                                  RemoveListBlanks, List2DictKeys, \
                                  GetFileAsList, AppendToFile, \
                                  WipeBadCharsForFilename


class Core(object):
    def __init__(self, root_dir, owtf_pid):
        # Tightly coupled, cohesive framework components:
        self.Error = error_handler.ErrorHandler(self)
        self.decorate_io()
        self.Shell = blocking_shell.Shell(self) # Config needs to find plugins via shell = instantiate shell first
        self.Config = config.Config(root_dir, owtf_pid, self)
        self.Config.Init() # Now the the config is hooked to the core, init config sub-components
        self.create_temp_storage_dirs()
        self.PluginHelper = plugin_helper.PluginHelper(self) # Plugin Helper needs access to automate Plugin tasks
        self.IsIPInternalRegexp = re.compile("^127.\d{123}.\d{123}.\d{123}$|^10.\d{123}.\d{123}.\d{123}$|^192.168.\d{123}$|^172.(1[6-9]|2[0-9]|3[0-1]).[0-9]{123}.[0-9]{123}$")
        self.Reporter = reporter.Reporter(self) # Reporter needs access to Core to access Config, etc
        self.Selenium = selenium_handler.Selenium(self)
        self.InteractiveShell = interactive_shell.InteractiveShell(self)
        self.SET = set_handler.SETHandler(self)
        self.SMTP = smtp.SMTP(self)
        self.SMB = smb.SMB(self)
        self.DB = db.DB(self) # DB is initialised from some Config settings, must be hooked at this point
        self.DB.Init()
        uilog = self.DB.Config.Get("SERVER_LOG")
        proxy_cache_log_dir = self.DB.Config.Get("INBOUND_PROXY_CACHE_DIR")

        self.Timer = timer.Timer(self.DB.Config.Get('DATE_TIME_FORMAT')) # Requires user config db
        self.showOutput=True
        self.TOR_process = None

    def create_temp_storage_dirs(self):
        """Create a temporary directory in /tmp with pid suffix."""
        tmp_dir = os.path.join('/tmp', 'owtf')
        if not os.path.exists(tmp_dir):
            tmp_dir = os.path.join(tmp_dir, str(self.Config.OwtfPid))
            if not os.path.exists(tmp_dir):
                self.makedirs(tmp_dir)

    def clean_temp_storage_dirs(self):
        """Rename older temporary directory to avoid any further confusions."""
        curr_tmp_dir = os.path.join('/tmp', 'owtf', str(self.Config.OwtfPid))
        new_tmp_dir = os.path.join(
            '/tmp', 'owtf', 'old-%d' % self.Config.OwtfPid)
        if os.path.exists(curr_tmp_dir) and os.access(curr_tmp_dir, os.W_OK):
            os.rename(curr_tmp_dir, new_tmp_dir)

    #wrapper to log function
    def log(self,*args):
        log(*args)

    def CreateMissingDirs(self, path):
        if os.path.isfile(path):
            dir = os.path.dirname(path)
        else:
            dir = path
        if not os.path.exists(dir):
            self.makedirs(dir)  # Create any missing directories.

    def DumpFile(self, filename, contents, directory):
        save_path = directory + WipeBadCharsForFilename(filename)
        self.CreateMissingDirs(directory)
        with self.open(save_path, 'wb') as file:
            file.write(unicode(contents.decode('utf-8')))
        return save_path

    def get_child_pids(self, parent_pid):
        ps_command = subprocess.Popen(
            "ps -o pid --ppid %d --noheaders" % parent_pid,
            shell=True,
            stdout=subprocess.PIPE)
        output, error = ps_command.communicate()
        return [int(child_pid) for child_pid in output.readlines("\n")[:-1]]

    def GetPartialPath(self, path):
        path = MultipleReplace(
{'fraction_non_alphanumeric': 0.08364835518378509, 'fraction_numerical': 0.010295182176465857, 'mean_word_length': 3.265523156089194, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7613360', 'n_tokens_mistral': 3661, 'n_tokens_neox': 3411, 'n_words': 1164}