예제 #1
0
    def __start(self):
        """
        Start and debug a program with (or without) parameters

        @rtype:  winappdbg.Debug
        @return: WinAppDbg Debug object that can be used to interact with the
                 application.

        @raise DebugError: Raises an exception on error.
            File was not found.
        """

        # First check if file exists (in case we have passed a full path)
        # If we cannot find the full path, search in %PATH%
        if win32.PathFileExists(self.pid_pname) is False:

            try:
                # Search for file using win32.SearchPath
                # If file does not exist, then an exception is raised
                # Works: win32.SearchPath(None, "notepad.exe", ".exe")
                # Works: win32.SearchPath(None, "notepad.exe", None)
                # Doesn't work: win32.SearchPath(None, "notepad", None)
                _, _ = win32.SearchPath(None, self.pid_pname, ".exe")

            # An exception will be raised if file was not found
            except WindowsError, e:
                raise DebugError(self.pid_pname, e)
예제 #2
0
def main(argv):

    # Print the banner.
    print "SelectMyParent: Start a program with a selected parent process"
    print "by Mario Vilas (mvilas at gmail.com)"
    print "based on a Didier Stevens tool (https://DidierStevens.com)"
    print

    # Check the command line arguments.
    if len(argv) < 3:
        script = os.path.basename(argv[0])
        print "  %s <pid> <process.exe> [arguments]" % script
        return

    # Request debug privileges.
    system = System()
    system.request_debug_privileges()

    # Parse the parent process argument.
    try:
        dwParentProcessId = HexInput.integer(argv[1])
    except ValueError:
        dwParentProcessId = None
    if dwParentProcessId is not None:
        dwMyProcessId = win32.GetProcessId(win32.GetCurrentProcess())
        if dwParentProcessId != dwMyProcessId:
            system.scan_processes_fast()
            if not system.has_process(dwParentProcessId):
                print "Can't find process ID %d" % dwParentProcessId
                return
    else:
        system.scan_processes()
        process_list = system.find_processes_by_filename(argv[1])
        if not process_list:
            print "Can't find process %r" % argv[1]
            return
        if len(process_list) > 1:
            print "Too many processes found:"
            for process, name in process_list:
                print "\t%d:\t%s" % (process.get_pid(), name)
            return
        dwParentProcessId = process_list[0][0].get_pid()

    # Parse the target process argument.
    filename = argv[2]
    if not ntpath.exists(filename):
        try:
            filename = win32.SearchPath(None, filename, '.exe')[0]
        except WindowsError, e:
            print "Error searching for %s: %s" % (filename, str(e))
            return
        argv = list(argv)
        argv[2] = filename
