Ejemplo n.º 1
0
def print_codepage(printer, codepage):
    if codepage.isdigit():
        codepage = int(codepage)
        printer._raw(CODEPAGE_CHANGE + six.int2byte(codepage))
        printer._raw("after")
    else:
        printer.charcode(codepage)

    sep = ""

    # Table header
    printer.set(text_type='B')
    printer._raw("  {}\n".format(sep.join(map(lambda s: hex(s)[2:], range(0, 16)))))
    printer.set()

    # The table
    for x in range(0, 16):
        # First column
        printer.set(text_type='B')
        printer._raw("{} ".format(hex(x)[2:]))
        printer.set()

        for y in range(0, 16):
            byte = six.int2byte(x * 16 + y)

            if byte in (ESC, CTL_LF, CTL_FF, CTL_CR, CTL_HT, CTL_VT):
                byte = ' '

            printer._raw(byte)
            printer._raw(sep)
        printer._raw('\n')
Ejemplo n.º 2
0
 def __test__(self, exponent, secret, compressed_secret):
     with self.assertRaises(InvalidSecretError):
         Secret(compressed=False, payload=b''.join([
             serialize_beint(exponent, 32)]))
     with self.assertRaises(InvalidSecretError):
         Secret(compressed=True, payload=b''.join([
             serialize_beint(exponent, 32)]))
     obj = Secret(payload=b''.join([serialize_beint(exponent, 32)]))
     self.assertEqual(obj, secret)
     self.assertEqual(obj.exponent, exponent)
     self.assertFalse(obj.compressed)
     with self.assertRaises(InvalidSecretError):
         Secret(compressed=False, payload=b''.join([
             serialize_beint(exponent, 32),
             six.int2byte(0x01)]))
     with self.assertRaises(InvalidSecretError):
         Secret(compressed=True, payload=b''.join([
             serialize_beint(exponent, 32),
             six.int2byte(0x01)]))
     obj = Secret(payload=b''.join([
         serialize_beint(exponent, 32),
         six.int2byte(0x01)]))
     self.assertEqual(obj, compressed_secret)
     self.assertEqual(obj.exponent, exponent)
     self.assertTrue(obj.compressed)
Ejemplo n.º 3
0
 def _serialize_derint(n):
     n_str = serialize_bignum(n)
     return b''.join([
         six.int2byte(0x02),
         six.int2byte(len(n_str)),
         n_str,
     ])
Ejemplo n.º 4
0
def itob(i):
    """Integer to two bytes"""
    # devide in two parts (bytes)
    i1 = i % 256
    i2 = int(i / 256)
    # make string (little endian)
    return six.int2byte(i1) + six.int2byte(i2)
Ejemplo n.º 5
0
    def generate_key(self, slot, algorithm, pin_policy=PIN_POLICY.DEFAULT,
                     touch_policy=TOUCH_POLICY.DEFAULT):

        if ALGO.is_rsa(algorithm):
            ensure_not_cve201715361_vulnerable_firmware_version(self.version)

        if algorithm not in self.supported_algorithms:
            raise UnsupportedAlgorithm(
                'Algorithm not supported on this YubiKey: {}'
                .format(algorithm),
                algorithm_id=algorithm)

        data = Tlv(TAG.ALGO, six.int2byte(algorithm))
        if pin_policy:
            data += Tlv(TAG.PIN_POLICY, six.int2byte(pin_policy))
        if touch_policy:
            data += Tlv(TAG.TOUCH_POLICY, six.int2byte(touch_policy))
        data = Tlv(0xac, data)
        resp = self.send_cmd(INS.GENERATE_ASYMMETRIC, 0, slot, data)
        if algorithm in [ALGO.RSA1024, ALGO.RSA2048]:
            data = _parse_tlv_dict(Tlv(resp[1:]).value)
            return rsa.RSAPublicNumbers(
                int_from_bytes(data[0x82], 'big'),
                int_from_bytes(data[0x81], 'big')
            ).public_key(default_backend())
        elif algorithm in [ALGO.ECCP256, ALGO.ECCP384]:
            curve = ec.SECP256R1 if algorithm == ALGO.ECCP256 else ec.SECP384R1
            return ec.EllipticCurvePublicNumbers.from_encoded_point(
                curve(),
                resp[5:]
            ).public_key(default_backend())

        raise UnsupportedAlgorithm(
            'Invalid algorithm: {}'.format(algorithm),
            algorithm_id=algorithm)
Ejemplo n.º 6
0
    def respond_to_client_hello(self, message):
        """ Establishing new connection to id_b, send a 128 bit response consisting of
        8 bytes challenge, and a H_k(id_a, id_b, R_a) truncated to 8 bytes.
        """
        # Verify that incoming packet has correct length
        if not len(message) == 18:
            _logger.info('Wrong length of client hello')
            return

        # Verify incoming MAC
        expected_mac = handshake_mac(self.shared_key, message[:-8])
        if not constant_time_compare(message[-8:], expected_mac):
            _logger.info('Incorrect mac for client hello')
            return

        # Check that version is supported
        client_version = decode_version(message[1:2])
        if not client_version == self.version:
            # reply with supported version, and copy of client's message
            _logger.info('Unsupported version of client hello')
            msg = (six.int2byte(Message.version_not_supported) +
                encode_version(self.version) +
                message[2:10])
            mac = handshake_mac(self.shared_key, msg)
            self._send(msg + mac)
            return

        self.R_a = rng(8)
        self.R_b = message[2:10]

        msg = six.int2byte(Message.server_hello) + self.R_a
        mac = handshake_mac(self.shared_key, msg, self.R_b)
        self.state = ServerState.wait_for_sa_proposal
        self._send(msg + mac)
Ejemplo n.º 7
0
    def __bytes__(self):
        first_byte = utils.setbit(0, 7, self.fin)
        first_byte = utils.setbit(first_byte, 6, self.rsv1)
        first_byte = utils.setbit(first_byte, 5, self.rsv2)
        first_byte = utils.setbit(first_byte, 4, self.rsv3)
        first_byte = first_byte | self.opcode

        second_byte = utils.setbit(self.length_code, 7, self.mask)

        b = six.int2byte(first_byte) + six.int2byte(second_byte)

        if self.payload_length < 126:
            pass
        elif self.payload_length < MAX_16_BIT_INT:
            # '!H' pack as 16 bit unsigned short
            # add 2 byte extended payload length
            b += struct.pack('!H', self.payload_length)
        elif self.payload_length < MAX_64_BIT_INT:
            # '!Q' = pack as 64 bit unsigned long long
            # add 8 bytes extended payload length
            b += struct.pack('!Q', self.payload_length)
        else:
            raise ValueError("Payload length exceeds 64bit integer")

        if self.masking_key:
            b += self.masking_key
        return b
