Esempio n. 1
0
    def run_scan(self, stderr = None):
        """Run the command represented by this class."""

        # We don't need a file name for stdout output, just a handle. A
        # TemporaryFile is deleted as soon as it is closed, and in Unix is
        # unlinked immediately after creation so it's not even visible.
        f = tempfile.TemporaryFile(mode = "rb", prefix = APP_NAME + "-stdout-")
        self.stdout_file = wrap_file_in_preferred_encoding(f)
        if stderr is None:
            stderr = f

        search_paths = self.get_path()
        env = dict(os.environ)
        env["PATH"] = search_paths
        log.debug("PATH=%s" % env["PATH"])

        command_list = self.ops.render()
        log.debug("Running command: %s" % repr(command_list))

        startupinfo = None
        if sys.platform == "win32":
            # This keeps a terminal window from opening.
            startupinfo = subprocess.STARTUPINFO()
            try:
                startupinfo.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW
            except AttributeError:
                # This name is used before Python 2.6.5.
                startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

        self.command_process = subprocess.Popen(command_list, bufsize=1,
                                     stdin=subprocess.PIPE,
                                     stdout=f,
                                     stderr=stderr,
                                     startupinfo = startupinfo,
                                     env=env)
Esempio n. 2
0
def wrap_file_in_preferred_encoding(f):
    """Wrap an open file to automatically decode its contents when reading from
    the encoding given by locale.getpreferredencoding, or just return the file
    if that doesn't work.

    The nmap executable will write its output in whatever the system encoding
    is. Nmap's output is usually all ASCII, but time zone it prints can be in a
    different encoding. If it is not decoded correctly it will be displayed as
    garbage characters. This function assists in reading the Nmap output. We
    don't know for sure what the encoding used is, but we take a best guess and
    decode the output into a proper unicode object so that the screen display
    and XML writer interpret it correctly."""

    try:
        preferredencoding = locale.getpreferredencoding()
    except locale.Error:
        # This can happen if the LANG environment variable is set to something
        # weird.
        preferredencoding = None

    if preferredencoding is not None:
        try:
            reader = codecs.getreader(preferredencoding)
            return reader(f, "replace")
        except LookupError:
            # The lookup failed. This can happen if the preferred encoding is
            # unknown ("X-MAC-KOREAN" has been observed). Ignore it and return
            # the unwrapped file.
            log.debug("Unknown encoding \"%s\"." % preferredencoding)

    return f
Esempio n. 3
0
def wrap_file_in_preferred_encoding(f):
    """Wrap an open file to automatically decode its contents when reading from
    the encoding given by locale.getpreferredencoding, or just return the file
    if that doesn't work.

    The nmap executable will write its output in whatever the system encoding
    is. Nmap's output is usually all ASCII, but time zone it prints can be in a
    different encoding. If it is not decoded correctly it will be displayed as
    garbage characters. This function assists in reading the Nmap output. We
    don't know for sure what the encoding used is, but we take a best guess and
    decode the output into a proper unicode object so that the screen display
    and XML writer interpret it correctly."""

    try:
        preferredencoding = locale.getpreferredencoding()
    except locale.Error:
        # This can happen if the LANG environment variable is set to something
        # weird.
        preferredencoding = None

    if preferredencoding is not None:
        try:
            reader = codecs.getreader(preferredencoding)
            return reader(f, "replace")
        except LookupError:
            # The lookup failed. This can happen if the preferred encoding is
            # unknown ("X-MAC-KOREAN" has been observed). Ignore it and return
            # the unwrapped file.
            log.debug("Unknown encoding \"%s\"." % preferredencoding)

    return f
Esempio n. 4
0
    def kill(self):
        """Kill the nmap subprocess."""
        log.debug(">>> Killing scan process %s" % self.command_process.pid)

        if sys.platform != "win32":
            try:
                from signal import SIGKILL
                os.kill(self.command_process.pid, SIGKILL)
                self.command_process.wait()
            except:
                pass
        else:
            try:
                import ctypes
                ctypes.windll.kernel32.TerminateProcess(int(self.command_process._handle), -1)
            except:
                pass
Esempio n. 5
0
    def kill(self):
        """Kill the nmap subprocess."""
        log.debug(">>> Killing scan process %s" % self.command_process.pid)

        if sys.platform != "win32":
            try:
                from signal import SIGKILL
                os.kill(self.command_process.pid, SIGKILL)
                self.command_process.wait()
            except:
                pass
        else:
            try:
                import ctypes
                ctypes.windll.kernel32.TerminateProcess(
                    int(self.command_process._handle), -1)
            except:
                pass
