def injectfunc1(addr, arg, argsize, pid=0, handle=None, timeout=INJECT_TIMEOUT): """Inject function with 1 argument Either pid or the process handle should be specified @param addr LONG function memory address @param arg LPVOID @param argsize int @param pid LONG @param handle HANDLE @param timeout int msecs @return bool """ dprint("enter: pid = %s" % pid) isLocalHandle = False # bool if not handle and pid: isLocalHandle = True try: handle = win32api.OpenProcess(PROCESS_INJECT_ACCESS, 0, pid) if not handle: with SkProcessElevator(SE_DEBUG_PRIVILEGE) as priv: if priv.isElevated(): handle = win32api.OpenProcess( PROCESS_INJECT_ACCESS, 0, pid) except Exception, e: dwarn("windows error:", e)
def __enter__(self): d = self.__d if not d.privileges: dwarn( "failed to elevate privilege. This is might be a Windows XP machine" ) return # See: http://msdn.microsoft.com/ja-jp/library/windows/desktop/ms724944%28v=vs.85%29.aspx # See: http://nullege.com/codes/search/win32security.AdjustTokenPrivileges # See: http://www.oschina.net/code/explore/chromium.r67069/third_party/python_24/Lib/site-packages/win32/Demos/security/setkernelobjectsecurity.py #pid = win32api.GetCurrentProcessId() #ph = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, pid) ph = win32api.GetCurrentProcess() #d.token = win32security.OpenProcessToken(ph, win32con.TOKEN_ALL_ACCESS) d.token = win32security.OpenProcessToken( ph, win32con.TOKEN_ADJUST_PRIVILEGES | win32con.TOKEN_QUERY) d.privileges = win32security.AdjustTokenPrivileges( d.token, 0, d.privileges) if win32api.GetLastError(): dwarn("failed to elevate process privilege") else: dprint("process privileges elevated") return self
def downloadRequest(self, req): """ @param req QNetworkRequest """ url = req.url() dprint(url) self.downloadUrl(url)
def unmarshal(self, data): # str -> l = ([] if not data else [cookie for it in data.split(self.marshalSeparator) for cookie in QNetworkCookie.parseCookies(it) ]) dprint("cookie count = %i" % len(l)) self.setAllCookies(l)
def removefile(path): """ @param path str @return bool """ dprint(path) try: os.remove(path); return True except: return False
def stop(self): self.endtime = time.clock() self.interval = self.endtime - self.starttime if self.verbose: if self.text is not None: msg = "prof time: %s = %s sec" % (self.text, self.interval) else: msg = "prof time: %s sec" % self.interval skdebug.dprint(msg)
def setIgnoresFocus(self, value): if skos.WIN: dprint("value = %s" % value) hwnd = skwin.hwnd_from_wid(self.winId()) style = win32api.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) if value != bool(style & win32con.WS_EX_NOACTIVATE): style = (style | win32con.WS_EX_NOACTIVATE if value else style & ~win32con.WS_EX_NOACTIVATE) #win32gui.ShowWindow(hwnd, win32con.SW_HIDE) win32api.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, style)
def removetree(path): # remove the whole directory recursively """ @param path str @return bool """ try: if os.path.exists(path): dprint(path) import shutil shutil.rmtree(path) return True except: return False
def detach(args, path=''): """ @param args [unicode] @param* path unicode working directory @return bool """ from PySide.QtCore import QProcess dprint("path: %s" % (path or '(empty)')) dprint(args) if path: return QProcess.startDetached(args[0], args[1:], path) else: return QProcess.startDetached(args[0], args[1:])
def downloadUrl(url): """ @param url QUrl """ dprint(url) import skpaths location = skpaths.DESKTOP if url.isLocalFile(): import shutil path = url.toLocalFile() try: shutil.copy(path, location) except Exception, e: dwarn(e) else: url = url.toString() import skfileio, sknetio name = sknetio.reqname(url) name = skfileio.escape(name or url) path = os.path.join(location, name) import skthreads skthreads.runasync(partial(sknetio.getfile, url, path))
def injectdll(dllpath, pid=0, handle=None, timeout=INJECT_TIMEOUT): """Either pid or the process handle should be specified @param dllpath unicode ABSOLUTE path to dll @param pid LONG @param handle HANDLE @param timeout int msecs @return bool """ #if not dllpath or not os.path.exists(dllpath): # dwarn("error: dll does not exist") # return False dprint("enter: pid = %s" % pid) try: dllpath = dllpath.decode('utf8') except UnicodeDecodeError: dwarn("exit: error: failed to decode dll path to utf8") return False LOADLIBRARYW = getModuleFunctionAddress('LoadLibraryW', 'kernel32.dll') if not LOADLIBRARYW: dprint("exit error: cannot find LoadLibraryW from kernel32") return False data = dllpath dataSize = len(dllpath) * 2 + 2 # L'\0' ok = injectfunc1(LOADLIBRARYW, data, dataSize, pid=pid, handle=handle, timeout=timeout) dprint("exit: ret = ok") return ok
def attachgui(args): """Always hide command prompt on Windows @param args [unicode] @return bool """ dprint(args) # http://stackoverflow.com/questions/13592219/launch-a-totally-independent-process-from-python import subprocess try: if skos.WIN: flags = win32con.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP else: flags = 0 errcode = subprocess.call( args, creationflags=flags, #shell=True, close_fds=True) return errcode == 0 except Exception, e: dwarn(e) return False
def unloaddll(dllhandle, pid=0, handle=None, timeout=INJECT_TIMEOUT): """Either pid or the process handle should be specified @param dllhandle handle of the injected dll @param pid LONG @param handle HANDLE @param timeout int msecs @return bool """ dprint("enter: pid = %s" % pid) LOADLIBRARYW = getModuleFunctionAddress('LoadLibraryW', 'kernel32.dll') if not LOADLIBRARYW: dprint("exit error: cannot find LoadLibraryW from kernel32") return False data = dllhandle dataSize = 4 # size of DWORD ok = injectfunc1(LOADLIBRARYW, data, dataSize, pid=pid, handle=handle, timeout=timeout) dprint("exit: ret = ok") return 0
def updateWindowVisible(self): t = self.rootObject().property('windowVisible') if self.isVisible() != t: self.setVisible(t) dprint("visible = %s" % t)
def marshal(self): # -> str l = self.allCookies() dprint("cookie count = %i" % len(l)) return self.marshalSeparator.join(( cookie.toRawForm().data() for cookie in l ))
def refresh(self): self.xChanged.emit(self.x) self.yChanged.emit(self.y) self.widthChanged.emit(self.width) self.heightChanged.emit(self.height) dprint("pass")
def __exit__(self, *err): d = self.__d if d.hThread: ok = skwin.resume_thread(d.hThread) dprint("resume thread: %s" % ok)
def __enter__(self): d = self.__d d.hProcess, d.hThread, d.dwProcessId, d.dwThreadId = skwin.create_process( d.path, suspended=True, complete=True, *d.args, **d.kwargs) dprint("pid = %i" % d.dwProcessId) return self
def refresh(self): d = self.__d d.refreshCount = (d.refreshCount + 1) % 1000 # prevent from being too large old = d.valid new = self.valid if old != new: self.validChanged.emit(new) old = self.isVisible() new = d.visible = d.obj.visible if old != new: self.visibleChanged.emit(new) old = self.geometry() new = qtwin.qrect_from_rect(d.obj.rect) if old != new: d.geometry = new if old.x() != new.x(): self.xChanged.emit(new.x()) if old.y() != new.y(): self.yChanged.emit(new.y()) if old.width() != new.width(): self.widthChanged.emit(new.width()) if old.height() != new.height(): self.heightChanged.emit(new.height()) # Only update content size when geometry changed #old = self.contentSize() #new = d.obj.contentsize #if old != new: # d.contentSize = new # if old[0] != new[0]: # self.contentWidthChanged.emit(new[0]) # if old[1] != new[1]: # self.contentHeightChanged.emit(new[1]) # Only update window state when geometry changed old = self.windowState() d.updateWindowState() new = d.windowState if old != new: dprint("window state changed") self.windowStateChanged.emit(new, old) if old & Qt.WindowFullScreen != new & Qt.WindowFullScreen: self.fullScreenChanged.emit( bool(new & Qt.WindowFullScreen)) if old & Qt.WindowMinimized != new & Qt.WindowMinimized: self.minimizedChanged.emit( bool(new & Qt.WindowMinimized)) # I am not sure if this could cause slowdown in Rance, but the contentWidth might change when geometry not changed # Slowdown the refresh rate and see if it could work #elif d.refreshCount % 5 == 0: # refresh every 1 second = 200 * 5 old = self.contentSize() new = d.obj.contentsize if old != new: d.contentSize = new if old[0] != new[0]: self.contentWidthChanged.emit(new[0]) if old[1] != new[1]: self.contentHeightChanged.emit(new[1])
""" dprint("enter: pid = %s" % pid) isLocalHandle = False # bool if not handle and pid: isLocalHandle = True try: handle = win32api.OpenProcess(PROCESS_INJECT_ACCESS, 0, pid) if not handle: with SkProcessElevator(SE_DEBUG_PRIVILEGE) as priv: if priv.isElevated(): handle = win32api.OpenProcess( PROCESS_INJECT_ACCESS, 0, pid) except Exception, e: dwarn("windows error:", e) if not handle: dprint("exit: error: failed to get process handle") return False ret = False hProcess = handle try: data = arg dataSize = argsize # Reserved & commit # http://msdn.microsoft.com/en-us/library/windows/desktop/aa366803%28v=vs.85%29.aspx # http://msdn.microsoft.com/en-us/library/ms810627.aspx remoteData = skwinapi.VirtualAllocEx( hProcess, # process None, # __in_opt address dataSize, # data size