Ejemplo n.º 8
0
    def get_graphics_control_ext(self, duration=0.1, dispose=2,
            transparent_flag=0, transparency_index=0):
        """
        Graphics Control Extension. A sort of header at the start of
        each image. Specifies duration and transparancy.

        Dispose
        -------
          * 0 - No disposal specified.
          * 1 - Do not dispose. The graphic is to be left in place.
          * 2 -	Restore to background color. The area used by the graphic
            must be restored to the background color.
          * 3 -	Restore to previous. The decoder is required to restore the
            area overwritten by the graphic with what was there prior to
            rendering the graphic.
          * 4-7 -To be defined.
        """
        bb = '\x21\xF9\x04'
        # low bit 1 == transparency,
        bb += six.int2byte(((dispose & 3) << 2) | (transparent_flag & 1))
        # 2nd bit 1 == user input , next 3 bits, the low two of which are used,
        # are dispose.
        bb += itob(int(duration * 100)) # in 100th of seconds
        bb += six.int2byte(transparency_index)  # transparency index
        bb += '\x00'  # end
        return bb
Ejemplo n.º 9
0
 def _serialize_derint(n):
     n_str = BigNum(n).serialize()
     return b''.join([
         six.int2byte(0x02),
         six.int2byte(len(n_str)),
         n_str,
     ])
Ejemplo n.º 10
0
 def encode(self, input, errors='strict'):
     """
     Encode string to byte array
     :param input: string (unicode) object to convert to byte array
     :param errors: defines the error handling to apply
     :return: returns a tuple (output object, length consumed)
     """
     encode_buffer = b''
     consumed = 0
     for character in input:
         consumed += 1
         num = None
         try:
             num = self._encoding_map[ord(character)]
         except KeyError:
             if errors == 'replace':
                 num = 0x3f
             elif errors == 'ignore':
                 pass
             else:
                 raise ValueError("'%s' codec can't encode character %r in position %d" %
                                  (self.NAME, character, consumed - 1))
         if num is not None:
             if num & 0xff00:
                 encode_buffer += int2byte(self._ESCAPE)
             encode_buffer += int2byte(num & 0xff)
     return encode_buffer, consumed
Ejemplo n.º 11
0
def xor(key, data):
    """
    Perform cyclical exclusive or operations on ``data``.

    The ``key`` can be a an integer *(0 <= key < 256)* or a byte sequence. If
    the key is smaller than the provided ``data``, the ``key`` will be
    repeated.

    Args:
        key(int or bytes): The key to xor ``data`` with.
        data(bytes): The data to perform the xor operation on.

    Returns:
        bytes: The result of the exclusive or operation.

    Examples:
        >>> from pwny import *
        >>> xor(5, b'ABCD')
        b'DGFA'
        >>> xor(5, b'DGFA')
        b'ABCD'
        >>> xor(b'pwny', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
        b'15-=51)19=%5=9!)!%=-%!9!)-'
        >>> xor(b'pwny', b'15-=51)19=%5=9!)!%=-%!9!)-')
        b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    """

    if type(key) is int:
        key = six.int2byte(key)
    key_len = len(key)

    return b''.join(
        six.int2byte(c ^ six.indexbytes(key, i % key_len))
        for i, c in enumerate(six.iterbytes(data))
    )
Ejemplo n.º 12
0
	def test_read_rain_collector_type(self, mock_read_config_setting):
		mock_read_config_setting.return_value = six.int2byte(0b10101110)

		collector_type = RainCollectorTypeSerial(self.communicator.read_rain_collector_type())

		self.assertEqual(RainCollectorTypeSerial.millimeters_0_1, collector_type)
		mock_read_config_setting.assert_called_once_with('2B', '01')

		mock_read_config_setting.reset_mock()

		mock_read_config_setting.return_value = six.int2byte(0b10011110)

		collector_type = RainCollectorTypeSerial(self.communicator.read_rain_collector_type())

		self.assertEqual(RainCollectorTypeSerial.millimeters_0_2, collector_type)
		mock_read_config_setting.assert_called_once_with('2B', '01')

		mock_read_config_setting.reset_mock()

		mock_read_config_setting.return_value = six.int2byte(0b10001110)

		collector_type = RainCollectorTypeSerial(self.communicator.read_rain_collector_type())

		self.assertEqual(RainCollectorTypeSerial.inches_0_01, collector_type)
		mock_read_config_setting.assert_called_once_with('2B', '01')
Ejemplo n.º 13
0
	def test_read_setup_bit(self, mock_read_config_setting):
		mock_read_config_setting.return_value = six.int2byte(0b10101110)

		bit = self.communicator.read_setup_bit(0b10)

		self.assertEqual(0b10, bit)
		mock_read_config_setting.assert_called_once_with('2B', '01')

		mock_read_config_setting.reset_mock()

		mock_read_config_setting.return_value = six.int2byte(0b10101101)

		bit = self.communicator.read_setup_bit(0b10)

		self.assertEqual(0b00, bit)
		mock_read_config_setting.assert_called_once_with('2B', '01')

		mock_read_config_setting.reset_mock()

		mock_read_config_setting.return_value = six.int2byte(0b10101101)

		bit = self.communicator.read_setup_bit(0b110)

		self.assertEqual(0b100, bit)
		mock_read_config_setting.assert_called_once_with('2B', '01')

		mock_read_config_setting.reset_mock()

		mock_read_config_setting.return_value = six.int2byte(0b10101111)

		bit = self.communicator.read_setup_bit(0b110)

		self.assertEqual(0b110, bit)
		mock_read_config_setting.assert_called_once_with('2B', '01')
Ejemplo n.º 14
0
def rldecode(data):
    """
    RunLength decoder (Adobe version) implementation based on PDF Reference
    version 1.4 section 3.3.4:
        The RunLengthDecode filter decodes data that has been encoded in a
        simple byte-oriented format based on run length. The encoded data
        is a sequence of runs, where each run consists of a length byte
        followed by 1 to 128 bytes of data. If the length byte is in the
        range 0 to 127, the following length + 1 (1 to 128) bytes are
        copied literally during decompression. If length is in the range
        129 to 255, the following single byte is to be copied 257 - length
        (2 to 128) times during decompression. A length value of 128
        denotes EOD.
    """
    decoded = b''
    i = 0
    while i < len(data):
        #print 'data[%d]=:%d:' % (i,ord(data[i]))
        length = six.indexbytes(data,i)
        if length == 128:
            break
        if length >= 0 and length < 128:
            for j in range(i+1,(i+1)+(length+1)):
                decoded+=six.int2byte(six.indexbytes(data,j))
            #print 'length=%d, run=%s' % (length+1,run)
            
            i = (i+1) + (length+1)
        if length > 128:
            run = six.int2byte(six.indexbytes(data,i+1))*(257-length)
            #print 'length=%d, run=%s' % (257-length,run)
            decoded+=run
            i = (i+1) + 1
    return decoded
