Python CreateFile Cannot Find PhysicalMemory - python

I am trying to access the Physical Memory of a Windows 2000 system (trying to do this without a memory dumping tool). My understanding is that I need to do this using the CreateFile function to create a handle. I have used an older version of win32dd to help me through this. Other documentation on the web points me to using either "\Device\PhysicalMemory" or "\\.\PhysicalMemory". Unfortunately, I get the same error for each.
Traceback (most recent call last):
File "testHandles.py", line 101, in (module)
File "testHandles.py", line 72, in createFileHandle
pywintypes.error: (3, 'CreateFile', 'The system cannot find the path specified.')
Actually, the error number returned is different for each run \\.\PhysicalMemory == 3 and \Device\PhysicalMemory == 2. Review of pywin32, win32file, createfile, pyhandle, and pywintypes did not produce information as to the different return values.
Here is my code. I am using py2exe to get this working on Windows 2000 (and yes it compiles successfully). I realize that I might also have a problem with DeviceIoControl but right now I am concentrating on CreateFile.
# testHandles.py
import ctypes
import socket
import struct
import sys
import win32file
import pywintypes
def createFileHandle():
outLoc = pywintypes.Unicode("C:\\Documents and Settings\\Administrator\\My Documents\\pymemdump_dotPM.dd")
handleLoc = pywintypes.Unicode("\\\\.\\PhysicalMemory")
#handleLoc = pywintypes.Unicode("\\Device\\PhysicalMemory")
placeHolder = 0
BytesReturned = 0
# Device = CreateFile(L"\\\\.\\win32dd", GENERIC_ALL, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
# CreateFile(fileName, desiredAccess , shareMode , attributes , creationDisposition , flagsAndAttributes , hTemplateFile )
#hMemHandle = win32file.CreateFile(handleLoc, GENERIC_ALL, SHARE_READ, None, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, None)
hMemHandle = win32file.CreateFile(handleLoc, win32file.GENERIC_READ, win32file.FILE_SHARE_READ, None, win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_NORMAL, None)
print "hMemHandle: %s" % hMemHandle
if (hMemHandle == NO_ERROR):
print "Could not build hMemHandle"
sys.exit()
# We send destination path to the driver.
#if (!DeviceIoControl(hMemHandle, 0x19880922, outLoc, (ULONG)(wcslen(outLoc) + 1) * sizeof(TCHAR), NULL, 0, &BytesReturned, NULL))
if (ctypes.windll.Kernel32.DeviceIoControl(hMemHandle, 0x19880922, outLoc, 5, NULL, 0, BytesReturned, NULL)):
print "Error: DeviceIoControl(), Cannot send IOCTL.\n"
else:
print "[win32dd] Physical memory dumped. You can now check %s.\n" % outLoc
# Dump memory
createFileHandle()
Thank you,
Cutaway

I don't believe it's possible to access the physical memory object from user mode land in Windows. As your win32dd link suggests, you will need to do it from kernel mode.

Related

pdfdump in python not working using scapy

#!/bin/bash/python3
from scapy3k.all import *``
import subprocess
import os
def ifac111():
pkts = sniff(filter="tcp", iface="tun0", count=100)
inp = input('want to see a \'pdfdump?\' \n Y/N--> ')
fag = pkts.summary()
print('-' * 60)
what_df = pkts.show()
print("^^^ Here you got {} packets {}.".format("100", "scanned"))
print("The {} ones are {} and second ones are just {} command".format("first", "summary", "show" ))
print(inp)
if inp == 'Y':
pkts[0].pdfdump()
else:
print("got ya \f hex0")
while 1 > 0:
SSS = input('enter your command\'s here:-> \t ') #\t moves 4 spaces
if SSS == 'packets':
ifac111()
elif SSS == 'nworkscan':
os.system('sudo nmap localhost/24')
elif SSS == 'Virusscan':
os.system('sudo chkrootkit')
elif SSS == 'clear':
subprocess.call('clear')
when i run the pdfdump i get this error
Traceback (most recent call last):
File "scapy2.py", line 27, in <module>
ifac111()
File "scapy2.py", line 16, in ifac111
pkts[0].pdfdump()
File "/usr/local/lib/python3.6/dist-packages/scapy3k/packet.py", line 418, in pdfdump
canvas = self.canvas_dump(**kargs)
File "/usr/local/lib/python3.6/dist-packages/scapy3k/packet.py", line 428, in canvas_dump
canvas = pyx.canvas.canvas()
NameError: name 'pyx' is not defined
sorry if the question is stupid I'm new with coding and been trying to do some research with no result I used ICMP instead of TCP also before on my old os but its not working after changing to parrot os and when I run pdfdump I get that error above
This is a bug in scapy3k.packet indeed - it tries to import pyx and silently continue if there's any import error, which leads to your problem:
try:
import pyx
except ImportError:
pass
You should fill a bug report in the project's github - the package should properly declare it's dependencies on 3rd part packages so they get installed alongside, and it should definitly not silence the fact that a required import failed.
In the meantime you can try installing pyx yourself - it might just work, or it might break elsewhere depending on versions compat.
You should use scapy instead of scapy3k, it contains those fixes and a better interception of PyX
FTR:
scapy3k = fork based on scapy 2.2.0 which used to be the only one supporting python 3
scapy (from secdev) = the original one, up-to-date that also works with python 3 since scapy 2.4.0+
Hard to believe this issue is still around after 3yrs. This is to inform anyone else who lands here wanting to know how to fix this problem.
It is due to "Intended" lazy import placed on the installation as it would require GB/s of downloaded files to support the TeX backend. Thus, this is an intentional error by the scapy project itself.
You need to install MikTeX and LiveTex as it is not evident.
LiveTex can be downloaded from here

