Esempio n. 1
0
def _getExpandedCounterPaths(processName, counterName):
  '''
  Get list of expanded counter paths given a counter name. Returns a
  list of strings or None, if no counter paths can be created
  '''
  pcchPathListLength = DWORD(0)
  szWildCardPath = LPSTR('\\process(%s)\\%s' % (processName, counterName))
  if pdh.PdhExpandCounterPathA(szWildCardPath, LPSTR(None),
                                      pointer(pcchPathListLength)) != _PDH_MORE_DATA:
    return None

  pathListLength = pcchPathListLength.value
  szExpandedPathList = LPCSTR('\0' * pathListLength)
  if pdh.PdhExpandCounterPathA(szWildCardPath, szExpandedPathList,
                               pointer(pcchPathListLength)) != 0:
    return None
  buffer = create_string_buffer(pcchPathListLength.value)
  memmove(buffer, szExpandedPathList, pcchPathListLength.value)

  paths = []
  i=0
  path = ''
  for j in range(0, pcchPathListLength.value):
    c = struct.unpack_from('c', buffer, offset=j)[0]
    if c == '\0':
      if j == i:
        # double null: we're done
        break
      paths.append(path)
      path = ''
      i = j + 1
    else:
      path += c

  return paths
Esempio n. 2
0
    def create_process(self, lpApplicationName, dwCreationFlags,
                       lpProcessInformation, lpStartupInfo):
        lpApplicationName = LPSTR(
            lpApplicationName.encode("utf-8"))  #   LPCSTR
        lpCommandLine = None  #   LPSTR
        lpProcessAttributes = None  #   LPSECUTITY_ATTRIBUTES
        lpThreadAttributes = None  #   LPSECUTITY_ATTRIBUTES
        bInheritHandle = False  #   Bool
        #dwCreationFlags     = None  #   DWORD
        lpEnvironment = None  #   LPVOID
        lpCurrentDirectory = None  #   LPCSTR
        #lpStartupInfo       = STARTUPINFRO()  #   LPSTARTUPINFOA
        #lpProcessInformation= PROCESS_INFORMATION()  #   #LPPROCESS_INFORMATION

        # Calling the Windows API Call
        response = self.__kernel_handler.CreateProcessA(
            lpApplicationName, lpCommandLine, lpProcessAttributes,
            lpThreadAttributes, bInheritHandle, dwCreationFlags, lpEnvironment,
            lpCurrentDirectory, ctypes.byref(lpStartupInfo),
            ctypes.byref(lpProcessInformation))
        # Check to see if we have a valid Handle to the process
        if response <= 0 or response is None:
            PrintScreen.err("create_process: Could Not Create Process Handle")
            self.assert_last_error()
        else:
            PrintScreen.log("Process Is Running...")

        return response
Esempio n. 3
0
    def _addCounter(self, processName, counterType, counterName):
        pCounterPathElements = _PDH_COUNTER_PATH_ELEMENTS_A(
            LPSTR(None),
            LPSTR(counterType),
            LPSTR(processName),
            LPSTR(None),
            DWORD(-1),
            LPSTR(counterName),
        )

        pcchbufferSize = DWORD(0)

        # First run we just try to get the buffer size so we can allocate a
        # string big enough to fill it
        if (pdh.PdhMakeCounterPathA(
                pointer(pCounterPathElements),
                LPCSTR(0),
                pointer(pcchbufferSize),
                DWORD(0),
        ) != _PDH_MORE_DATA):
            raise TalosError(
                "Could not create counter path for counter %s for %s" %
                (counterName, processName))

        szFullPathBuffer = LPCSTR("\0" * pcchbufferSize.value)
        # Then we run to get the actual value
        if (pdh.PdhMakeCounterPathA(
                pointer(pCounterPathElements),
                szFullPathBuffer,
                pointer(pcchbufferSize),
                DWORD(0),
        ) != 0):
            raise TalosError(
                "Could not create counter path for counter %s for %s" %
                (counterName, processName))

        path = szFullPathBuffer.value

        hq = HANDLE()
        if pdh.PdhOpenQuery(None, None, byref(hq)) != 0:
            raise TalosError("Could not open win32 counter query")

        hc = HANDLE()
        if pdh.PdhAddCounterA(hq, path, 0, byref(hc)) != 0:
            raise TalosError("Could not add win32 counter %s" % path)

        self.registeredCounters[counterName] = [hq, [(hc, path)]]