Ejemplo n.º 15
0
def nasm_null_safe_mutable_data_finalizer(env, code, data):
    """
    Simple data allocation strategy that expects the code to be in a writable
    segment. We just append the data to the end of the code.
    """

    if data or env.buffers:
        # Determine length of nullify + shellcode and adjust data pointer
        xor_offsets = []
        masked_data = OrderedDict()

        for datum, (offset, orig_datum) in six.iteritems(data):
            xor_offsets.extend([
                                   offset + i
                                   for i, b in enumerate(six.iterbytes(datum))
                                   if b in (0, 10, 13)
                                   ])

            masked_datum = b''.join([
                                        six.int2byte(b) if b not in (0, 10, 13)
                                        else six.int2byte(b ^ 0xff)
                                        for b in six.iterbytes(datum)
                                        ])
            masked_data[masked_datum] = (offset, orig_datum)

        if xor_offsets:
            # Build code to restore NUL, \r and \n
            temp_reg = env.TEMP_REG[env.target.bits]
            null_code = env.reg_load(env.BL, 255) + \
                        env.reg_load(temp_reg, env.OFFSET_REG)

            last_offset = 0
            for offset in xor_offsets:
                offset -= last_offset
                null_code.extend(
                    env.reg_add(temp_reg, offset) +
                    ['xor [%s], bl' % temp_reg]
                )
                last_offset += offset
            code = ['\t%s' % line for line in null_code] + code
            data = masked_data

        code_len = len(asm('\n'.join(code), target=env.target))
        adjust_ebp = env.reg_add(env.OFFSET_REG, code_len)

        return [
            '\tjmp __getpc1',
            '__getpc0:',
            '\tpop %s' % env.OFFSET_REG,
        ] + [
            '\t%s' % line for line in adjust_ebp
        ] + [
            '\tjmp __realstart',
            '__getpc1:',
            '\tcall __getpc0',
            '__realstart:',
        ] + code + _pack_data(data)
    else:
        return code
Ejemplo n.º 16
0
def serialize_bignum(n, *args, **kwargs):
    neg = n < 0
    n_str = serialize_beint(n, *args, **kwargs)
    if not n_str or n_str[:1] > six.int2byte(0x7f):
        n_str = six.int2byte(0) + n_str
    if neg:
        n_str = b''.join([six.int2byte(ord(n_str[:1])|0x80), n_str[1:]])
    return n_str
Ejemplo n.º 17
0
 def EncodeVarint(write, value):
   bits = value & 0x7f
   value >>= 7
   while value:
     write(six.int2byte(0x80|bits))
     bits = value & 0x7f
     value >>= 7
   return write(six.int2byte(bits))
Ejemplo n.º 18
0
 def EncodeVarint(write, value, unused_deterministic):
   bits = value & 0x7f
   value >>= 7
   while value:
     write(six.int2byte(0x80|bits))
     bits = value & 0x7f
     value >>= 7
   return write(six.int2byte(bits))
Ejemplo n.º 19
0
def int2ber(i, signed=True):
    encoded = b''
    while ((signed and (i > 127 or i < -128))
           or (not signed and (i > 255))):
        encoded = six.int2byte(i % 256) + encoded
        i = i >> 8
    encoded = six.int2byte(i % 256) + encoded
    return encoded
Ejemplo n.º 20
0
 def serialize(self, *args, **kwargs):
     neg = self < 0
     bytes_ = BigInteger(self).serialize(*args, **kwargs)
     if not bytes_ or bytes_[:1] > six.int2byte(0x7f):
         bytes_ = six.int2byte(0) + bytes_
     if neg:
         bytes_ = b''.join([six.int2byte(ord(bytes_[:1])|0x80), bytes_[1:]])
     return bytes_
Ejemplo n.º 21
0
	def display(self, cells):
		if self.translationTable:
			cells = _translate(cells, FOCUS_1_TRANSLATION_TABLE)
		if not self._awaitingAck:
			cells = b"".join([int2byte(x) for x in cells])
			self._sendPacket(FS_PKT_WRITE, int2byte(self.numCells), FS_BYTE_NULL, FS_BYTE_NULL, cells)
			self._pendingCells = []
		else:
			self._pendingCells = cells
Ejemplo n.º 22
0
 def bytes(self):
     return (
         six.int2byte(0x05) +
         self.pub_key +
         six.int2byte(len(self.key_handle)) +
         self.key_handle +
         self.certificate +
         self.signature
     )
Ejemplo n.º 23
0
def write_varlen(out, n):
    data = six.int2byte(n & 0x7F)
    while True:
        n = n >> 7
        if n:
            data = six.int2byte((n & 0x7F) | 0x80) + data
        else:
            break
    out.write(data)
Ejemplo n.º 24
0
 def _sendfrag(self, last, frag):
     x = len(frag)
     if last:
         x = x | 0x80000000
     header = (six.int2byte(int(x >> 24 & 0xff)) +
               six.int2byte(int(x >> 16 & 0xff)) +
               six.int2byte(int(x >> 8 & 0xff)) +
               six.int2byte(int(x & 0xff)))
     self.sock.send(header + frag)
Ejemplo n.º 25
0
 def testQueryBytesGlobalParams(self):
     method_config = base_api.ApiMethodInfo(request_type_name="SimpleMessage", query_params=["bytes_field"])
     service = FakeService()
     non_unicode_message = b"".join((six.int2byte(100), six.int2byte(200)))
     request = SimpleMessage()
     global_params = StandardQueryParameters(nextPageToken=non_unicode_message)
     http_request = service.PrepareHttpRequest(method_config, request, global_params=global_params)
     want = urllib_parse.urlencode({"nextPageToken": base64.urlsafe_b64encode(non_unicode_message)})
     self.assertIn(want, http_request.url)
Ejemplo n.º 26
0
 def import_key(self, slot, key, pin_policy=PIN_POLICY.DEFAULT,
                touch_policy=TOUCH_POLICY.DEFAULT):
     algorithm, data = _get_key_data(key)
     if pin_policy:
         data += Tlv(TAG.PIN_POLICY, six.int2byte(pin_policy))
     if touch_policy:
         data += Tlv(TAG.TOUCH_POLICY, six.int2byte(touch_policy))
     self.send_cmd(INS.IMPORT_KEY, algorithm, slot, data)
     return algorithm
