예제 #1
0
 def openDevice(self,
                device="DEVICE_UNKNOWN",
                password="",
                deviceCode=0,
                setId=0):
     device = c_char_p(device)
     self.MSP430_OpenDevice(device, c_char_p(password), len(password),
                            LONG(deviceCode), LONG(setId))
예제 #2
0
    def nativeEvent(self, event, message):
        return_value, result = super().nativeEvent(event, message)
        if sys.platform != "win32":
            return return_value, result
        # if you use Windows OS
        if event == b"windows_generic_MSG":
            msg = ctypes.wintypes.MSG.from_address(message.__int__())
            # Get the coordinates when the mouse moves.
            x = win32api.LOWORD(LONG(msg.lParam).value)  # type: ignore
            # converted an unsigned int to int (for dual monitor issue)
            if x & 32768:
                x = x | -65536
            y = win32api.HIWORD(LONG(msg.lParam).value)  # type: ignore
            if y & 32768:
                y = y | -65536

            x -= self.frameGeometry().x()
            y -= self.frameGeometry().y()

            # Determine whether there are other widgets at the mouse position.
            if self.childAt(x, y) is not None and self.childAt(
                    x, y) is not self.findChild(widgets.Widget,
                                                "ControlWidget"):
                # passing
                if (self.width() - self.BORDER_WIDTH > x > self.BORDER_WIDTH
                        and y < self.height() - self.BORDER_WIDTH):
                    return return_value, result

            if msg.message == WM_NCCALCSIZE:
                # Remove system title
                return True, 0

            if msg.message == WM_NCHITTEST:
                w, h = self.width(), self.height()
                lx = x < self.BORDER_WIDTH
                rx = x > w - self.BORDER_WIDTH
                ty = y < self.BORDER_WIDTH
                by = y > h - self.BORDER_WIDTH
                if lx and ty:
                    return True, HTTOPLEFT
                if rx and by:
                    return True, HTBOTTOMRIGHT
                if rx and ty:
                    return True, HTTOPRIGHT
                if lx and by:
                    return True, HTBOTTOMLEFT
                if ty:
                    return True, HTTOP
                if by:
                    return True, HTBOTTOM
                if lx:
                    return True, HTLEFT
                if rx:
                    return True, HTRIGHT
                # Title
                return True, HTCAPTION

        return return_value, result
예제 #3
0
 def getIF(self, number):
     name = create_string_buffer(128)
     pName = c_char_p(addressof(name))
     status = LONG()
     self.MSP430_GetNameOfUsbIf(LONG(number), byref(pName), byref(status))
     return (
         pName.value,
         EnableDisableType(status.value),
     )
예제 #4
0
    def initialize(self, port="TIUSB"):
        """.. py:method:: initialize(port)

            \brief   Initialize the interface.

            \note    1. This function must be called first.
            \note    2. MSP430_VCC() must be called second (after MSP430_Initialize() is called).
            \note    3. When initializing the MSP-FET430UIF (TI USB FET) parameter 'version' could
                        contain the value -1 or -3. This means that the Dll and the MSP-FET430UIF do not
                        have the same version (-3 means a major internal update is required).
                        MSP430_FET_FwUpdate() should be called.
                        MSP430_FET_FwUpdate() is part of the Maintenance API of the Dll.
                        When -3 was returned and calling MSP430_FET_FwUpdate(), the file CDC.log must exist
                        in the directory of the executed binary and the content must be the string "True"
                        without a newline. This file signals that a CDC driver is installed and prevents
                        the update from making the MSP-FET430UIF unusable.

            \param   port:    Interface port reference (application specific).
                            - To initialize a MSP-FET430PIF LPT Jtag adapter the parameter port should point to
                                a string which respresents the corresponding LPT port
                                (e.g. '1','2',... or 'LPT1','LPT2',...).
                            - To initialize TI's MSP-FET430UIF USB Jtag adapter the parameter
                                port should point to the string 'TIUSB' or just 'USB'.
                            - TI's MSP-FET430UIF USB Jtag adapter create Virtual Com Ports (VCPs)
                                on the PC system (see Device Manager). It is also possible to directly
                                pass the name of a dedicated VCP via this parameter (e.g. 'COM4, COM23,...).
                                This can be used to support multiple MSP-FET430UIF interfaces on one PC.
                                The later generation of USB development tools (eZ430-RF2500) no longer
                                uses the VCP approach. These tools enumerate as Human Interface Devices (HID)
                                on the USB. Since DLL version 2.03.00.000 it is also possible to directly
                                pass the name of a dedicated HID via this parameter.
                                When using a v3 MSP-FET430UIF it is enumerated as Communication Device Class (CDC).
                                Refer to MSP430_GetNumberOfUsbIfs() and MSP430_GetNameOfUsbIf()
                                for more information on VCP, HID and CDC.
            \param   version: The version number of the MSP430 DLL is returned (if version is not NULL).
                            A value of -1 or -3 reports a version conflict between the Dll and USB FET f/w.
                            In that case please refer to MSP430_FET_FwUpdate() on how to update
                            the firmware of the MSP-FET430UIF.

            \return  STATUS_OK:    The interface was initialized.
            \n       STATUS_ERROR: The interface was not initialized.

            \par     Error codes:
                     INITIALIZE_ERR
            \n       USB_FET_NOT_FOUND_ERR
            \n       USB_FET_BUSY_ERR
            \n           COMM_ERR
        """
        version = LONG()
        self.MSP430_Initialize(port, byref(version))
        self.debug(
            "MSP430_Initialize('{0}') - version returned: {1:#x}".format(
                port, version.value))
        return version.value