Esempio n. 4
0
def get_session_info(session):
    info = {
        "StationName": session.pWinStationName.decode("latin1"),
        "State": CONNECT_STATE.get(session.State, session.State),
    }
    csid = session.SessionId
    buf = LPSTR()
    size = DWORD()
    for q in (
            WTSInitialProgram,
            WTSApplicationName,
            WTSWorkingDirectory,
            WTSUserName,
            WTSDomainName,
            WTSClientName,
            WTSClientDirectory,
    ):
        if WTSQuerySessionInformationA(WTS_CURRENT_SERVER_HANDLE, csid, q,
                                       byref(buf), byref(size)):
            if buf.value:
                try:
                    info[WTS_INFO_CLASS.get(q, q)] = buf.value.decode("latin1")
                except:
                    pass
    if WTSQuerySessionInformationA(WTS_CURRENT_SERVER_HANDLE, csid,
                                   WTSClientDisplay, byref(buf), byref(size)):
        if size.value >= sizeof(WTS_CLIENT_DISPLAY):
            pdisplay = cast(buf, POINTER(WTS_CLIENT_DISPLAY))
            display = pdisplay[0]
            if display.HorizontalResolution > 0 and display.VerticalResolution > 0 and display.ColorDepth > 0:
                info["Display"] = {
                    "Width": display.HorizontalResolution,
                    "Height": display.VerticalResolution,
                    "Depth": display.ColorDepth,
                }
    #if WTSQuerySessionInformationA(WTS_CURRENT_SERVER_HANDLE, csid, WTSConnectState, byref(buf), byref(size)):
    #    if size.value==4:
    #        state = cast(buf, POINTER(DWORD)).contents.value
    #        info["ConnectState"] = CONNECT_STATE.get(state, state)
    if WTSQuerySessionInformationA(WTS_CURRENT_SERVER_HANDLE, csid,
                                   WTSClientProtocolType, byref(buf),
                                   byref(size)):
        if size.value == 2:
            ptype = cast(buf, POINTER(WORD)).contents.value
            info["Type"] = {
                0: "console",
                1: "legacy",
                2: "RDP"
            }.get(ptype, ptype)
    return info
Esempio n. 5
0
def _getExpandedCounterPaths(processName, counterName):
    """
    Get list of expanded counter paths given a counter name. Returns a
    list of strings or None, if no counter paths can be created
    """
    pcchPathListLength = DWORD(0)
    szWildCardPath = LPSTR("\\process(%s)\\%s" % (processName, counterName))
    if (pdh.PdhExpandCounterPathA(szWildCardPath, LPSTR(None),
                                  pointer(pcchPathListLength)) !=
            _PDH_MORE_DATA):
        return []

    pathListLength = pcchPathListLength.value
    szExpandedPathList = LPCSTR("\0" * pathListLength)
    if (pdh.PdhExpandCounterPathA(szWildCardPath, szExpandedPathList,
                                  pointer(pcchPathListLength)) != 0):
        return []
    buffer = create_string_buffer(pcchPathListLength.value)
    memmove(buffer, szExpandedPathList, pcchPathListLength.value)

    paths = []
    i = 0
    path = ""
    for j in six.moves.range(0, pcchPathListLength.value):
        c = struct.unpack_from("c", buffer, offset=j)[0]
        if c == "\0":
            if j == i:
                # double null: we're done
                break
            paths.append(path)
            path = ""
            i = j + 1
        else:
            path += c

    return paths
Esempio n. 6
0
def get_sessions():
    cur = LPSTR(WTS_CURRENT_SERVER_HANDLE)
    h = WTSOpenServerA(cur)
    if not h:
        return {}
    session_info = PWTS_SESSION_INFOA()
    count = DWORD()
    sessions = {}
    if WTSEnumerateSessionsA(h, 0, 1, byref(session_info), byref(count)):
        for i in range(count.value):
            session = session_info[i]
            sessions[session.SessionId] = get_session_info(session)
        WTSFreeMemory(session_info)
    WTSCloseServer(h)
    return sessions