Ejemplo n.º 27
0
 def serialize(self):
     point = self.point
     order = self._ecdsa_verifying_key.curve.generator.order()
     x_str = pyecdsa.util.number_to_string(point.x(), order)
     y_str = pyecdsa.util.number_to_string(point.y(), order)
     if self.compressed:
         return b''.join([six.int2byte(2 + (point.y() & 1)), x_str])
     else:
         return b''.join([six.int2byte(4), x_str, y_str])
Ejemplo n.º 28
0
def encode_length(l):
    assert l >= 0
    if l < 0x80:
        return int2byte(l)
    s = ("%x" % l).encode()
    if len(s)%2:
        s = b("0")+s
    s = binascii.unhexlify(s)
    llen = len(s)
    return int2byte(0x80|llen) + s
Ejemplo n.º 29
0
 def EncodeSignedVarint(write, value, unused_deterministic):
   if value < 0:
     value += (1 << 64)
   bits = value & 0x7f
   value >>= 7
   while value:
     write(six.int2byte(0x80|bits))
     bits = value & 0x7f
     value >>= 7
   return write(six.int2byte(bits))
Ejemplo n.º 30
0
def encode_varint(i):
    """ Encode a positiv integer to a variable length byte string. """
    if i < 0:
        raise ArgumentError('Cannot encode negative numbers as varint!')
    res = [six.int2byte(i % 128)]
    while i > 127:
        i >>= 7
        res.append(six.int2byte((i % 128) | 128))

    return b''.join(reversed(res))
Ejemplo n.º 31
0
def parse_response_data(resp_data):
    """
    According to https://fidoalliance.org/specs/fido-u2f-v1.0-nfc-bt-amendment-20150514/fido-u2f-raw-message-formats.html#authentication-response-message-success
    the response is made up of
    0:      user presence byte
    1-4:    counter
    5-:     signature

    :param resp_data: response data from the FIDO U2F client
    :type resp_data: hex string
    :return: tuple of user_presence_byte(byte), counter(int),
        signature(hexstring)
    """
    resp_data_bin = binascii.unhexlify(resp_data)
    user_presence = six.int2byte(six.indexbytes(resp_data_bin, 0))
    signature = resp_data_bin[5:]
    counter = struct.unpack(">L", resp_data_bin[1:5])[0]
    return user_presence, counter, signature
Ejemplo n.º 32
0
    def _int_low_high(inp_number, out_bytes):
        """ Generate multiple bytes for a number: In lower and higher parts, or more parts as needed.

        :param inp_number: Input number
        :param out_bytes: The number of bytes to output (1 - 4).
        """
        max_input = (256 << (out_bytes * 8) - 1)
        if not 1 <= out_bytes <= 4:
            raise ValueError("Can only output 1-4 bytes")
        if not 0 <= inp_number <= max_input:
            raise ValueError(
                "Number too large. Can only output up to {0} in {1} bytes".
                format(max_input, out_bytes))
        outp = b''
        for _ in range(0, out_bytes):
            outp += six.int2byte(inp_number % 256)
            inp_number //= 256
        return outp
Ejemplo n.º 33
0
def position_risk_request():
    socket = socket_init()

    # 拼消息
    msg_position_risk_request = AllProtoMsg_pb2.PositionRiskRequestMsg()

    # 序列化
    msg_str = msg_position_risk_request.SerializeToString()
    msg_type = 19
    msg_list = [six.int2byte(msg_type), msg_str]

    print "Send Position Risk Request Message."
    socket.send_multipart(msg_list)

    receive_message = socket.recv_multipart()
    print "Receive Message Success."
    position_risk_msg = AllProtoMsg_pb2.PositionRiskResponseMsg()
    position_risk_msg.ParseFromString((position_risk_msg.Holdings))
    print(receive_message[1])

    instrument_info_msg = AllProtoMsg_pb2.InstrumentInfoResponseMsg()
    instrument_info_msg.ParseFromString(instrument_info_msg.Targets)

    targets_msg_dict = dict()
    for instrument_msg in instrument_info_msg.Targets:
        targets_msg_dict[instrument_msg.id] = instrument_msg
    # for market_msg in instrument_info_msg.Infos:
    #     instrument_info = targets_msg_dict[market_msg.ID]
    return targets_msg_dict
    # print(targets_msg_dict)

    risk_msg_list = position_risk_msg(socket)
    for risk_item in risk_msg_list:
        account_name = risk_item.Key
        for position_item in risk_item.Value:
            instrument_msg = instrument_dict[position_item.Key]
            market_msg = market_dict[position_item.Key]
            risk_view = RiskView(instrument_msg, market_msg,
                                 position_item.Value, account_name)
            risk_view.print_info()
    # for market_msg in instrument_info_msg.Infos:
    #     instrument_info = targets_msg_dict[market_msg.ID]
    #     print(targets_msg_dict)
    return targets_msg_dict
Ejemplo n.º 34
0
def make_attribute_list(cr, attribute_order=None, validity_signing=None):
    """
    cr =
        {
            u'attributes': { ... "name": "value" ... },
            u'credential': u'pbdf.nijmegen.address',
            u'keyCounter': 0,
            u'validity': 1570123936
        }

    :param attribute_order: the order in which to handle the keys
    :type attribute_order: list
    """
    meta = MetadataAttribute(b'\x03')
    meta.setKeyCounter(cr[u'keyCounter'])
    meta.setCredentialTypeIdentifier(cr[u'credential'].encode('utf-8'))
    if validity_signing:
        meta.setValidityDuration(validity_signing[0])
        meta.setSigningDate(validity_signing[1])
    else:
        meta.setSigningDate()
        meta.setExpiryDateFromTimestamp(cr[u'validity'])
    signing_date = int(binascii.hexlify(meta.field(signingDateField)), 16)

    attrs = [meta.Int]
    attr_map = cr[u"attributes"]
    attribute_order = attribute_order or attr_map.keys()

    for k in attribute_order:
        if attr_map.get(k, None) is None:
            attrs.append(0)
        elif not attr_map[k]:
            attrs.append(1)
        else:
            encoded = attr_map[k].encode('utf-8')
            v = int(
                binascii.hexlify(b''.join(
                    six.int2byte(c) if isinstance(c, int) else c
                    for c in encoded)), 16)
            v <<= 1
            v += 1
            attrs.append(v)

    return attrs, signing_date