예제 #3
0
파일: ptrace.py 프로젝트: pho3be/winappdbg
def parse_cmdline(argv):
    # Help message and version string
    version = ("Process execution tracer\n"
               "by Mario Vilas (mvilas at gmail.com)\n"
               "%s\n") % winappdbg.version
    usage = (
        "\n"
        "\n"
        "  Create a new process (parameters for the target must be escaped):\n"
        "    %prog [options] -c <executable> [parameters for the target]\n"
        "    %prog [options] -w <executable> [parameters for the target]\n"
        "\n"
        "  Attach to a running process (by filename):\n"
        "    %prog [options] -a <executable>\n"
        "\n"
        "  Attach to a running process (by ID):\n"
        "    %prog [options] -a <process id>")
    ##    formatter = optparse.IndentedHelpFormatter()
    ##    formatter = optparse.TitledHelpFormatter()
    parser = optparse.OptionParser(
        usage=usage,
        version=version,
        ##                                    formatter=formatter,
    )

    # Commands
    commands = optparse.OptionGroup(parser, "Commands")
    commands.add_option("-a",
                        "--attach",
                        action="append",
                        type="string",
                        metavar="PROCESS",
                        help="Attach to a running process")
    commands.add_option("-w",
                        "--windowed",
                        action="callback",
                        type="string",
                        metavar="CMDLINE",
                        callback=callback_execute_target,
                        help="Create a new windowed process")
    commands.add_option("-c",
                        "--console",
                        action="callback",
                        type="string",
                        metavar="CMDLINE",
                        callback=callback_execute_target,
                        help="Create a new console process [default]")
    parser.add_option_group(commands)

    # Tracing options
    tracing = optparse.OptionGroup(parser, "Tracing options")
    tracing.add_option("--trace",
                       action="store_const",
                       const="trace",
                       dest="mode",
                       help="Set the single step mode [default]")
    if System.arch == win32.ARCH_I386:
        tracing.add_option(
            "--branch",
            action="store_const",
            const="branch",
            dest="mode",
            help=
            "Set the step-on-branch mode (doesn't work on virtual machines)")
        tracing.add_option("--syscall",
                           action="store_const",
                           const="syscall",
                           dest="mode",
                           help="Set the syscall trap mode")
    ##    tracing.add_options("--module", action="append", metavar="MODULES",
    ##                                                            dest="modules",
    ##                   help="only trace into these modules (comma-separated)")
    ##    debugging.add_option("--from-start", action="store_true",
    ##                  help="start tracing when the process is created [default]")
    ##    debugging.add_option("--from-entry", action="store_true",
    ##                  help="start tracing when the entry point is reached")
    parser.add_option_group(tracing)

    # Debugging options
    debugging = optparse.OptionGroup(parser, "Debugging options")
    debugging.add_option(
        "--autodetach",
        action="store_true",
        help="automatically detach from debugees on exit [default]")
    debugging.add_option(
        "--follow",
        action="store_true",
        help="automatically attach to child processes [default]")
    debugging.add_option("--trusted",
                         action="store_false",
                         dest="hostile",
                         help="treat debugees as trusted code [default]")
    debugging.add_option(
        "--dont-autodetach",
        action="store_false",
        dest="autodetach",
        help="don't automatically detach from debugees on exit")
    debugging.add_option("--dont-follow",
                         action="store_false",
                         dest="follow",
                         help="don't automatically attach to child processes")
    debugging.add_option("--hostile",
                         action="store_true",
                         help="treat debugees as hostile code")
    parser.add_option_group(debugging)

    # Defaults
    parser.set_defaults(
        autodetach=True,
        follow=True,
        hostile=False,
        windowed=list(),
        console=list(),
        attach=list(),
        ##        modules     = list(),
        mode="trace",
    )

    # Parse and validate the command line options
    if len(argv) == 1:
        argv = argv + ['--help']
    (options, args) = parser.parse_args(argv)
    args = args[1:]
    if not options.windowed and not options.console and not options.attach:
        if not args:
            parser.error("missing target application(s)")
        options.console = [args]
    else:
        if args:
            parser.error("don't know what to do with extra parameters: %s" %
                         args)

    # Get the list of attach targets
    system = System()
    system.request_debug_privileges()
    system.scan_processes()
    attach_targets = list()
    for token in options.attach:
        try:
            dwProcessId = HexInput.integer(token)
        except ValueError:
            dwProcessId = None
        if dwProcessId is not None:
            if not system.has_process(dwProcessId):
                parser.error("can't find process %d" % dwProcessId)
            try:
                process = Process(dwProcessId)
                process.open_handle()
                process.close_handle()
            except WindowsError as e:
                parser.error("can't open process %d: %s" % (dwProcessId, e))
            attach_targets.append(dwProcessId)
        else:
            matched = system.find_processes_by_filename(token)
            if not matched:
                parser.error("can't find process %s" % token)
            for process, name in matched:
                dwProcessId = process.get_pid()
                try:
                    process = Process(dwProcessId)
                    process.open_handle()
                    process.close_handle()
                except WindowsError as e:
                    parser.error("can't open process %d: %s" %
                                 (dwProcessId, e))
                attach_targets.append(process.get_pid())
    options.attach = attach_targets

    # Get the list of console programs to execute
    console_targets = list()
    for vector in options.console:
        if not vector:
            parser.error("bad use of --console")
        filename = vector[0]
        if not ntpath.exists(filename):
            try:
                filename = win32.SearchPath(None, filename, '.exe')[0]
            except WindowsError as e:
                parser.error("error searching for %s: %s" % (filename, str(e)))
            vector[0] = filename
        console_targets.append(vector)
    options.console = console_targets

    # Get the list of windowed programs to execute
    windowed_targets = list()
    for vector in options.windowed:
        if not vector:
            parser.error("bad use of --windowed")
        filename = vector[0]
        if not ntpath.exists(filename):
            try:
                filename = win32.SearchPath(None, filename, '.exe')[0]
            except WindowsError as e:
                parser.error("error searching for %s: %s" % (filename, str(e)))
            vector[0] = filename
        windowed_targets.append(vector)
    options.windowed = windowed_targets

    # If no targets were set at all, show an error message
    if not options.attach and not options.console and not options.windowed:
        parser.error("no targets found!")

    return options
