def setUp(self):
        self.choice0 = DummyChoice(name='octets2', value=bytes([1, 2, 3, 4]))

        self.seq_1 = DummySequence(
            value={
                'oid0': ObjectIdentifier("4.5.6.7"),
                'bool1': True,
                'octets2': bytes([9, 10, 11, 12, 13])
            })

        self.choice2 = DummyChoice(name='oid0',
                                   value=ObjectIdentifier("14.15.16.17"))

        self.seq_3 = DummySequence(
            value={
                'oid0': ObjectIdentifier("18.19.20.21"),
                'bool1': False,
                'octets2': bytes([22, 23, 24, 25])
            })

        self.nested = NestedSequence(
            value={
                'choice0': self.choice0,
                'sequence1': self.seq_1,
                'choice2': self.choice2,
                'sequence3': self.seq_3
            })
Ejemplo n.º 2
0
def OidFromAttid(prefixTable, attr):
    # separate the ATTRTYP into two parts
    upperWord = attr // 65536
    lowerWord = attr % 65536

    # search in the prefix table to find the upperWord, if found,
    # construct the binary OID by appending lowerWord to the end of
    # found prefix.

    binaryOID = None
    for j, item in enumerate(prefixTable):
        if item['ndx'] == upperWord:
            binaryOID = item['prefix']['elements'][:item['prefix']['length']]
            if lowerWord < 128:
                binaryOID.append(pack('B', lowerWord))
            else:
                if lowerWord >= 32768:
                    lowerWord -= 32768
                binaryOID.append(pack('B', (((lowerWord // 128) % 128) + 128)))
                binaryOID.append(pack('B', (lowerWord % 128)))
            break

    if binaryOID is None:
        return None

    return str(
        ObjectIdentifier.load(b'\x06' + pack('B', (len(binaryOID))) +
                              b''.join(binaryOID)))
Ejemplo n.º 3
0
def to_int_tuple(value: OidValue) -> Tuple[int, ...]:
    """
    Convert several types to a tuple of ints.
    """
    if isinstance(value, ObjectIdentifier):
        return value.value
    if isinstance(value, bytes):
        value = Asn1ObjId.load(value)
    if isinstance(value, Asn1ObjId):
        value = value.dotted
    if isinstance(value, str):
        value = value.split(".")

    result = tuple(map(int, value))

    # X.660 6.2.1
    for i in result:
        if i < 0:
            raise ValueError("OID arcs cannot be negative")

    # X.660 6.2.1 a)
    if len(result) > 0 and result[0] > 2:
        raise ValueError("Root arc must be 0, 1 or 2")

    # X.660 6.2.1 b)
    if len(result) > 1 and result[0] < 2 and result[1] > 39:
        raise ValueError("Second arc must be in [0, 39] for roots 0 and 1")

    return result
Ejemplo n.º 4
0
    def test_encoding_can_be_decoded_1(self):
        dummy_choice = DummyChoice(name='oid0', value=ObjectIdentifier("1.2.3.4"))

        dummy_dump = dummy_choice.dump()

        decoded = DummyChoice.load(dummy_dump)

        self.assertEqual(dummy_choice.native, decoded.native)
Ejemplo n.º 5
0
    def test_bad_oid(self):
        _, _, der = pem.unarmor(rsa_pem)
        dc = TSSPrivKey._tssprivkey_der.load(der)
        dc["type"] = ObjectIdentifier("1.2.3.4")
        badder = dc.dump()

        with self.assertRaises(TypeError) as e:
            TSSPrivKey.from_der(badder)
        self.assertEqual(str(e.exception), "unsupported key type")
Ejemplo n.º 6
0
    def test_encoding_can_be_decoded(self):
        dummy_seq = DummySequence(value={'oid0':ObjectIdentifier("1.2.3.4"),
                                         'bool1':True,
                                         'octets2':bytes([5,6,7,8])})

        dummy_dump = dummy_seq.dump()

        decoded = DummySequence.load(dummy_dump)

        self.assertEqual(dummy_seq.native, decoded.native)
Ejemplo n.º 7
0
    def test_encoding_can_be_decoded_1(self):
        dummy_seq = DummySequence(value={'oid0':ObjectIdentifier("1.2.3.4"),
                                         # Note that the 2nd element, which is also optional is omitted
                                         'octets2':bytes([5,6,7,8])})

        dummy_dump = dummy_seq.dump()

        decoded = DummySequence.load(dummy_dump)

        self.assertEqual(dummy_seq.native, decoded.native)

        self.assertEqual(decoded.native['oid0'], "1.2.3.4")
        self.assertEqual(decoded.native['octets2'], bytes([5,6,7,8]))
Ejemplo n.º 8
0
	def from_buffer(buff):
		
		start = buff.read(1)
		if start != b'\x60':
			raise Exception('Incorrect token data!')
		remaining_length = KRB5_MECH_INDEP_TOKEN.decode_length_buffer(buff)
		token_data = buff.read(remaining_length)
		
		buff = io.BytesIO(token_data)
		pos = buff.tell()
		buff.read(1)
		oid_length = KRB5_MECH_INDEP_TOKEN.decode_length_buffer(buff)
		buff.seek(pos)
		token_oid = ObjectIdentifier.load(buff.read(oid_length+2))
		
		return KRB5_MECH_INDEP_TOKEN(buff.read(), str(token_oid), remlen = remaining_length)
Ejemplo n.º 9
0
def MakeAttid(prefixTable, oid):
	# get the last value in the original OID: the value * after the last '.'
	lastValue = int(oid.split('.')[-1])

	# convert the dotted form of OID into a BER encoded binary * format.
	# The BER encoding of OID is described in section * 8.19 of [ITUX690]
	binaryOID = ObjectIdentifier(oid).dump()[2:]


	# get the prefix of the OID
	if lastValue < 128:
		oidPrefix = list(binaryOID[:-1])
	else:
		oidPrefix = list(binaryOID[:-2])

	# search the prefix in the prefix table, if none found, add
	# one entry for the new prefix.
	fToAdd = True
	pos = len(prefixTable)
	for j, item in enumerate(prefixTable):
		if item['prefix']['elements'] == oidPrefix:
			fToAdd = False
			pos = j
			break

	if fToAdd is True:
		entry = PrefixTableEntry()
		entry['ndx'] = pos
		entry['prefix']['length'] = len(oidPrefix)
		entry['prefix']['elements'] = oidPrefix
		prefixTable.append(entry)

	# compose the attid
	lowerWord = lastValue % 16384
	if lastValue >= 16384:
		# mark it so that it is known to not be the whole lastValue
		lowerWord += 32768

	upperWord = pos

	attrTyp = ATTRTYP()
	attrTyp['Data'] = (upperWord << 16) + lowerWord
	return attrTyp
Ejemplo n.º 10
0
	def to_bytes(self):
		t = ObjectIdentifier(self.oid).dump() + self.data
		t = b'\x60' + KRB5_MECH_INDEP_TOKEN.encode_length(len(t)) + t
		return t[:-len(self.data)] , self.data
Ejemplo n.º 11
0
    def test_encoding_does_not_throw(self):
        dummy_choice = DummyChoice(name='oid0', value=ObjectIdentifier("1.2.3.4"))

        dummy_choice.dump()  # This should not throw an exception
Ejemplo n.º 12
0
    def test_encoding_does_not_throw(self):
        dummy_seq = DummySequence(value={'oid0':ObjectIdentifier("1.2.3.4"),
                                         'bool1':True,
                                         'octets2':bytes([5,6,7,8])})

        dummy_seq.dump()  # This should not throw an exception
Ejemplo n.º 13
0
    nameAlg=TPM2_ALG.SHA256,
    objectAttributes=TPMA_OBJECT.USERWITHAUTH
    | TPMA_OBJECT.SIGN_ENCRYPT
    | TPMA_OBJECT.NODA
    | TPMA_OBJECT.FIXEDTPM
    | TPMA_OBJECT.FIXEDPARENT
    | TPMA_OBJECT.SENSITIVEDATAORIGIN,
    authPolicy=b"",
    parameters=TPMU_PUBLIC_PARMS(eccDetail=TPMS_ECC_PARMS(
        symmetric=TPMT_SYM_DEF_OBJECT(algorithm=TPM2_ALG.NULL),
        scheme=TPMT_ECC_SCHEME(scheme=TPM2_ALG.NULL),
        kdf=TPMT_KDF_SCHEME(scheme=TPM2_ALG.NULL),
    ), ),
)

_loadablekey_oid = ObjectIdentifier("2.23.133.10.1.3")


# _BooleanOne is used to encode True in the same way as tpm2-tss-engine
class _BooleanOne(Boolean):
    def set(self, value):
        self._native = bool(value)
        self.contents = b"\x00" if not value else b"\x01"
        self._header = None
        if self._trailer != b"":
            self._trailer = b""


class TSSPrivKey(object):
    """TSSPrivKey is class to create/load keys for/from tpm2-tss-engine / tpm2-openssl.
Ejemplo n.º 14
0
class AlgorithmObjectIdentifiers(enum.Enum):
    ecdsa_with_sha256_secp192r1     = ObjectIdentifier("2.16.840.1.114513.1.0")
    ecdsa_with_sha256_secp224r1     = ObjectIdentifier("2.16.840.1.114513.1.1")
    ecdsa_with_sha256_sect233k1     = ObjectIdentifier("2.16.840.1.114513.1.2")
    ecdsa_with_sha256_sect233r1     = ObjectIdentifier("2.16.840.1.114513.1.3")
    ecqv_with_sha256_secp192r1      = ObjectIdentifier("2.16.840.1.114513.1.4")
    ecqv_with_sha256_secp224r1      = ObjectIdentifier("2.16.840.1.114513.1.5")
    ecqv_with_sha256_sect233k1      = ObjectIdentifier("2.16.840.1.114513.1.6")
    ecqv_with_sha256_sect233r1      = ObjectIdentifier("2.16.840.1.114513.1.7")
    rsa_with_sha256                 = ObjectIdentifier("2.16.840.1.114513.1.8")
    ecdsa_with_sha256_secp256r1     = ObjectIdentifier("2.16.840.1.114513.1.9")
    ecqv_with_sha256_secp256r1      = ObjectIdentifier("2.16.840.1.114513.1.10")
Ejemplo n.º 15
0
        decoded_certificate = Certificate.load(certificate_bytes)
        return self.verify(decoded_certificate)

if __name__ == "__main__":
    subject = Name()
    subject[0] = AttributeValue(name='country', value=PrintableString(value='US'))
    subject[1] = AttributeValue(name='organization', value=UTF8String(value='ACME corp.'))
    subject[2] = AttributeValue(name='locality', value=UTF8String(value='Fairfield'))

    pubkey = contentbytes_from_pem_file("public.pem")
    builder = CertificateBuilder(subject, pubkey)

    builder.version = 0
    # builder.serial_number = None
    builder.ca_algorithm = "1.2.840.10045.4.3.2" # ECDSA with SHA256, see http://oid-info.com/get/1.2.840.10045.4.3.2
    builder.ca_algorithm_parameters = ObjectIdentifier(value="1.2.840.10045.3.1.7").dump()  # EC PARAMETERS as bytes
    # Parameters for the elliptic curve: http://oid-info.com/get/1.2.840.10045.3.1.7
    builder.self_signed = True #builder.issuer = subject
    builder.pk_algorithm = "1.2.840.10045.4.3.2"  # Same as cAAlgorithm
    builder.subject_key_id = int(1).to_bytes(1, byteorder='big')
    builder.key_usage = 0b10100000.to_bytes(1, byteorder='big') # digitalSignature & keyEncipherment bit set
    # builder.basicConstraints =  # Omit if end-entity cert
    builder.certificate_policy = "2.5.29.32.0"  # Anypolicy: http://www.oid-info.com/get/2.5.29.32.0
    builder.extended_key_usage = "2.16.840.1.114513.29.37" # Optional in ASN1 but explanation in spec says it MUST be present. Variant of X509 http://www.oid-info.com/get/2.5.29.37.0
    # builder.crl_distribution_point_uri =  IA5String(u'www.acme.com/')

    orig_cert = builder.build(signing_private_key_path="private.pem", debug=True)

    orig_dump = orig_cert.dump()
    orig_dump_hex = hexlify(orig_dump)
    print("Original certificate ({len}): {content}".format(content=orig_dump_hex, len=len(orig_dump)))