Ejemplo n.º 35
0
Archivo: rrtype.py Proyecto: tlex/dim
def _unescapify_from(value, offset):
    '''
    Unescape dns character string in value[offset:]. Returns a tuple of (bytearray unescaped_string,
    the position where the processing of value stopped).

    If offset == 0, value is supposed to be a dns character string. In this case, an exception is
    thrown at the first unescaped double quote found.

    If offset > 0, value should be a concatenation of dns character strings enclosed in double
    quotes (eg. '"ab" "c"').

    The processing of value stops at the first unescaped double quote. This position is returned
    along with the unescaped string created thus far.
    '''
    string = ''
    i = offset
    while i < len(value):
        if value[i] == '"':
            if offset > 0:
                return string, i
            raise ValueError('Unescaped quote at position %d in: %s' %
                             (i, value))
        elif value[i] == '\\':
            try:
                escape_sequence = value[i]
                if value[i + 1] in ('"', '\\'):
                    escape_sequence = value[i:i + 2]
                    string += str(value[i + 1])
                    i += 2
                else:
                    escape_sequence = value[i:i + 4]
                    string += int2byte(int(value[i + 1:i + 4]))
                    i += 4
            except:
                raise ValueError('Invalid escape sequence: %s' %
                                 escape_sequence)
        else:
            if 32 <= ord(value[i]) <= 126:
                string += value[i]
                i += 1
            else:
                raise ValueError('Invalid character at position %d in: %s' %
                                 (i, value))
    return string, len(value)
Ejemplo n.º 36
0
def gs_k_barcode(symbology, data, **kwargs):
    """Build standard ESC/POS barcode through ``GS k`` command set. Keyword
    arguments can be used to configure barcode height, bar widths and HRI
    positioning. User applications should not use this function. This function
    is provided as an ESC/POS "standard barcode command set" to be used by
    specific implementations.

    :param bytes symbology: The symbology to build. Should be one of the
        constants in :attr:`NUL_TERM_SYMBOLOGIES` or :attr:`SYMBOLOGIES`.

    :param bytes data: The barcode data. You should draw up your data
        according to the symbology. If you do not want to worry about data
        formating then you should use barcode methods provided by the
        reference ESC/POS implementation
        :class:`~escpos.impl.epson.GenericESCPOS` instead of this function.

    :param barcode_height: Optional.
    :param barcode_width: Optional.
    :param barcode_hri: Optional.

    :return: A list of commands (bytes), ready to be sent to the device.
    :rtype: list

    """
    commands = gs_k_barcode_configure(**kwargs)

    if symbology in (k for k, v in NUL_TERM_SYMBOLOGIES):
        commands.append(
                b'\x1D\x6B'
                + symbology
                + data
                + b'\x00'
            )
    else:
        size = len(data)
        commands.append(
                b'\x1D\x6B'
                + symbology
                + six.int2byte(size)
                + data
                + b'\x00'
            )

    return commands
Ejemplo n.º 37
0
    def new_order_message(self, clientid):
        file = '%s_%s_basicvwap.csv' % (stock_account, strategy)
        test_type = all
        strategy_config_path = os.path.join(version_path,
                                            '%s_Config' % test_type)
        df = pd.read_csv(os.path.join(strategy_config_path, file),
                         dtype={'target': str},
                         index_col='clientid')
        # print df

        msg_algo = AllProtoMsg_pb2.AlgoParameter()
        msg_algo.AlgoNameWired = 13

        msg = AllProtoMsg_pb2.NewOrderMsg()

        msg_order_child = AllProtoMsg_pb2.Order()
        msg_order_child.TradeTypeWire = df.at[clientid, 'trade_type']
        msg_order_child.TypeWire = df.at[clientid, 'type']
        msg_order_child.PropertyWire = 0
        msg_order_child.Qty = df.at[clientid, 'order_qty']
        msg_order_child.Price = self.get_target_pre_price(df.at[clientid,
                                                                'target'])
        msg_order_child.DirectionWire = df.at[clientid, 'direction']
        msg_order_child.OrderAccount = stock_account
        msg_order_child.UserID = fund_name
        msg_order_child.StrategyID = strategy
        msg_order_child.CliOrdID = clientid
        msg_order_child.Parameters.CopyFrom(msg_algo)

        msg_child = AllProtoMsg_pb2.NewOrderMsg()
        msg_child = msg.childOrdersWire.add()
        msg_child.TargetID = random.randint(0, 99)
        msg_child.Order.CopyFrom(msg_order_child)
        msg_child.Symbol = df.at[clientid, 'target']

        msg.TargetID = 0
        msg.Order.CopyFrom(msg_order_child)
        msg.Symbol = df.at[clientid, 'target']
        # print msg

        msg_str = msg.SerializeToString()
        msg_type = 4
        msg_list = [six.int2byte(msg_type), msg_str]
        return msg_list
Ejemplo n.º 38
0
    def getAssertion(self, facet, app_id, challenge, key, touch_byte=1):
        """
        signData = {
            'version': "U2F_V2",
            'challenge': websafe_encode(self.challenge),
            'appId': self.binding.app_id,
            'keyHandle': websafe_encode(self.binding.key_handle),
        }
        """

        key = RegisteredKey.wrap(key)

        if key.version != "U2F_V2":
            raise ValueError("Unsupported U2F version: %s" % key.version)

        if key.keyHandle not in self.keys:
            raise ValueError("Unknown key handle!")

        # Client data
        client_data = ClientData(typ=Type.SIGN.value,
                                 challenge=challenge,
                                 origin=facet)
        client_data = client_data.json.encode('utf-8')
        client_param = sha_256(client_data)

        # Unwrap:
        priv_key, app_param = self.keys[key.keyHandle]

        # Increment counter
        self.counter += 1

        # Create signature
        touch = six.int2byte(touch_byte)
        counter = struct.pack('>I', self.counter)

        data = app_param + touch + counter + client_param
        signer = priv_key.signer(ec.ECDSA(hashes.SHA256()))
        signer.update(data)
        signature = signer.finalize()
        raw_response = touch + counter + signature

        return SignResponse(clientData=websafe_encode(client_data),
                            signatureData=websafe_encode(raw_response),
                            keyHandle=key['keyHandle'])