예제 #5
0
def QueryValue(key, sub_key):
    """string = QueryValue(key, sub_key) - retrieves the unnamed value for a key.

    key is an already open key, or any one of the predefined HKEY_* constants.
    sub_key is a string that holds the name of the subkey with which the value
    is associated.  If this parameter is None or empty, the function retrieves
    the value set by the SetValue() method for the key identified by key."

    Values in the registry have name, type, and data components. This method
    retrieves the data for a key's first value that has a NULL name.
    But the underlying API call doesn't return the type, Lame Lame Lame, DONT USE THIS!!!
    """
    from cygwinreg3.w32api import RegQueryValueW
    hkey = PyHKEY.make(key)
    buf_size = LONG()
    wincall(RegQueryValueW(hkey, sub_key, None, byref(buf_size)))
    buf = create_unicode_buffer(buf_size.value)
    wincall(RegQueryValueW(hkey, sub_key, buf, byref(buf_size)))
    return buf.value
예제 #6
0
 def getNumberOfIFs(self):
     number = LONG()
     self.MSP430_GetNumberOfUsbIfs(byref(number))
     return number.value
예제 #7
0
 def getFoundDevice(self):
     device = create_string_buffer(256)
     self.MSP430_GetFoundDevice(device, LONG(256))
     deviceStructure = cast(device, POINTER(_DeviceStructure))
     content = deviceStructure.contents
     return instanceiateNamedtuple(DeviceStructureNT, content)
예제 #8
0
 def getJTAGId(self):
     jid = LONG()
     self.MSP430_GetJtagID(byref(jid))
     return jid.value
예제 #9
0
 def getExternalVoltage(self):
     voltage = LONG()
     state = LONG()
     self.MSP430_GetExtVoltage(byref(voltage), byref(state))
     return (voltage.value, ErrorType(state.value))
예제 #10
0
 def getVCC(self):
     voltage = LONG()
     self.MSP430_GetCurVCCT(byref(voltage))
     self.debug("MSP430_GetCurVCCT() returned: {0:d}".format(voltage.value))
     return voltage.value  #/ 1000.0
예제 #11
0
    def get_token_next_code(self,
                            serial: str,
                            pin: str = '') -> Tuple[ByteString, Any, int]:
        # get the next passcode or tokencode (PRN) from a specified token
        # return a named tuple of passcode, tokencode, time-left
        # When using PINs with get_token_next_code, the passcode returned will vary based on the type of token.
        # There are three different types:
        #   PINPad-style - With this type of token, the numeric PIN is mixed or rolled into the tokencode. The passcode
        #   will be the same length as the tokencode (typically 6 or 8 digits).

        #   Fob-style - With this type of token, the alphanumeric PIN is prepended to the tokencode which can result in
        #   a passcode with a maximum length of 16 (8 characters for the PIN and 8 characters for the tokencode).

        #   PINless - With this type of token, the PIN is ignored if it is passed in, and the passcode will always be
        #   the same as the tokencode.

        if self.pin_style == "Fob-style":
            logger.debug(
                f"Fob-style token detected. Setting passcode length to pin_length {self.pin_length} +"
                f" tokencode length {self.tokencode_length}")
            passcode_length = self.pin_length + self.tokencode_length
        else:
            logger.debug(
                "PINLess or PINPad token. Tokencode and passcode length are equal."
            )
            passcode_length = self.tokencode_length

        chPASSCODE: Any = create_string_buffer(passcode_length)
        chPRN: Any = create_string_buffer(self.tokencode_length)

        # ctypes strings are bytes
        chPIN: c_char_p = c_char_p(pin.encode('utf-8'))
        lTimeLeft: c_long = LONG()

        svc_get_next: Any = self.process.GetNextCode

        if platform.architecture()[0] == "64bit":
            logger.debug("Setting return type of GetNextCode to c_int64")
            svc_get_next.restype = c_int64
        else:
            logger.debug("Setting return type of GetNextCode to c_int64")
            svc_get_next.restype = c_int

        svc_get_next.argtypes = [
            LONG,
            LPCSTR,
            LPCSTR,
            LPLONG,
            LPSTR,
            LPSTR,
        ]
        logger.debug(
            f"Setting arguments for GetNextCode to {svc_get_next.argtypes}")

        logger.debug("Calling GetNextCode with ctypes.")
        try:
            self.process.GetNextCode(self.lTokenServiceHandle,
                                     serial.encode("utf-8"), chPIN,
                                     byref(lTimeLeft), chPASSCODE, chPRN)
        except Exception as e:
            logger.debug(e)
            logger.error("Error getting next token code.")
            self.get_token_error()
        # On pinless tokens, PASSCODE and PRN will be the same
        return chPASSCODE.value.decode('utf-8'), chPRN.value.decode(
            'utf-8'), lTimeLeft.value