예제 #4
0
                    process.open_handle()
                    process.close_handle()
                except WindowsError, e:
                    parser.error("can't open process %d: %s" % (dwProcessId, e))
                attach_targets.append( process.get_pid() )
    options.attach = attach_targets

    # Get the list of console programs to execute
    console_targets = list()
    for vector in options.console:
        if not vector:
            parser.error("bad use of --console")
        filename = vector[0]
        if not ntpath.exists(filename):
            try:
                filename = win32.SearchPath(None, filename, '.exe')[0]
            except WindowsError, e:
                parser.error("error searching for %s: %s" % (filename, str(e)))
            vector[0] = filename
        console_targets.append(vector)
    options.console = console_targets

    # Get the list of windowed programs to execute
    windowed_targets = list()
    for vector in options.windowed:
        if not vector:
            parser.error("bad use of --windowed")
        filename = vector[0]
        if not ntpath.exists(filename):
            try:
                filename = win32.SearchPath(None, filename, '.exe')[0]
예제 #5
0
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of the copyright holder 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.

import sys

from winappdbg import win32

try:
    fullpath, basename = win32.SearchPath( None, sys.argv[1], '.dll' )
except WindowsError, e:
    if e.winerror != win32.ERROR_FILE_NOT_FOUND:
        raise
    fullpath, basename = win32.SearchPath( None, sys.argv[1], '.exe' )

print "Full path: %s" % fullpath
print "Base name: %s" % basename
예제 #6
0
def main(argv):

    # print(the banner.)
    print("SelectMyParent: Start a program with a selected parent process")
    print("by Mario Vilas (mvilas at gmail.com)")
    print("based on a Didier Stevens tool (https://DidierStevens.com)")
    print

    # Check the command line arguments.
    if len(argv) < 3:
        script = os.path.basename(argv[0])
        print("  %s <pid> <process.exe> [arguments]" % script)
        return

    # Request debug privileges.
    system = System()
    system.request_debug_privileges()

    # Parse the parent process argument.
    try:
        dwParentProcessId = HexInput.integer(argv[1])
    except ValueError:
        dwParentProcessId = None
    if dwParentProcessId is not None:
        dwMyProcessId = win32.GetProcessId(win32.GetCurrentProcess())
        if dwParentProcessId != dwMyProcessId:
            system.scan_processes_fast()
            if not system.has_process(dwParentProcessId):
                print("Can't find process ID %d" % dwParentProcessId)
                return
    else:
        system.scan_processes()
        process_list = system.find_processes_by_filename(argv[1])
        if not process_list:
            print("Can't find process %r" % argv[1])
            return
        if len(process_list) > 1:
            print("Too many processes found:")
            for process, name in process_list:
                print("\t%d:\t%s" % (process.get_pid(), name))
            return
        dwParentProcessId = process_list[0][0].get_pid()

    # Parse the target process argument.
    filename = argv[2]
    if not ntpath.exists(filename):
        try:
            filename = win32.SearchPath(None, filename, '.exe')[0]
        except WindowsError as e:
            print("Error searching for %s: %s" % (filename, str(e)))
            return
        argv = list(argv)
        argv[2] = filename

    # Start the new process.
    try:
        process = system.start_process(system.argv_to_cmdline(argv[2:]),
                                       bConsole=True,
                                       bInheritHandles=True,
                                       dwParentProcessId=dwParentProcessId)
        dwProcessId = process.get_pid()
    except AttributeError as e:
        if "InitializeProcThreadAttributeList" in str(e):
            print("This tool requires Windows Vista or above.")
        else:
            print("Error starting new process: %s" % str(e))
        return
    except WindowsError as e:
        print("Error starting new process: %s" % str(e))
        return
    print("Process created: %d" % dwProcessId)
    return dwProcessId