Ejemplo n.º 39
0
    def read_sicard(self, reftime=None):
        """Reads out the SI Card currently inserted into the station. The card must be
        detected with poll_sicard before."""

        if not self.proto_config['ext_proto']:
            raise SIReaderException(
                'This command only supports stations in "Extended Protocol" '
                'mode. Switch mode first')

        if not self.proto_config['mode'] == SIReader.M_READOUT:
            raise SIReaderException(
                "Station must be in 'Read SI cards' operating mode! Change operating mode first."
            )

        if self.cardtype == 'SI5':
            raw_data = self._send_command(SIReader.C_GET_SI5, b'')[1]
        elif self.cardtype == 'SI6':
            raw_data = self._send_command(SIReader.C_GET_SI6,
                                          SIReader.P_SI6_CB)[1][1:]
            raw_data += self._read_command()[1][1:]
            raw_data += self._read_command()[1][1:]
            return SIReader._decode_carddata(raw_data, self.cardtype)
        elif self.cardtype in ('SI8', 'SI9'):
            raw_data = b''
            for b in range(SIReader.CARD[self.cardtype]['BC']):
                raw_data += self._send_command(SIReader.C_GET_SI9,
                                               int2byte(b))[1][1:]

            return SIReader._decode_carddata(raw_data, self.cardtype)
        elif self.cardtype == 'SI10':
            # Reading out SI10 cards block by block proved to be unreliable and slow
            # Thus reading with C_GET_SI9 and block number 8 = P_SI6_CB like SI6
            # cards
            raw_data = self._send_command(SIReader.C_GET_SI9,
                                          SIReader.P_SI6_CB)[1][1:]
            raw_data += self._read_command()[1][1:]
            raw_data += self._read_command()[1][1:]
            raw_data += self._read_command()[1][1:]
            raw_data += self._read_command()[1][1:]
        else:
            raise SIReaderException('No card in the device.')

        return SIReader._decode_carddata(raw_data, self.cardtype, reftime)
Ejemplo n.º 40
0
    def _generate_signature(self, signature_plain, iv, lib_path="encrypt.so"):
        if self._signature_lib is None:
            self.activate_signature(lib_path)
        self._signature_lib.argtypes = [
            ctypes.c_char_p, ctypes.c_size_t, ctypes.c_char_p,
            ctypes.POINTER(ctypes.POINTER(ctypes.c_ubyte))
        ]
        self._signature_lib.restype = ctypes.c_int

        rounded_size = len(signature_plain) + (256 -
                                               (len(signature_plain) % 256))
        total_size = rounded_size + 5
        output = ctypes.POINTER(ctypes.c_ubyte * total_size)()
        output_size = self._signature_lib.encrypt(signature_plain,
                                                  len(signature_plain), iv,
                                                  ctypes.byref(output))
        signature = b''.join(
            list(map(lambda x: six.int2byte(x), output.contents)))
        return signature
Ejemplo n.º 41
0
    def test_getbytes(self):
        # Test getbytes method.
        all_bytes = b''.join(six.int2byte(n) for n in range(256))

        #Open not supported, changed Test
        self.fs.setbytes('foo', all_bytes)
        # ~ with self.fs.open('foo', 'wb') as f:
        # ~ f.write(all_bytes)
        self.assertEqual(self.fs.getbytes('foo'), all_bytes)
        _all_bytes = self.fs.getbytes('foo')
        self.assertIsInstance(_all_bytes, bytes)
        self.assertEqual(_all_bytes, all_bytes)

        with self.assertRaises(errors.ResourceNotFound):
            self.fs.getbytes('foo/bar')

        self.fs.makedir('baz')
        with self.assertRaises(errors.FileExpected):
            self.fs.getbytes('baz')
Ejemplo n.º 42
0
 def test_setdefault(self):
     for flags in xrange(16):
         pn = MemoryPatriciaAuthTree()
         pn.update((k, v) for k, v in six.iteritems(SCENARIOS[flags])
                   if k != 'hash_')
         for key, value in six.iteritems(ADDRESS_TO_VALUE):
             pn2 = MemoryPatriciaAuthTree()
             pn2.update(pn)
             if flags & ord(value):
                 pn2.setdefault(key, six.int2byte(ord(value) + 1))
                 self.assertIn(key, pn2)
                 self.assertEqual(pn2[key], value)
                 self.assertEqual(pn2.hash, SCENARIOS[flags]['hash_'])
             else:
                 pn2.setdefault(key, value)
                 self.assertIn(key, pn2)
                 self.assertEqual(pn2[key], value)
                 self.assertEqual(pn2.hash,
                                  SCENARIOS[flags | ord(value)]['hash_'])
Ejemplo n.º 43
0
 def authenticate_owner_password(self, password):
     # Algorithm 3.7
     password = (password + self.PASSWORD_PADDING)[:32]
     hash = md5.md5(password)
     if self.r >= 3:
         for _ in range(50):
             hash = md5.md5(hash.digest())
     n = 5
     if self.r >= 3:
         n = self.length // 8
     key = hash.digest()[:n]
     if self.r == 2:
         user_password = ARC4.new(key).decrypt(self.o)
     else:
         user_password = self.o
         for i in range(19, -1, -1):
             k = b''.join(six.int2byte(c ^ i) for c in six.iterbytes(key))
             user_password = ARC4.new(k).decrypt(user_password)
     return self.authenticate_user_password(user_password)
Ejemplo n.º 44
0
 def check(self, fmt, value):
     from random import randrange
     # build a buffer which is surely big enough to contain what we need
     # and check:
     #   1) that we correctly write the bytes we expect
     #   2) that we do NOT write outside the bounds
     #
     pattern = [six.int2byte(randrange(256)) for _ in range(256)]
     pattern = b''.join(pattern)
     buf = bytearray(pattern)
     buf2 = bytearray(pattern)
     offset = 16
     pack_into(ord(fmt), buf, offset, value)
     struct.pack_into(fmt, buf2, offset, value)
     assert buf == buf2
     #
     # check that it raises if it's out of bound
     out_of_bound = 256-struct.calcsize(fmt)+1
     pytest.raises(IndexError, "pack_into(ord(fmt), buf, out_of_bound, value)")
Ejemplo n.º 45
0
def send_order_info_request_msg(socket):
    msg = AllProtoMsg_pb2.OrderInfoRequestMsg()
    msg.IsAll = False
    task_logger.info("Send OrderInfoRequestMsg")
    msg_str = msg.SerializeToString()
    msg_type = 7
    msg_list = [six.int2byte(msg_type), msg_str]

    socket.send_multipart(msg_list)
    recv_message = socket.recv_multipart()
    task_logger.info("Recv OrderInfoResponseMsg.")
    orderinfo_msg = AllProtoMsg_pb2.OrderInfoResponseMsg()
    orderinfo_msg.ParseFromString(zlib.decompress(recv_message[1]))

    order_msg_list = []
    for order_info in orderinfo_msg.Orders:
        order_msg_list.append(order_info)
        # print order_msg_list
    return order_msg_list