예제 #12
0
    def get_token_current_code(self,
                               serial: str,
                               pin_style: str,
                               pin: str = '') -> Tuple[ByteString, Any, int]:
        # The Pièce de résistance of this lib. Get the current code that would be displayed on the token screen
        # return a tuple of code + time-left.

        # When using PINs with get_token_current_code, the passcode returned will vary based on the type of token.
        # There are three different types:
        #   PINPad-style - With this type of token, the numeric PIN is mixed or rolled into the tokencode. The passcode
        #   will be the same length as the tokencode (typically 6 or 8 digits).

        #   Fob-style - With this type of token, the alphanumeric PIN is prepended to the tokencode which can result in
        #   a passcode with a maximum length of 16 (8 characters for the PIN and 8 characters for the tokencode).

        #   PINless - With this type of token, the PIN is ignored if it is passed in, and the passcode will always be
        #   the same as the tokencode.

        logger.debug(f"Pin style is {pin_style}")
        if self.pin_style == "Fob-style":
            passcode_length: int = self.pin_length + self.tokencode_length
        else:
            passcode_length: int = self.pin_length + self.tokencode_length

        logger.debug(f"Passcode length is now {passcode_length}")

        logger.debug(
            "Creating string buffers for passcode and pincode argument vars")

        # ctypes strings are bytes
        chPASSCODE: Any = create_string_buffer(passcode_length)
        chPRN: Any = create_string_buffer(self.tokencode_length)
        chPIN: c_char_p = c_char_p(pin.encode('utf-8'))
        lTimeLeft: c_long = LONG()

        svc_get_code: Any = self.process.GetCurrentCode

        if platform.architecture()[0] == "64bit":
            logger.debug("Setting return type of GetCurrentCode to c_int64")
            svc_get_code.restype = c_int64
        else:
            logger.debug("Setting return type of GetCurrentCode to c_int64")
            svc_get_code.restype = c_int

        svc_get_code.argtypes = [
            LONG,
            LPCSTR,
            LPCSTR,
            LPLONG,
            LPSTR,
            LPSTR,
        ]
        logger.debug(
            f"Setting arguments for GetCurrentCode to {svc_get_code.argtypes}")

        logger.debug("Calling GetCurrentCode with ctypes.")
        try:
            if self.process.GetCurrentCode(
                    self.lTokenServiceHandle, serial.encode("utf-8"), chPIN,
                    byref(lTimeLeft), chPASSCODE, chPRN) > 0:
                logger.info("Successfully retrieved the code.")
            else:
                logger.error(
                    "We did not successdully call the GetCurrentCode function")

        except Exception as e:
            logger.debug(e)
            logger.error("Error getting token code.")
            self.get_token_error()

        # On pinless tokens, PASSCODE and PRN will be the same
        logger.debug(
            f"Returning the passcode:{chPASSCODE.value}, tokencode: {chPRN.value}, and time left: {lTimeLeft}"
        )
        return chPASSCODE.value.decode('utf-8'), chPRN.value.decode(
            'utf-8'), lTimeLeft.value