Esempio n. 6
0
    def __init__(self, command):
        """Initialize an Nmap command. This creates temporary files for
        redirecting the various types of output and sets the backing
        command-line string."""
        self.command = command
        self.command_process = None

        self.stdout_file = None

        self.ops = NmapOptions()
        self.ops.parse_string(command)
        # Replace the executable name with the value of nmap_command_path.
        #self.ops.executable = paths_config.nmap_command_path

        # Normally we generate a random temporary filename to save XML output
        # to. If we find -oX or -oA, the user has chosen his own output file.
        # Set self.xml_is_temp to False and don't delete the file when we're
        # done.
        self.xml_is_temp = True
        self.xml_output_filename = None
        if self.ops["-oX"]:
            self.xml_is_temp = False
            self.xml_output_filename = self.ops["-oX"]
        if self.ops["-oA"]:
            self.xml_is_temp = False
            self.xml_output_filename = self.ops["-oA"] + ".xml"

        # Escape '%' to avoid strftime expansion.
        for op in ("-oA", "-oX", "-oG", "-oN", "-oS"):
            if self.ops[op]:
                self.ops[op] = escape_nmap_filename(self.ops[op])

        if self.xml_is_temp:
            self.xml_output_filename = tempfile.mktemp(prefix=APP_NAME + "-",
                                                       suffix=".xml")
            self.ops["-oX"] = escape_nmap_filename(self.xml_output_filename)

        log.debug(">>> Temporary files:")
        log.debug(">>> XML OUTPUT: %s" % self.xml_output_filename)
Esempio n. 7
0
    def __init__(self, command):
        """Initialize an Nmap command. This creates temporary files for
        redirecting the various types of output and sets the backing
        command-line string."""
        self.command = command
        self.command_process = None

        self.stdout_file = None

        self.ops = NmapOptions()
        self.ops.parse_string(command)
        # Replace the executable name with the value of nmap_command_path.
        #self.ops.executable = paths_config.nmap_command_path

        # Normally we generate a random temporary filename to save XML output
        # to. If we find -oX or -oA, the user has chosen his own output file.
        # Set self.xml_is_temp to False and don't delete the file when we're
        # done.
        self.xml_is_temp = True
        self.xml_output_filename = None
        if self.ops["-oX"]:
            self.xml_is_temp = False
            self.xml_output_filename = self.ops["-oX"]
        if self.ops["-oA"]:
            self.xml_is_temp = False
            self.xml_output_filename = self.ops["-oA"] + ".xml"

        # Escape '%' to avoid strftime expansion.
        for op in ("-oA", "-oX", "-oG", "-oN", "-oS"):
            if self.ops[op]:
                self.ops[op] = escape_nmap_filename(self.ops[op])

        if self.xml_is_temp:
            self.xml_output_filename = tempfile.mktemp(prefix = APP_NAME + "-", suffix = ".xml")
            self.ops["-oX"] = escape_nmap_filename(self.xml_output_filename)

        log.debug(">>> Temporary files:")
        log.debug(">>> XML OUTPUT: %s" % self.xml_output_filename)
Esempio n. 8
0
    def run_scan(self, stderr=None):
        """Run the command represented by this class."""

        # We don't need a file name for stdout output, just a handle. A
        # TemporaryFile is deleted as soon as it is closed, and in Unix is
        # unlinked immediately after creation so it's not even visible.
        f = tempfile.TemporaryFile(mode="rb", prefix=APP_NAME + "-stdout-")
        self.stdout_file = wrap_file_in_preferred_encoding(f)
        if stderr is None:
            stderr = f

        search_paths = self.get_path()
        env = dict(os.environ)
        env["PATH"] = search_paths
        log.debug("PATH=%s" % env["PATH"])

        command_list = self.ops.render()
        log.debug("Running command: %s" % repr(command_list))

        startupinfo = None
        if sys.platform == "win32":
            # This keeps a terminal window from opening.
            startupinfo = subprocess.STARTUPINFO()
            try:
                startupinfo.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW
            except AttributeError:
                # This name is used before Python 2.6.5.
                startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

        self.command_process = subprocess.Popen(command_list,
                                                bufsize=1,
                                                stdin=subprocess.PIPE,
                                                stdout=f,
                                                stderr=stderr,
                                                startupinfo=startupinfo,
                                                env=env)