Ejemplo n.º 46
0
 def encode(self, b64=False):
     """Encode the payload for transmission."""
     encoded_payload = b''
     for pkt in self.packets:
         encoded_packet = pkt.encode(b64=b64)
         packet_len = len(encoded_packet)
         if b64:
             encoded_payload += str(packet_len).encode('utf-8') + b':' + encoded_packet
         else:
             binary_len = b''
             while packet_len != 0:
                 binary_len = six.int2byte(packet_len % 10) + binary_len
                 packet_len = int(packet_len / 10)
             if not pkt.binary:
                 encoded_payload += b'\0'
             else:
                 encoded_payload += b'\1'
             encoded_payload += binary_len + b'\xff' + encoded_packet
     return encoded_payload
def __send_instrument_info_request_msg(socket):
    msg = AllProtoMsg_pb2.InstrumentInfoRequestMsg()
    msg.IsAll = True
    msg.IncludeStaticInfo = True
    msg_str = msg.SerializeToString()
    msg_type = 2
    msg_list = [six.int2byte(msg_type), msg_str]

    print "Send InstrumentInfoRequestMsg."
    socket.send_multipart(msg_list)
    recv_message = socket.recv_multipart()
    print "Recv InstrumentInfoResponseMsg."
    instrument_info_msg = AllProtoMsg_pb2.InstrumentInfoResponseMsg()
    instrument_info_msg.ParseFromString(zlib.decompress(recv_message[1]))

    targets_msg_dict = dict()
    for instrument_msg in instrument_info_msg.Targets:
        targets_msg_dict[instrument_msg.id] = instrument_msg
    return targets_msg_dict
Ejemplo n.º 48
0
def serialize_number(x, fmt=SER_BINARY, outlen=None):
    """ Serializes `x' to a string of length `outlen' in format `fmt' """
    ret = b''
    if fmt == SER_BINARY:
        while x:
            x, r = divmod(x, 256)
            ret = six.int2byte(int(r)) + ret
        if outlen is not None:
            assert len(ret) <= outlen
            ret = ret.rjust(outlen, b'\0')
        return ret
    assert fmt == SER_COMPACT
    while x:
        x, r = divmod(x, len(COMPACT_DIGITS))
        ret = COMPACT_DIGITS[r:r + 1] + ret
    if outlen is not None:
        assert len(ret) <= outlen
        ret = ret.rjust(outlen, COMPACT_DIGITS[0:1])
    return ret
Ejemplo n.º 49
0
 def init_time_card(self, time=datetime.today()):
     """Initialize card for writing time to base station.
     @param time: Time for base station (default current time).
     """
     params = b''
     params += int2byte(time.year - 2000)
     params += int2byte(time.month)
     params += int2byte(time.day)
     params += int2byte(time.hour)
     params += int2byte(time.minute)
     params += int2byte(time.second)
     self._send_command(Sportiduino.CMD_INIT_TIMECARD,
                        params,
                        wait_response=True)
Ejemplo n.º 50
0
    def unread(self, c):
        """Unread the given character, byte, or code point.

        If this is a unicode buffer and the input is an int or byte, it will be interpreted as an ordinal representing
        a unicode code point.

        If this is a binary buffer, the input must be a byte or int; a unicode character will raise an error.
        """
        if self.position < 1:
            raise IndexError('Cannot unread an empty buffer queue.')
        if isinstance(c, six.text_type):
            if not self.is_unicode:
                BufferQueue._incompatible_types(self.is_unicode, c)
        else:
            c = self.__chr(c)
        num_code_units = self.is_unicode and len(c) or 1
        if self.__offset == 0:
            if num_code_units == 1 and six.PY3:
                if self.is_unicode:
                    segment = c
                else:
                    segment = six.int2byte(c)
            else:
                segment = c
            self.__segments.appendleft(segment)
        else:
            self.__offset -= num_code_units

            def verify(ch, idx):
                existing = self.__segments[0][self.__offset + idx]
                if existing != ch:
                    raise ValueError(
                        'Attempted to unread %s when %s was expected.' %
                        (ch, existing))

            if num_code_units == 1:
                verify(c, 0)
            else:
                for i in range(num_code_units):
                    verify(c[i], i)
        self.__size += num_code_units
        self.position -= num_code_units
Ejemplo n.º 51
0
    def set_mgm_key(self, new_key, touch=False, store_on_device=False):
        # If the key should be protected by PIN and no key is given,
        # we generate a random key.
        if store_on_device and not new_key:
            new_key = generate_random_management_key()

        if store_on_device or (not store_on_device and self.has_stored_key):
            # Ensure we have access to protected data before overwriting key
            try:
                self._init_pivman_protected()
            except Exception as e:
                logger.debug('Failed to initialize protected pivman data',
                             exc_info=e)

                if store_on_device:
                    raise

        # Set the new management key
        self.send_cmd(
            INS.SET_MGMKEY, 0xff, 0xfe if touch else 0xff,
            six.int2byte(ALGO.TDES) + Tlv(SLOT.CARD_MANAGEMENT, new_key))
        if self.has_derived_key:
            # Clear salt for old derived keys.
            self._pivman_data.salt = None
        # Set flag for stored or not stored key.
        self._pivman_data.mgm_key_protected = store_on_device
        # Update readable pivman data
        self.put_data(OBJ.PIVMAN_DATA, self._pivman_data.get_bytes())
        if store_on_device:
            # Store key in protected pivman data
            self._pivman_protected_data.key = new_key
            self.put_data(OBJ.PIVMAN_PROTECTED_DATA,
                          self._pivman_protected_data.get_bytes())
        elif not store_on_device and self.has_stored_key:
            # If new key should not be stored and there is an old stored key,
            # try to clear it.
            try:
                self._pivman_protected_data.key = None
                self.put_data(OBJ.PIVMAN_PROTECTED_DATA,
                              self._pivman_protected_data.get_bytes())
            except APDUError as e:
                logger.debug("No PIN provided, can't clear key..", exc_info=e)
Ejemplo n.º 52
0
def aes_encrypt(key, iv, data, mode=AES.MODE_CBC):
    """
    encrypts the given data with key/iv

    :param key: The encryption key
    :type key: binary string
    :param iv: The initialization vector
    :type iv: binary string
    :param data: The cipher text
    :type data: bytes
    :param mode: The AES MODE
    :return: plain text in binary data
    :rtype: bytes
    """
    aes = AES.new(key, mode, iv)
    # pad data
    num_pad = aes.block_size - (len(data) % aes.block_size)
    data = data + six.int2byte(num_pad) * num_pad
    output = aes.encrypt(data)
    return output