Start multiprocessing.process in namespace

I'm trying to start a new process from within an already created namespace (named 'test').
I've looked into a few methods including nsenter:
import subprocess
from nsenter import Namespace
with Namespace(mypid, 'net'):
# output network interfaces as seen from within the mypid's net NS:
subprocess.check_output(['ip', 'a'])
But I cant seem to find a reference of where to find the var, mypid...!
Ideally I'd like to keep dependancies like nsenter to a minimum (for portability) so i'd probably like to go down the ctypes route, something like (although there is no syscall for netns...):
nsname = 'test'
netnspath = '%s%s' % ('/run/netns/', nsname)
netnspath = netnspath.encode('ascii')
libc = ctypes.CDLL('libc.so.6')
printdir(libc)
fd = open(netnspath)
print libc.syscall(???, fd.fileno())
OR (taken from http://tech.zalando.com/posts/entering-kernel-namespaces-with-python.html)
import ctypes
libc = ctypes.CDLL('libc.so.6')
# replace MYPID with the container's PID
fd = open('/proc/<MYPID>/ns/net')
libc.setns(fd.fileno(), 0)
# we are now inside MYPID's network namespace
However, I still have to know the PID, plus my libc does not have setns!
Any thoughts on how I could obtain the PID would be great!
TIA!
The problem with the nsenter module is that you need to provide it with the PID of a process that is already running inside your target namespace. This means that you can't actually use this module to make use of a network namespace that you have created using something like ip netns add.
The kernel's setns() system call takes a file descriptor rather than a PID. If you're willing to solve it with ctypes, you can do something like this:
from ctypes import cdll
libc = cdll.LoadLibrary('libc.so.6')
_setns = libc.setns
CLONE_NEWIPC = 0x08000000
CLONE_NEWNET = 0x40000000
CLONE_NEWUTS = 0x04000000
def setns(fd, nstype):
if hasattr(fd, 'fileno'):
fd = fd.fileno()
_setns(fd, nstype)
def get_netns_path(nspath=None, nsname=None, nspid=None):
'''Generate a filesystem path from a namespace name or pid,
and return a filesystem path to the appropriate file. Returns
the nspath argument if both nsname and nspid are None.'''
if nsname:
nspath = '/var/run/netns/%s' % nsname
elif nspid:
nspath = '/proc/%d/ns/net' % nspid
return nspath
If your libc doesn't have the setns() call, you may be out of luck
(although where are you running that you have a kernel recent enough
to support network namespaces but a libc that doesn't?).
Assuming you have a namespace named "blue" available (ip netns add
blue) you can run:
with open(get_netns_path(nsname="blue")) as fd:
setns(fd, CLONE_NEWNET)
subprocess.check_call(['ip', 'a'])
Note that you must run this code as root.
This works, however I'm unsure at what the 0 does as part of the syscall. So if someone could enlighten me that would be great!
import ctypes
nsname = 'test'
netnspath = '%s%s' % ('/run/netns/', nsname)
netnspath = netnspath.encode('ascii')
libc = ctypes.CDLL('libc.so.6')
fd = open(netnspath)
print libc.syscall(308, fd.fileno(), 0)
After finding this question we've updated python-nsenter so it is now able to enter namespaces via an arbitrary path in addition to providing the pid.
For example if you wanted to enter a namespace created by ip netns add you can now do something like:
with Namespace('/var/run/netns/foo', 'net'):
# do something in the namespace
pass
Version 0.2 is now available via PyPi with this update.

Python import error

I am trying to run a python file from the command line with a single parameter in Ubuntu 12.04. The program works if I simply run it from the IDE and pass the parameter in the code. However, if I call 'python readFromSerial1.py 3' in the command prompt, I get:
Traceback (most recent call last):
File "readFromSerial1.py", line 62, in <module>
main()
File "readFromSerial1.py", line 6, in main
readDataFromUSB(time)
File "readFromSerial1.py", line 9, in readDataFromUSB
import usb.core
ImportError: No module named usb.core
I'm a little confused as the module imports correctly if I run from the IDE. I download the pyUSB module and extracted it (its filename is pyusb-1.0.0a3). I then copied this file into
/usr/local/lib/python2.7/site-packages/. Is that the correct procedure? I have a feeling the issue is due to python simply not being able to find the usb module and I need to put it in the correct location. My code is below, and any help would be greatly appreciated:
readFromSerial1.py
import sys
def main():
time = sys.argv[1]
#time = 1
readDataFromUSB(time)
def readDataFromUSB(time):
import usb.core
#find device
dev = usb.core.find(idVendor=0x099e, idProduct=0x0001) #GPS info
#Was the device found?
if dev is None:
raise ValueError('Device not found')
else:
print "Device found!"
#Do this to avoid 'Errno16: Resource is busy'
if dev.is_kernel_driver_active(0):
try:
dev.detach_kernel_driver(0)
except usb.core.USBError as e:
sys.exit("Could not detach kernel driver: %s" % str(e))
#Sets default config
dev.set_configuration()
#Gets default endpoint
endpoint = dev[0][(0,0)][0]
writeObject = open("InputData.txt", "w")
#iterate for time purposes
for i in range(0, (time*6)): #sys.argv is command line variable for time input
data = dev.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize, 0, 100000)
sret = ''.join([chr(x) for x in data])
writeObject.write(sret);
print sret
'''
newStr = ''.join(sret[7:14])
compareStr = ",*4F"
if (newStr == compareStr):
print "The GPS is not reading in any values right now. Try going somewhere else with better reception."
else:
print sret[7:14]
'''
writeObject.close()
main()

Python and landscape_api

I am working on managing Canonical CM Landscape through Python api's. I don't know if any one could help me but am stuck in one point and I don't know if it is a simple Python error of that specific library. This is part of larger script but it drops when I tried to use the last function in this listing.
import os, json, sys, subprocess, csv, datetime, time
from landscape_api.base import API, HTTPError
from subprocess import Popen,PIPE,STDOUT,call
uri = "xxxxxxxxxxxxxxxxxxxxxxxx"
key = "xxxxxxxxxxxxxxxxxxxx"
secret = "xxxxxxxxxxxxxxxxxxxxxxx"
api = API(uri, key, secret)
proc=Popen('zenity --entry --text "Fill with machine Tag to be searched" --entry- text "Type Tag"', shell=True, stdout=PIPE, ) #Input from zenity window
output=proc.communicate()[0]
user="root"
script="2408"
mac = api.execute_script(query="tag:%s", script_id="script_id:%s", username="user:%s" %(output, script, user))
Last function api.execute_script returns error
Traceback (most recent call last):
File "Python_MAC_IP.py", line 35, in <module>
mac = api.execute_script(query="tag:%s", script_id="script_id:%s", username="user:%s" %(output, script, user))
TypeError: not all arguments converted during string formatting
You can only use the % operator on a single string, not across multiple strings. What you are currently asking Python to do is insert multiple variables into a string that only has one defined.
Change this line:
mac = api.execute_script(query="tag:%s", script_id="script_id:%s", username="user:%s" %(output, script, user))
to this:
mac = api.execute_script(query="tag:%s" %tag, script_id="script_id:%s" %script, username="user:%s" %user

Determine if an executable (or library) is 32 -or 64-bits (on Windows)

I am trying to find out if a given executable (or library) is compiled for 32-bits or 64-bits from Python. I am running Vista 64-bits and would like to determine if a certain application in a directory is compiled for 32-bits or 64-bits.
Is there a simple way to do this using only the standard Python libraries (currently using 2.5.4)?
The Windows API for this is GetBinaryType. You can call this from Python using pywin32:
import win32file
type=GetBinaryType("myfile.exe")
if type==win32file.SCS_32BIT_BINARY:
print "32 bit"
# And so on
If you want to do this without pywin32, you'll have to read the PE header yourself. Here's an example in C#, and here's a quick port to Python:
import struct
IMAGE_FILE_MACHINE_I386=332
IMAGE_FILE_MACHINE_IA64=512
IMAGE_FILE_MACHINE_AMD64=34404
f=open("c:\windows\explorer.exe", "rb")
s=f.read(2)
if s!="MZ":
print "Not an EXE file"
else:
f.seek(60)
s=f.read(4)
header_offset=struct.unpack("<L", s)[0]
f.seek(header_offset+4)
s=f.read(2)
machine=struct.unpack("<H", s)[0]
if machine==IMAGE_FILE_MACHINE_I386:
print "IA-32 (32-bit x86)"
elif machine==IMAGE_FILE_MACHINE_IA64:
print "IA-64 (Itanium)"
elif machine==IMAGE_FILE_MACHINE_AMD64:
print "AMD64 (64-bit x86)"
else:
print "Unknown architecture"
f.close()
If you're running Python 2.5 or later on Windows, you could also use the Windows API without pywin32 by using ctypes.
from ctypes import windll, POINTER
from ctypes.wintypes import LPWSTR, DWORD, BOOL
SCS_32BIT_BINARY = 0 # A 32-bit Windows-based application
SCS_64BIT_BINARY = 6 # A 64-bit Windows-based application
SCS_DOS_BINARY = 1 # An MS-DOS-based application
SCS_OS216_BINARY = 5 # A 16-bit OS/2-based application
SCS_PIF_BINARY = 3 # A PIF file that executes an MS-DOS-based application
SCS_POSIX_BINARY = 4 # A POSIX-based application
SCS_WOW_BINARY = 2 # A 16-bit Windows-based application
_GetBinaryType = windll.kernel32.GetBinaryTypeW
_GetBinaryType.argtypes = (LPWSTR, POINTER(DWORD))
_GetBinaryType.restype = BOOL
def GetBinaryType(filepath):
res = DWORD()
handle_nonzero_success(_GetBinaryType(filepath, res))
return res
Then use GetBinaryType just like you would with win32file.GetBinaryType.
Note, you would have to implement handle_nonzero_success, which basically throws an exception if the return value is 0.
I've edited Martin B's answer to work with Python 3, added with statements and ARM/ARM64 support:
import struct
IMAGE_FILE_MACHINE_I386 = 332
IMAGE_FILE_MACHINE_IA64 = 512
IMAGE_FILE_MACHINE_AMD64 = 34404
IMAGE_FILE_MACHINE_ARM = 452
IMAGE_FILE_MACHINE_AARCH64 = 43620
with open('foo.exe', 'rb') as f:
s = f.read(2)
if s != b'MZ':
print('Not an EXE file')
else:
f.seek(60)
s = f.read(4)
header_offset = struct.unpack('<L', s)[0]
f.seek(header_offset + 4)
s = f.read(2)
machine = struct.unpack('<H', s)[0]
if machine == IMAGE_FILE_MACHINE_I386:
print('IA-32 (32-bit x86)')
elif machine == IMAGE_FILE_MACHINE_IA64:
print('IA-64 (Itanium)')
elif machine == IMAGE_FILE_MACHINE_AMD64:
print('AMD64 (64-bit x86)')
elif machine == IMAGE_FILE_MACHINE_ARM:
print('ARM eabi (32-bit)')
elif machine == IMAGE_FILE_MACHINE_AARCH64:
print('AArch64 (ARM-64, 64-bit)')
else:
print(f'Unknown architecture {machine}')
I was able to use Martin B's answer successfully in a Python 3.5 program after making this adjustment:
s=f.read(2).decode(encoding="utf-8", errors="strict")
Originally it worked just fine with my program in Python 2.7, but after making other necessary changes, I discovered I was getting b'MZ', and decoding it appears to fix this.
Using Python 3.7, 32 bit on 64 bit Win 7, the first code fragment in the top answer doesn't run for me. It fails because GetBinaryType is an unknown symbol. Solution is to use win32file.GetBinaryType.
Also running it on a .pyd file doesn't work, even if it is renamed to a .dll. See next:
import shutil
import win32file
from pathlib import Path
myDir = Path("C:\\Users\\rdboylan\\AppData\\Roaming\\Python\\Python37\\site-packages\\pythonwin")
for fn in ("Pythonwin.exe", "win32ui.pyd"):
print(fn, end=": ")
myf = myDir / fn
if myf.suffix == ".pyd":
mytemp = myf.with_suffix(".dll")
if mytemp.exists():
raise "Can not create temporary dll since {} exists".format(mytemp)
shutil.copyfile(myf, mytemp)
type = win32file.GetBinaryType(str(mytemp))
mytemp.unlink()
else:
type=win32file.GetBinaryType(str(myf))
if type==win32file.SCS_32BIT_BINARY:
print("32 bit")
else:
print("Something else")
# And so on
Results in
Pythonwin.exe: 32 bit
win32ui.pyd: Traceback (most recent call last):
File "C:/Users/rdboylan/Documents/Wk devel/bitness.py", line 14, in <module>
type = win32file.GetBinaryType(str(mytemp))
pywintypes.error: (193, 'GetBinaryType', '%1 is not a valid Win32 application.')

Categories