Esempio n. 7
0
def GetTokenSid(hToken):
    """Retrieve SID from Token"""

    dwSize = DWORD(0)
    pStringSid = LPSTR()
    TokenUser = 1

    r = GetTokenInformation(hToken, TokenUser, byref(TOKEN_USER()), 0,
                            byref(dwSize))
    if r != 0:
        raise WinError(get_last_error())

    address = LocalAlloc(0x0040, dwSize)
    GetTokenInformation(hToken, TokenUser, address, dwSize, byref(dwSize))
    pToken_User = cast(address, POINTER(TOKEN_USER))
    ConvertSidToStringSidA(pToken_User.contents.User.Sid, byref(pStringSid))
    sid = pStringSid.value
    LocalFree(address)
    return sid
Esempio n. 8
0
def print_session_info(csid):
    buf = LPSTR()
    size = DWORD()
    for q in (WTSInitialProgram, WTSApplicationName, WTSWorkingDirectory,
              WTSUserName, WTSWinStationName, WTSDomainName,
              WTSClientName, WTSClientDirectory,
              WTSClientDisplay, ):
        if WTSQuerySessionInformationA(WTS_CURRENT_SERVER_HANDLE, csid, q, byref(buf), byref(size)):
            #log.info("%s=%s (%i bytes)", WTS_INFO_CLASS.get(q, q), bytestostr(buf.value), size.value)
            print(" %s=%s" % (WTS_INFO_CLASS.get(q, q), buf.value.decode("latin1")))
        else:
            print(" WTSQuerySessionInformationA failed for %s" % WTS_INFO_CLASS.get(q, q))
    if WTSQuerySessionInformationA(WTS_CURRENT_SERVER_HANDLE, csid, WTSConnectState, byref(buf), byref(size)):
        if size.value==4:
            state = cast(buf, POINTER(DWORD)).contents.value
            print(" WTSConnectState=%s" % (CONNECT_STATE.get(state, state),))
    if WTSQuerySessionInformationA(WTS_CURRENT_SERVER_HANDLE, csid, WTSClientProtocolType, byref(buf), byref(size)):
        if size.value==2:
            ptype = cast(buf, POINTER(WORD)).contents.value
            print(" WTSClientProtocolType=%s" % {0:"console", 1:"legacy", 2:"RDP"}.get(ptype, ptype))
Esempio n. 9
0
    def find_window_a(self, widnowName):
        #hWndParent = 0
        #hWndChildAfter = 0
        lpClassName = None  # ctypes.c_char_p(widnowName.encode("utf-8"))
        #lpWidnowName = ctypes.c_char_p(widnowName.encode('utf-8'))
        lpWidnowName = LPSTR(widnowName.encode('utf-8'))

        # Calling the Windows API Call
        #window_handle = self.__user_handler.FindWindowExA(hWndParent,hWndChildAfter, lpClassName, lpWidnowsName)
        window_handle = self.__user_handler.FindWindowA(
            lpClassName, lpWidnowName)
        #.FindWindowA(None, lpWindowName)

        if window_handle == 0 or window_handle is None:
            PrintScreen.err("find_window_a: Could Not Grab Handle".format())
            self.assert_last_error()  # check if occur error
            exit(1)
        else:
            PrintScreen.log(
                "find_window_a: Got Handle [{}]...".format(widnowName))

        return window_handle
Esempio n. 10
0
def main():
    from xpra.platform.win32.common import WTSGetActiveConsoleSessionId
    csid = WTSGetActiveConsoleSessionId()
    print("WTSGetActiveConsoleSessionId()=%s" % csid)
    cur = LPSTR(WTS_CURRENT_SERVER_HANDLE)
    h = WTSOpenServerA(cur)
    print("WTSOpenServerA(WTS_CURRENT_SERVER_HANDLE)=%s" % (h,))
    if h:
        sessions = PWTS_SESSION_INFOA()
        count = DWORD()
        if WTSEnumerateSessionsA(h, 0, 1, byref(sessions), byref(count)):
            print("WTSEnumerateSessionsA() found %i sessions" % count.value)
            for i in range(count.value):
                print("%i:" % i)
                session = sessions[i]
                print(" %#x" % session.SessionId)
                print(" %s" % session.pWinStationName.decode("latin1"))
                print(" %s" % CONNECT_STATE.get(session.State, session.State))
                print_session_info(session.SessionId)

            WTSFreeMemory(sessions)
        WTSCloseServer(h)
Esempio n. 11
0
def windowsOpen(filename):
    return CreateFile(LPSTR(filename.encode()), GENERIC_READ|GENERIC_WRITE, 0, None, OPEN_EXISTING, 0, None)