Ejemplo n.º 53
0
def b58_encode(b, errors='strict'):
    "Encode bytes to a base58-encoded string."
    len_ = len(b)

    # Convert big-endian bytes to integer
    n = BigInteger.deserialize(StringIO(b), len_)

    # Divide that integer into base58
    res = []
    while n > 0:
        n, r = divmod(n, 58)
        res.append(b58_digits[r])
    res = ''.join(res[::-1])

    # Encode leading zeros as base58 zeros
    pad = 0
    for c in b:
        if c == six.int2byte(0): pad += 1
        else: break
    return (b58_digits[0] * pad + res, len_)
Ejemplo n.º 54
0
def send_order_info_request_msg2(socket, last_update=None):
    msg = AllProtoMsg_pb2.OrderInfoRequestMsg()
    if last_update is not None:
        msg.IsAll = False
        msg.LastUpdateTime.scale = last_update.scale
        msg.LastUpdateTime.value = last_update.value
    else:
        msg.IsAll = True

    task_logger.info("Send OrderInfoRequestMsg")
    msg_str = msg.SerializeToString()
    msg_type = 7
    msg_list = [six.int2byte(msg_type), msg_str]

    socket.send_multipart(msg_list)
    recv_message = socket.recv_multipart()
    task_logger.info("Recv OrderInfoResponseMsg.")
    orderinfo_msg = AllProtoMsg_pb2.OrderInfoResponseMsg()
    orderinfo_msg.ParseFromString(zlib.decompress(recv_message[1]))
    return orderinfo_msg
Ejemplo n.º 55
0
        def send_command(self, serial, code, parameters=None, wait_response=True, timeout=None):
            if parameters is None:
                parameters = b''
            data_len = len(parameters)
            if data_len > self.MAX_DATA_LEN:
                raise SportiduinoException("Command too long: %d" % data_len)
            cmd_string = code + int2byte(data_len) + parameters

            cs = self._checsum(cmd_string)
            cmd = self._start_byte + cmd_string + cs

            self._log_debug("=> 0x %s" % ' '.join(('%02x' % byte2int(c)) for c in cmd))

            serial.flushInput()
            serial.write(cmd)

            if wait_response:
                return self._read_response(serial, timeout)

            return None, None
Ejemplo n.º 56
0
    def _send_command(self, command, parameters, **kw):
        try:
            if self._serial.inWaiting() != 0:
                raise SIReaderException('Input buffer must be empty before sending command. Currently %s bytes in the input buffer.' % self._serial.inWaiting())
            command_string = command + int2byte(len(parameters)) + parameters
            crc = SIReader._crc(command_string)
            cmd = SIReader.STX + command_string + crc + SIReader.ETX
            if not kw.get('skipwakeup'):
                cmd = SIReader.WAKEUP + SIReader.STX + cmd
            if self._debug:
                print("==>> send '%s' at %d bps" % (hexlify(cmd), self._serial.baudrate))
            self._serial.write(cmd)
        except (SerialException, OSError) as  msg:
            raise SIReaderException('Could not send command: %s' % msg)

        if self._logfile:
            self._logfile.write('s %s %s\n' % (datetime.now(), cmd))
            self._logfile.flush()
            os.fsync(self._logfile)
        return self._read_command()
Ejemplo n.º 57
0
def send_subscribetradeserverinfo_request_msg(socket, tradeserver_info_list):
    msg = AllProtoMsg_pb2.SubscribeTradeServerInfoRequestMsg()

    # msg.TradeServerInfo = tradeserver_info_list
    for tradeserver_info in tradeserver_info_list:
        msg.TradeServerInfo.append(tradeserver_info)

    custom_log.log_debug_task("Send SubscribeTradeServerInfoRequestMsg")
    msg_str = msg.SerializeToString()
    msg_type = const.MSG_TYPEID_ENUMS.SubscribeTradeServerInfoRequest
    msg_list = [six.int2byte(msg_type), msg_str]

    socket.send_multipart(msg_list)
    recv_message = socket.recv_multipart()
    custom_log.log_debug_task("Recv SubscribeTradeServerInfoResponseMsg.")
    subscribetradeserverinfo_msg = AllProtoMsg_pb2.SubscribeTradeServerInfoResponseMsg(
    )
    subscribetradeserverinfo_msg.ParseFromString(
        zlib.decompress(recv_message[1]))
    return subscribetradeserverinfo_msg
Ejemplo n.º 58
0
def _udp_checksum_pseudo_header(src_addr, dst_addr, msg_len):
    """Return pseudo-header for UDP checksum.

    :type src_addr: bytes
    :param src_addr: Source IP address -- 4 bytes.

    :type dst_addr: bytes
    :param dst_addr: Destination IP address -- 4 bytes.

    :param msg_len: Length of UDP message (not including IPv4 header).
    :type msg_len: int

    :return: UDP pseudo-header
    :rtype: bytes
    """
    return (src_addr
            + dst_addr
            + six.binary_type(b"\x00")
            + six.int2byte(ip_constants.IPV4_PROTOCOL_UDP)
            + struct.pack(">H", msg_len))
Ejemplo n.º 59
0
 def __init__(self, ix, port_number):
     # The remote port number
     self.port_number = port_number
     # The websocket channel byte number for this port
     self.channel = six.int2byte(ix * 2)
     # A socket pair is created to provide a means of translating the data flow
     # between the python application and the kubernetes websocket. The self.python
     # half of the socket pair is used by the _proxy method to receive and send data
     # to the running python application.
     s, self.python = socket.socketpair()
     # The self.socket half of the pair is used by the python application to send
     # and receive data to the eventual pod port. It is wrapped in the _Socket class
     # because a socket pair is an AF_UNIX socket, not a AF_INET socket. This allows
     # intercepting setting AF_INET socket options that would error against an AF_UNIX
     # socket.
     self.socket = self._Socket(s)
     # Data accumulated from the websocket to be sent to the python application.
     self.data = b''
     # All data sent from kubernetes on the port error channel.
     self.error = None
Ejemplo n.º 60
0
    def respond_to_client_terminate(self, message):
        # Verify length
        if len(message) != 2 + self._mac_length:
            _logger.info('Invalid length of client terminate')
            return

        # Verify MAC
        if not self.verify_mac(message):
            _logger.info('Invalid MAC on client termiante')
            return

        # Verify sequence number
        if not self.validate_and_update_others_seqnum(message):
            _logger.info('Invalid sequence number on client terminate')
            return

        self.state = ServerState.inactive
        msg = six.int2byte(Message.server_terminate)
        mac = self.get_mac(msg)
        self._send(msg + mac)