def testMemory(self):
pwr_sid = self.pwr_sid
admin_sid = self.admin_sid
sd1=win32security.SECURITY_DESCRIPTOR()
sd2=win32security.SECURITY_DESCRIPTOR()
sd3=win32security.SECURITY_DESCRIPTOR()
dacl=win32security.ACL()
dacl.AddAccessAllowedAce(win32security.ACL_REVISION,win32con.GENERIC_READ,pwr_sid)
dacl.AddAccessAllowedAce(win32security.ACL_REVISION,win32con.GENERIC_ALL,admin_sid)
sd4=win32security.SECURITY_DESCRIPTOR()
sacl=win32security.ACL()
sacl.AddAuditAccessAce(win32security.ACL_REVISION,win32con.DELETE,admin_sid,1,1)
sacl.AddAuditAccessAce(win32security.ACL_REVISION,win32con.GENERIC_ALL,pwr_sid,1,1)
for x in xrange(0,200000):
sd1.SetSecurityDescriptorOwner(admin_sid,0)
sd2.SetSecurityDescriptorGroup(pwr_sid,0)
sd3.SetSecurityDescriptorDacl(1,dacl,0)
sd4.SetSecurityDescriptorSacl(1,sacl,0)
python类GENERIC_READ的实例源码
def CopyFileToCe(src_name, dest_name, progress = None):
sh = win32file.CreateFile(src_name, win32con.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None)
bytes=0
try:
dh = wincerapi.CeCreateFile(dest_name, win32con.GENERIC_WRITE, 0, None, win32con.OPEN_ALWAYS, 0, None)
try:
while 1:
hr, data = win32file.ReadFile(sh, 2048)
if not data:
break
wincerapi.CeWriteFile(dh, data)
bytes = bytes + len(data)
if progress is not None: progress(bytes)
finally:
pass
dh.Close()
finally:
sh.Close()
return bytes
def EnumServices():
resume = 0
accessSCM = win32con.GENERIC_READ
accessSrv = win32service.SC_MANAGER_ALL_ACCESS
#Open Service Control Manager
hscm = win32service.OpenSCManager(None, None, accessSCM)
#Enumerate Service Control Manager DB
typeFilter = win32service.SERVICE_WIN32
stateFilter = win32service.SERVICE_STATE_ALL
statuses = win32service.EnumServicesStatus(hscm, typeFilter, stateFilter)
for (short_name, desc, status) in statuses:
print short_name, desc, status
def testTransactNamedPipeBlocking(self):
event = threading.Event()
self.startPipeServer(event)
open_mode = win32con.GENERIC_READ | win32con.GENERIC_WRITE
hpipe = win32file.CreateFile(self.pipename,
open_mode,
0, # no sharing
None, # default security
win32con.OPEN_EXISTING,
0, # win32con.FILE_FLAG_OVERLAPPED,
None)
# set to message mode.
win32pipe.SetNamedPipeHandleState(
hpipe, win32pipe.PIPE_READMODE_MESSAGE, None, None)
hr, got = win32pipe.TransactNamedPipe(hpipe, str2bytes("foo\0bar"), 1024, None)
self.failUnlessEqual(got, str2bytes("bar\0foo"))
event.wait(5)
self.failUnless(event.isSet(), "Pipe server thread didn't terminate")
def testTransactNamedPipeBlockingBuffer(self):
# Like testTransactNamedPipeBlocking, but a pre-allocated buffer is
# passed (not really that useful, but it exercises the code path)
event = threading.Event()
self.startPipeServer(event)
open_mode = win32con.GENERIC_READ | win32con.GENERIC_WRITE
hpipe = win32file.CreateFile(self.pipename,
open_mode,
0, # no sharing
None, # default security
win32con.OPEN_EXISTING,
0, # win32con.FILE_FLAG_OVERLAPPED,
None)
# set to message mode.
win32pipe.SetNamedPipeHandleState(
hpipe, win32pipe.PIPE_READMODE_MESSAGE, None, None)
buffer = win32file.AllocateReadBuffer(1024)
hr, got = win32pipe.TransactNamedPipe(hpipe, str2bytes("foo\0bar"), buffer, None)
self.failUnlessEqual(got, str2bytes("bar\0foo"))
event.wait(5)
self.failUnless(event.isSet(), "Pipe server thread didn't terminate")
def CopyFileToCe(src_name, dest_name, progress = None):
sh = win32file.CreateFile(src_name, win32con.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None)
bytes=0
try:
dh = wincerapi.CeCreateFile(dest_name, win32con.GENERIC_WRITE, 0, None, win32con.OPEN_ALWAYS, 0, None)
try:
while 1:
hr, data = win32file.ReadFile(sh, 2048)
if not data:
break
wincerapi.CeWriteFile(dh, data)
bytes = bytes + len(data)
if progress is not None: progress(bytes)
finally:
pass
dh.Close()
finally:
sh.Close()
return bytes
def EnumServices():
resume = 0
accessSCM = win32con.GENERIC_READ
accessSrv = win32service.SC_MANAGER_ALL_ACCESS
#Open Service Control Manager
hscm = win32service.OpenSCManager(None, None, accessSCM)
#Enumerate Service Control Manager DB
typeFilter = win32service.SERVICE_WIN32
stateFilter = win32service.SERVICE_STATE_ALL
statuses = win32service.EnumServicesStatus(hscm, typeFilter, stateFilter)
for (short_name, desc, status) in statuses:
print(short_name, desc, status)
def testTransactNamedPipeBlocking(self):
event = threading.Event()
self.startPipeServer(event)
open_mode = win32con.GENERIC_READ | win32con.GENERIC_WRITE
hpipe = win32file.CreateFile(self.pipename,
open_mode,
0, # no sharing
None, # default security
win32con.OPEN_EXISTING,
0, # win32con.FILE_FLAG_OVERLAPPED,
None)
# set to message mode.
win32pipe.SetNamedPipeHandleState(
hpipe, win32pipe.PIPE_READMODE_MESSAGE, None, None)
hr, got = win32pipe.TransactNamedPipe(hpipe, str2bytes("foo\0bar"), 1024, None)
self.failUnlessEqual(got, str2bytes("bar\0foo"))
event.wait(5)
self.failUnless(event.isSet(), "Pipe server thread didn't terminate")
def testMemory(self):
pwr_sid = self.pwr_sid
admin_sid = self.admin_sid
sd1=win32security.SECURITY_DESCRIPTOR()
sd2=win32security.SECURITY_DESCRIPTOR()
sd3=win32security.SECURITY_DESCRIPTOR()
dacl=win32security.ACL()
dacl.AddAccessAllowedAce(win32security.ACL_REVISION,win32con.GENERIC_READ,pwr_sid)
dacl.AddAccessAllowedAce(win32security.ACL_REVISION,win32con.GENERIC_ALL,admin_sid)
sd4=win32security.SECURITY_DESCRIPTOR()
sacl=win32security.ACL()
sacl.AddAuditAccessAce(win32security.ACL_REVISION,win32con.DELETE,admin_sid,1,1)
sacl.AddAuditAccessAce(win32security.ACL_REVISION,win32con.GENERIC_ALL,pwr_sid,1,1)
for x in range(0,200000):
sd1.SetSecurityDescriptorOwner(admin_sid,0)
sd2.SetSecurityDescriptorGroup(pwr_sid,0)
sd3.SetSecurityDescriptorDacl(1,dacl,0)
sd4.SetSecurityDescriptorSacl(1,sacl,0)
def __init__(self):
self.pty = Pty()
self.ready_f = Future()
self._input_ready_callbacks = []
self.loop = get_event_loop()
self.stdout_handle = win32file.CreateFile(
self.pty.conout_name(),
win32con.GENERIC_READ,
0,
win32security.SECURITY_ATTRIBUTES(),
win32con.OPEN_EXISTING,
win32con.FILE_FLAG_OVERLAPPED,
0)
self.stdin_handle = win32file.CreateFile(
self.pty.conin_name(),
win32con.GENERIC_WRITE,
0,
win32security.SECURITY_ATTRIBUTES(),
win32con.OPEN_EXISTING,
win32con.FILE_FLAG_OVERLAPPED,
0)
self._buffer = []
def w32CreateFile(name, access=GENERIC_READ|GENERIC_WRITE,
flags=OPEN_BY_SERIAL_NUMBER):
return FTD2XX(_ft.FT_W32_CreateFile(_ft.STRING(name),
_ft.DWORD(access),
_ft.DWORD(0),
None,
_ft.DWORD(OPEN_EXISTING),
_ft.DWORD(flags),
_ft.HANDLE(0)))
def _mapmodule(self,module):
'''
Internal function!
manually map the module in memory. no error checking - fuck it, I don't care!
'''
self.LoadPE(module)
# Get current process handle
p_handle = kernel32.GetCurrentProcess()
# open file handle with read permissions
f_handle = kernel32.CreateFileA(module,win32con.GENERIC_READ,win32con.FILE_SHARE_READ,0,win32con.OPEN_EXISTING,win32con.FILE_ATTRIBUTE_NORMAL,0)
f_size = kernel32.GetFileSize(f_handle,None)
vp_pointer = kernel32.VirtualAllocEx(p_handle,0,f_size,win32con.MEM_RESERVE | win32con.MEM_COMMIT,win32con.PAGE_READWRITE)
byteread = ctypes.c_ulong(0)
# read file
state = kernel32.ReadFile(f_handle,vp_pointer,f_size,ctypes.byref(byteread),None)
kernel32.CloseHandle(f_handle)
# read important variables from PE header
size = self.pe.OPTIONAL_HEADER.SizeOfImage
src = self.pe.OPTIONAL_HEADER.ImageBase
headersize = self.pe.OPTIONAL_HEADER.SizeOfHeaders
p_addr = kernel32.VirtualAllocEx(p_handle,0,size,win32con.MEM_RESERVE | win32con.MEM_COMMIT,win32con.PAGE_READWRITE)
# Write headers
kernel32.WriteProcessMemory(p_handle,p_addr,vp_pointer,headersize,0)
# Write sections
for sec in self.pe.sections:
dstaddr = p_addr + sec.VirtualAddress
srcaddr = vp_pointer + sec.PointerToRawData
secsize = sec.SizeOfRawData
kernel32.WriteProcessMemory(p_handle,dstaddr,srcaddr,secsize,0)
kernel32.CloseHandle(p_handle)
kernel32.VirtualFree(vp_pointer,f_size,win32con.MEM_RELEASE)
return p_addr
def DemoCopyFile():
# Create a file on the device, and write a string.
cefile = wincerapi.CeCreateFile("TestPython", win32con.GENERIC_WRITE, 0, None, win32con.OPEN_ALWAYS, 0, None)
wincerapi.CeWriteFile(cefile, "Hello from Python")
cefile.Close()
# reopen the file and check the data.
cefile = wincerapi.CeCreateFile("TestPython", win32con.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None)
if wincerapi.CeReadFile(cefile, 100) != "Hello from Python":
print "Couldnt read the data from the device!"
cefile.Close()
# Delete the test file
wincerapi.CeDeleteFile("TestPython")
print "Created, wrote to, read from and deleted a test file!"
def HttpExtensionProc(self, ecb):
# NOTE: If you use a ThreadPoolExtension, you must still perform
# this check in HttpExtensionProc - raising the exception from
# The "Dispatch" method will just cause the exception to be
# rendered to the browser.
if self.reload_watcher.change_detected:
print "Doing reload"
raise InternalReloadException
if ecb.GetServerVariable("UNICODE_URL").endswith("test.py"):
file_flags = win32con.FILE_FLAG_SEQUENTIAL_SCAN | win32con.FILE_FLAG_OVERLAPPED
hfile = win32file.CreateFile(__file__, win32con.GENERIC_READ,
0, None, win32con.OPEN_EXISTING,
file_flags, None)
flags = isapicon.HSE_IO_ASYNC | isapicon.HSE_IO_DISCONNECT_AFTER_SEND | \
isapicon.HSE_IO_SEND_HEADERS
# We pass hFile to the callback simply as a way of keeping it alive
# for the duration of the transmission
try:
ecb.TransmitFile(TransmitFileCallback, hfile,
int(hfile),
"200 OK",
0, 0, None, None, flags)
except:
# Errors keep this source file open!
hfile.Close()
raise
else:
# default response
ecb.SendResponseHeaders("200 OK", "Content-Type: text/html\r\n\r\n", 0)
print >> ecb, "<HTML><BODY>"
print >> ecb, "The root of this site is at", ecb.MapURLToPath("/")
print >> ecb, "</BODY></HTML>"
ecb.close()
return isapicon.HSE_STATUS_SUCCESS
def HttpExtensionProc(self, ecb):
# NOTE: If you use a ThreadPoolExtension, you must still perform
# this check in HttpExtensionProc - raising the exception from
# The "Dispatch" method will just cause the exception to be
# rendered to the browser.
if self.reload_watcher.change_detected:
print("Doing reload")
raise InternalReloadException
if ecb.GetServerVariable("UNICODE_URL").endswith("test.py"):
file_flags = win32con.FILE_FLAG_SEQUENTIAL_SCAN | win32con.FILE_FLAG_OVERLAPPED
hfile = win32file.CreateFile(__file__, win32con.GENERIC_READ,
0, None, win32con.OPEN_EXISTING,
file_flags, None)
flags = isapicon.HSE_IO_ASYNC | isapicon.HSE_IO_DISCONNECT_AFTER_SEND | \
isapicon.HSE_IO_SEND_HEADERS
# We pass hFile to the callback simply as a way of keeping it alive
# for the duration of the transmission
try:
ecb.TransmitFile(TransmitFileCallback, hfile,
int(hfile),
"200 OK",
0, 0, None, None, flags)
except:
# Errors keep this source file open!
hfile.Close()
raise
else:
# default response
ecb.SendResponseHeaders("200 OK", "Content-Type: text/html\r\n\r\n", 0)
print("<HTML><BODY>", file=ecb)
print("The root of this site is at", ecb.MapURLToPath("/"), file=ecb)
print("</BODY></HTML>", file=ecb)
ecb.close()
return isapicon.HSE_STATUS_SUCCESS
def DemoCopyFile():
# Create a file on the device, and write a string.
cefile = wincerapi.CeCreateFile("TestPython", win32con.GENERIC_WRITE, 0, None, win32con.OPEN_ALWAYS, 0, None)
wincerapi.CeWriteFile(cefile, "Hello from Python")
cefile.Close()
# reopen the file and check the data.
cefile = wincerapi.CeCreateFile("TestPython", win32con.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None)
if wincerapi.CeReadFile(cefile, 100) != "Hello from Python":
print("Couldnt read the data from the device!")
cefile.Close()
# Delete the test file
wincerapi.CeDeleteFile("TestPython")
print("Created, wrote to, read from and deleted a test file!")
def testTransactNamedPipeAsync(self):
event = threading.Event()
overlapped = pywintypes.OVERLAPPED()
overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None)
self.startPipeServer(event, 0.5)
open_mode = win32con.GENERIC_READ | win32con.GENERIC_WRITE
hpipe = win32file.CreateFile(self.pipename,
open_mode,
0, # no sharing
None, # default security
win32con.OPEN_EXISTING,
win32con.FILE_FLAG_OVERLAPPED,
None)
# set to message mode.
win32pipe.SetNamedPipeHandleState(
hpipe, win32pipe.PIPE_READMODE_MESSAGE, None, None)
buffer = win32file.AllocateReadBuffer(1024)
hr, got = win32pipe.TransactNamedPipe(hpipe, str2bytes("foo\0bar"), buffer, overlapped)
self.failUnlessEqual(hr, winerror.ERROR_IO_PENDING)
nbytes = win32file.GetOverlappedResult(hpipe, overlapped, True)
got = buffer[:nbytes]
self.failUnlessEqual(got, str2bytes("bar\0foo"))
event.wait(5)
self.failUnless(event.isSet(), "Pipe server thread didn't terminate")
def win32_comports_bruteforce():
import win32file
import win32con
ports = []
for i in range(1, 257):
portname = "\\\\.\\COM%i" % i
try:
mode = win32con.GENERIC_READ | win32con.GENERIC_WRITE
port = \
win32file.CreateFile(portname,
mode,
win32con.FILE_SHARE_READ,
None,
win32con.OPEN_EXISTING,
0,
None)
if portname.startswith("\\"):
portname = portname[4:]
ports.append((portname, "Unknown", "Serial"))
win32file.CloseHandle(port)
port = None
except Exception, e:
pass
return ports