예제 #13
0
    def __init__(self,
                 dll_name: str = '',
                 log_level: str = 'WARNING',
                 pin_length: int = 8,
                 tokencode_length: int = 8,
                 pin_style: str = "PINless"):
        # Set the logging level
        n_log_level: int
        if log_level.casefold() == 'NOTSET'.casefold():
            n_log_level = logging.NOTSET
        elif log_level.casefold() == 'CRITICAL'.casefold():
            n_log_level = logging.CRITICAL
        elif log_level.casefold() == 'ERROR'.casefold():
            n_log_level = logging.ERROR
        elif log_level.casefold() == 'WARNING'.casefold():
            n_log_level = logging.WARNING
        elif log_level.casefold() == 'INFO'.casefold():
            n_log_level = logging.INFO
        elif log_level.casefold() == 'DEBUG'.casefold():
            n_log_level = logging.DEBUG
        else:
            n_log_level = logging.WARNING
            logger.warning(
                'Log level: {} is not a supported option. Set to warning.'.
                format(log_level))

        if log_level != '':
            logger.setLevel(n_log_level)

        logging.debug('Initializing the SDProcess (calling sdauto32 init)')
        # Sanity check
        if pin_style not in self.valid_pin_styles:
            logger.warning(
                f"Invalid pin style {pin_style}. Setting to {self.valid_pin_styles[0]}"
            )
            self.pin_style = self.valid_pin_styles[0]
        else:
            self.pin_style = pin_style
            logger.debug(f'Pin style set to {self.pin_style}')

        if dll_name:  # Passed in from init args
            self.dll_name = dll_name
            logger.debug(f'DLL name set to {self.dll_name} from arguments')
            self.process = windll.LoadLibrary(self.dll_name)

        else:
            logger.debug(
                "No dll name passed in during initialization. Determining correct default from platform/arch"
            )
            if platform.system() == 'Windows':
                logger.debug("This is a windows platform.")
                if platform.architecture()[0] == "64bit":
                    logger.debug("This is a 64-bit platform.")
                    dll_path = Path(
                        r"C:\Program Files\RSA SecurID Token Common\stauto32.dll"
                    )
                    logger.info(f"Using path {dll_path}")
                else:
                    logger.debug("This is a 32-bit platform.")
                    dll_path = Path(
                        r"C:\Program Files (x86)\RSA SecurID Token Common\stauto32.dll"
                    )
                    logger.info(f"Using path {dll_path}")
                if dll_path.exists():
                    logger.debug(f"dll path {dll_path} exists.")
                    self.dll_name = str(dll_path)
                else:
                    logger.warning(
                        f"dll path {dll_path} does not exist. Setting dll_name to stauto32.dll"
                    )
                    self.dll_name = 'stauto32.dll'  # Hopefully, it's in the path
                try:
                    logger.debug(
                        f"Loading {dll_path} using ctypes windll method")
                    self.process = windll.LoadLibrary(self.dll_name)
                except Exception as e:
                    logger.debug(e)
                    logger.error("Error finding Soft Token service.")
                    return

            else:
                logger.debug("Non-windows system identified")
                try:
                    if self.dll_name == '':  # Don't use path locating. Call explicit default location.
                        self.dll_name = '/Library/Frameworks/stauto32.framework/Versions/Current/stauto32'
                    logger.debug(
                        f"Loading {dll_name} using ctypes cdll method")
                    self.process = cdll.LoadLibrary(self.dll_name)
                except Exception as e:
                    logger.debug(e)
                    logger.error("Error finding Soft Token service.")
                    return

        logger.debug("Loaded {} successfully".format(self.dll_name))

        # Validate pin-length
        if pin_length in range(6, 9) or pin_length == 0:
            logger.debug(f'Pin length is valid {pin_length}')
            self.pin_length = pin_length
        else:
            logger.error(f'Invalid pin length {pin_length}')
            raise ValueError(f"Invalid pin length {pin_length}")

        # Validate tokencode length (can be 6-8 digits)
        if tokencode_length in range(6, 9):
            logger.debug(f'Tokencode is set to {tokencode_length} digits')
            self.tokencode_length = tokencode_length
        else:
            logger.error(f'Invalid tokencode length provided')
            raise ValueError(
                f"Bad value for tokencode length {tokencode_length}")

        logger.info("Setting up SDProcess vars.")
        self.tokens: List[Any] = []
        self.lTokens: c_long = LONG()
        self.lTokenServiceHandle: c_long = LONG()
        self.lDefaultToken: c_long = LONG()
        self.lTimeLeft: c_long = LONG()
        self.dwBuffersize: c_long = DWORD(0)

        # Open the service
        logger.info(f"Opening SD Process from init")
        self._open_service()

        # Populate lTokens and dwBuffersize
        logger.info(f"Enumerating tokens from init")
        self._enum_tokens()
        logger.debug(f"There are {self.lTokens.value} tokens.")

        # Populate the token dict
        logger.info("Populating token dictionary from init")
        self.tokens = self._get_tokens()
예제 #14
0
 def writeRegister(self, num, value):
     reg = LONG(value)
     self.MSP430_Register(byref(reg), num, ReadWriteType.WRITE)