Esempio n. 9
0
def create_user_config_dir(user_dir, template_dir):
    """Create a user configuration directory by creating the directory if
    necessary, then copying all the files from the given template directory,
    skipping any that already exist."""
    from zenmapCore_Kvasir.UmitLogging import log
    log.debug(">>> Create user dir at %s" % user_dir)
    create_dir(user_dir)

    for filename in os.listdir(template_dir):
        template_filename = os.path.join(template_dir, filename)
        user_filename = os.path.join(user_dir, filename)
        # Only copy regular files.
        if not os.path.isfile(template_filename):
            continue
        # Don't overwrite existing files.
        if os.path.exists(user_filename):
            log.debug(">>> %s already exists." % user_filename)
            continue
        shutil.copyfile(template_filename, user_filename)
        log.debug(">>> Copy %s to %s." % (template_filename, user_filename))
Esempio n. 10
0
def create_user_config_dir(user_dir, template_dir):
    """Create a user configuration directory by creating the directory if
    necessary, then copying all the files from the given template directory,
    skipping any that already exist."""
    from zenmapCore_Kvasir.UmitLogging import log
    log.debug(">>> Create user dir at %s" % user_dir)
    create_dir(user_dir)

    for filename in os.listdir(template_dir):
        template_filename = os.path.join(template_dir, filename)
        user_filename = os.path.join(user_dir, filename)
        # Only copy regular files.
        if not os.path.isfile(template_filename):
            continue
        # Don't overwrite existing files.
        if os.path.exists(user_filename):
            log.debug(">>> %s already exists." % user_filename)
            continue
        shutil.copyfile(template_filename, user_filename)
        log.debug(">>> Copy %s to %s." % (template_filename, user_filename))
Esempio n. 11
0
except ImportError, e:
    raise ImportError(str(e) + ".\n" + _("Python 2.4 or later is required."))

# Removed Path(s) dependency to support a Kvasir configurable item
#import zenmapCore_Kvasir.Paths
#from zenmapCore_Kvasir.Paths import Path
from zenmapCore_Kvasir.NmapOptions import NmapOptions, split_quoted, join_quoted
from zenmapCore_Kvasir.UmitLogging import log
#from zenmapCore.UmitConf import PathsConfig
from zenmapCore_Kvasir.Name import APP_NAME

# The [paths] configuration from zenmap.conf, used to get nmap_command_path.
# This is not needed for Kvasir when set via config_item
#paths_config = PathsConfig()

log.debug(">>> Platform: %s" % sys.platform)


def wrap_file_in_preferred_encoding(f):
    """Wrap an open file to automatically decode its contents when reading from
    the encoding given by locale.getpreferredencoding, or just return the file
    if that doesn't work.

    The nmap executable will write its output in whatever the system encoding
    is. Nmap's output is usually all ASCII, but time zone it prints can be in a
    different encoding. If it is not decoded correctly it will be displayed as
    garbage characters. This function assists in reading the Nmap output. We
    don't know for sure what the encoding used is, but we take a best guess and
    decode the output into a proper unicode object so that the screen display
    and XML writer interpret it correctly."""
Esempio n. 12
0
    raise ImportError(str(e) + ".\n" + _("Python 2.4 or later is required."))

# Removed Path(s) dependency to support a Kvasir configurable item
#import zenmapCore_Kvasir.Paths
#from zenmapCore_Kvasir.Paths import Path
from zenmapCore_Kvasir.NmapOptions import NmapOptions, split_quoted, join_quoted
from zenmapCore_Kvasir.UmitLogging import log
#from zenmapCore.UmitConf import PathsConfig
from zenmapCore_Kvasir.Name import APP_NAME


# The [paths] configuration from zenmap.conf, used to get nmap_command_path.
# This is not needed for Kvasir when set via config_item
#paths_config = PathsConfig()

log.debug(">>> Platform: %s" % sys.platform)

def wrap_file_in_preferred_encoding(f):
    """Wrap an open file to automatically decode its contents when reading from
    the encoding given by locale.getpreferredencoding, or just return the file
    if that doesn't work.

    The nmap executable will write its output in whatever the system encoding
    is. Nmap's output is usually all ASCII, but time zone it prints can be in a
    different encoding. If it is not decoded correctly it will be displayed as
    garbage characters. This function assists in reading the Nmap output. We
    don't know for sure what the encoding used is, but we take a best guess and
    decode the output into a proper unicode object so that the screen display
    and XML writer interpret it correctly."""

    try: