1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
|
###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Crossbar.io Technologies GmbH
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
###############################################################################
import os
import sys
from binascii import a2b_hex, b2a_hex
from unittest import skipIf
from twisted.internet.defer import inlineCallbacks
from twisted.trial.unittest import TestCase
from autobahn.wamp.cryptosign import HAS_CRYPTOSIGN
from autobahn.xbr import HAS_XBR
if HAS_XBR and HAS_CRYPTOSIGN:
from autobahn.wamp.cryptosign import CryptosignKey
from autobahn.xbr import make_w3, EthereumKey
from autobahn.xbr._secmod import SecurityModuleMemory
from autobahn.xbr import create_eip712_delegate_certificate, create_eip712_authority_certificate
from autobahn.xbr._eip712_delegate_certificate import EIP712DelegateCertificate
from autobahn.xbr._eip712_authority_certificate import EIP712AuthorityCertificate
from autobahn.xbr._eip712_certificate_chain import parse_certificate_chain
# https://web3py.readthedocs.io/en/stable/providers.html#infura-mainnet
HAS_INFURA = 'WEB3_INFURA_PROJECT_ID' in os.environ and len(os.environ['WEB3_INFURA_PROJECT_ID']) > 0
# TypeError: As of 3.10, the *loop* parameter was removed from Lock() since it is no longer necessary
IS_CPY_310 = sys.version_info.minor == 10
@skipIf(not os.environ.get('USE_TWISTED', False), 'only for Twisted')
@skipIf(not HAS_INFURA, 'env var WEB3_INFURA_PROJECT_ID not defined')
@skipIf(not (HAS_XBR and HAS_CRYPTOSIGN), 'package autobahn[encryption,xbr] not installed')
class TestEip712Certificate(TestCase):
def setUp(self):
self._gw_config = {
'type': 'infura',
'key': os.environ.get('WEB3_INFURA_PROJECT_ID', ''),
'network': 'mainnet',
}
self._w3 = make_w3(self._gw_config)
self._seedphrase = "avocado style uncover thrive same grace crunch want essay reduce current edge"
self._sm: SecurityModuleMemory = SecurityModuleMemory.from_seedphrase(self._seedphrase, num_eth_keys=5,
num_cs_keys=5)
@inlineCallbacks
def test_eip712_delegate_certificate(self):
yield self._sm.open()
delegate_eth_key: EthereumKey = self._sm[1]
delegate_cs_key: CryptosignKey = self._sm[6]
chainId = 1
verifyingContract = a2b_hex('0xf766Dc789CF04CD18aE75af2c5fAf2DA6650Ff57'[2:])
validFrom = 15124128
delegate = delegate_eth_key.address(binary=True)
csPubKey = delegate_cs_key.public_key(binary=True)
bootedAt = 1657579546469365046 # txaio.time_ns()
meta = 'Qme7ss3ARVgxv6rXqVPiikMJ8u2NLgmgszg13pYrDKEoiu'
cert_data = create_eip712_delegate_certificate(chainId=chainId, verifyingContract=verifyingContract,
validFrom=validFrom, delegate=delegate, csPubKey=csPubKey,
bootedAt=bootedAt, meta=meta)
# print('\n\n{}\n\n'.format(pformat(cert_data)))
cert_sig = yield delegate_eth_key.sign_typed_data(cert_data, binary=False)
self.assertEqual(cert_sig,
'2bd697b2bdb9bc2c2494e53e9440ddb3e8a596eedaad717f8ecdb732d091a7de48d72d9a26d7e092ec55c074979ab039f8e003acf80224819ff396c9529eb1d11b')
yield self._sm.close()
@inlineCallbacks
def test_eip712_authority_certificate(self):
yield self._sm.open()
trustroot_eth_key: EthereumKey = self._sm[0]
delegate_eth_key: EthereumKey = self._sm[1]
chainId = 1
verifyingContract = a2b_hex('0xf766Dc789CF04CD18aE75af2c5fAf2DA6650Ff57'[2:])
validFrom = 15124128
issuer = trustroot_eth_key.address(binary=True)
subject = delegate_eth_key.address(binary=True)
realm = a2b_hex('0xA6e693CC4A2b4F1400391a728D26369D9b82ef96'[2:])
capabilities = 3
meta = 'Qme7ss3ARVgxv6rXqVPiikMJ8u2NLgmgszg13pYrDKEoiu'
cert_data = create_eip712_authority_certificate(chainId=chainId, verifyingContract=verifyingContract,
validFrom=validFrom, issuer=issuer, subject=subject,
realm=realm, capabilities=capabilities, meta=meta)
# print('\n\n{}\n\n'.format(pformat(cert_data)))
cert_sig = yield trustroot_eth_key.sign_typed_data(cert_data, binary=False)
self.assertEqual(cert_sig,
'83590d4304cc5f6024d6a85ed2c511a60e804d609e4f498c8af777d5102c6d22657673e7b68876795e3c72f857b68e13cf616ee4c2ea559bceb344021bf977b61c')
yield self._sm.close()
@skipIf(not os.environ.get('USE_TWISTED', False), 'only for Twisted')
@skipIf(not HAS_INFURA, 'env var WEB3_INFURA_PROJECT_ID not defined')
@skipIf(not (HAS_XBR and HAS_CRYPTOSIGN), 'package autobahn[encryption,xbr] not installed')
class TestEip712CertificateChain(TestCase):
def setUp(self):
self._gw_config = {
'type': 'infura',
'key': os.environ.get('WEB3_INFURA_PROJECT_ID', ''),
'network': 'mainnet',
}
self._w3 = make_w3(self._gw_config)
self._seedphrase = "avocado style uncover thrive same grace crunch want essay reduce current edge"
self._sm: SecurityModuleMemory = SecurityModuleMemory.from_seedphrase(self._seedphrase, num_eth_keys=5,
num_cs_keys=5)
# HELLO.Details.authextra.certificates
#
self._certs_expected1 = [({'domain': {'name': 'WMP', 'version': '1'},
'message': {'bootedAt': 1657781999086394759,
'chainId': 1,
'csPubKey': '12ae0184b180e9a9c5e45be4a1afbce3c6491320063701cd9c4011a777d04089',
'delegate': '0xf5173a6111B2A6B3C20fceD53B2A8405EC142bF6',
'meta': 'Qme7ss3ARVgxv6rXqVPiikMJ8u2NLgmgszg13pYrDKEoiu',
'validFrom': 15139218,
'verifyingContract': '0xf766Dc789CF04CD18aE75af2c5fAf2DA6650Ff57'},
'primaryType': 'EIP712DelegateCertificate',
'types': {'EIP712DelegateCertificate': [{'name': 'chainId',
'type': 'uint256'},
{'name': 'verifyingContract',
'type': 'address'},
{'name': 'validFrom',
'type': 'uint256'},
{'name': 'delegate',
'type': 'address'},
{'name': 'csPubKey',
'type': 'bytes32'},
{'name': 'bootedAt',
'type': 'uint64'},
{'name': 'meta', 'type': 'string'}],
'EIP712Domain': [{'name': 'name', 'type': 'string'},
{'name': 'version', 'type': 'string'}]}},
'70726dda677cac8f21366f8023d17203b2f4f9099e954f9bebb2134086e2ac291d80ce038a1342a7748d4b0750f06b8de491561d581c90c99f1c09c91cfa7e191c'),
({'domain': {'name': 'WMP', 'version': '1'},
'message': {'capabilities': 12,
'chainId': 1,
'issuer': '0xf766Dc789CF04CD18aE75af2c5fAf2DA6650Ff57',
'meta': 'QmNbMM6TMLAgqBKzY69mJKk5VKvpcTtAtwAaLC2FV4zC3G',
'realm': '0xA6e693CC4A2b4F1400391a728D26369D9b82ef96',
'subject': '0xf5173a6111B2A6B3C20fceD53B2A8405EC142bF6',
'validFrom': 15139218,
'verifyingContract': '0xf766Dc789CF04CD18aE75af2c5fAf2DA6650Ff57'},
'primaryType': 'EIP712AuthorityCertificate',
'types': {'EIP712AuthorityCertificate': [{'name': 'chainId',
'type': 'uint256'},
{'name': 'verifyingContract',
'type': 'address'},
{'name': 'validFrom',
'type': 'uint256'},
{'name': 'issuer',
'type': 'address'},
{'name': 'subject',
'type': 'address'},
{'name': 'realm',
'type': 'address'},
{'name': 'capabilities',
'type': 'uint64'},
{'name': 'meta', 'type': 'string'}],
'EIP712Domain': [{'name': 'name', 'type': 'string'},
{'name': 'version', 'type': 'string'}]}},
'f031b2625ae7e32e7eec3a8fa09f4db3a43217f282b7695e5b09dd2e13c25dc679c1f3ce27b94a3074786f7f12183a2a275a00aea5a66b83c431281f1069bd841c'),
({'domain': {'name': 'WMP', 'version': '1'},
'message': {'capabilities': 63,
'chainId': 1,
'issuer': '0xf766Dc789CF04CD18aE75af2c5fAf2DA6650Ff57',
'meta': 'QmNbMM6TMLAgqBKzY69mJKk5VKvpcTtAtwAaLC2FV4zC3G',
'realm': '0xA6e693CC4A2b4F1400391a728D26369D9b82ef96',
'subject': '0xf766Dc789CF04CD18aE75af2c5fAf2DA6650Ff57',
'validFrom': 15139218,
'verifyingContract': '0xf766Dc789CF04CD18aE75af2c5fAf2DA6650Ff57'},
'primaryType': 'EIP712AuthorityCertificate',
'types': {'EIP712AuthorityCertificate': [{'name': 'chainId',
'type': 'uint256'},
{'name': 'verifyingContract',
'type': 'address'},
{'name': 'validFrom',
'type': 'uint256'},
{'name': 'issuer',
'type': 'address'},
{'name': 'subject',
'type': 'address'},
{'name': 'realm',
'type': 'address'},
{'name': 'capabilities',
'type': 'uint64'},
{'name': 'meta', 'type': 'string'}],
'EIP712Domain': [{'name': 'name', 'type': 'string'},
{'name': 'version', 'type': 'string'}]}},
'c3bcd7a3c3c45ae45a24cd7745db3b39c4113e6b71a4220f943f0969282246b4083ef61277bd7ba9e92c9a07b79869ce63bc6206986480f9c5daddb27b91bebe1b')]
@inlineCallbacks
def test_eip712_create_certificate_chain_manual(self):
yield self._sm.open()
# keys needed to create all certificates in certificate chain
#
trustroot_eth_key: EthereumKey = self._sm[0]
delegate_eth_key: EthereumKey = self._sm[1]
delegate_cs_key: CryptosignKey = self._sm[6]
# data needed for delegate certificate: cert1
#
chainId = 1 # self._w3.eth.chain_id
verifyingContract = a2b_hex('0xf766Dc789CF04CD18aE75af2c5fAf2DA6650Ff57'[2:])
validFrom = 15139218 # self._w3.eth.block_number
delegate = delegate_eth_key.address(binary=True)
csPubKey = delegate_cs_key.public_key(binary=True)
bootedAt = 1657781999086394759 # txaio.time_ns()
delegateMeta = 'Qme7ss3ARVgxv6rXqVPiikMJ8u2NLgmgszg13pYrDKEoiu'
# data needed for intermediate authority certificate: cert2
#
issuer_cert2 = trustroot_eth_key.address(binary=True)
subject_cert2 = delegate
realm_cert2 = a2b_hex('0xA6e693CC4A2b4F1400391a728D26369D9b82ef96'[2:])
capabilities_cert2 = EIP712AuthorityCertificate.CAPABILITY_PUBLIC_RELAY | EIP712AuthorityCertificate.CAPABILITY_PRIVATE_RELAY
meta_cert2 = 'QmNbMM6TMLAgqBKzY69mJKk5VKvpcTtAtwAaLC2FV4zC3G'
# data needed for root authority certificate: cert3
#
issuer_cert3 = trustroot_eth_key.address(binary=True)
subject_cert3 = issuer_cert3
realm_cert3 = a2b_hex('0xA6e693CC4A2b4F1400391a728D26369D9b82ef96'[2:])
capabilities_cert3 = EIP712AuthorityCertificate.CAPABILITY_ROOT_CA | EIP712AuthorityCertificate.CAPABILITY_INTERMEDIATE_CA | EIP712AuthorityCertificate.CAPABILITY_PUBLIC_RELAY | EIP712AuthorityCertificate.CAPABILITY_PRIVATE_RELAY | EIP712AuthorityCertificate.CAPABILITY_PROVIDER | EIP712AuthorityCertificate.CAPABILITY_CONSUMER
meta_cert3 = 'QmNbMM6TMLAgqBKzY69mJKk5VKvpcTtAtwAaLC2FV4zC3G'
# create delegate certificate
#
cert1_data = create_eip712_delegate_certificate(chainId=chainId, verifyingContract=verifyingContract,
validFrom=validFrom, delegate=delegate, csPubKey=csPubKey,
bootedAt=bootedAt, meta=delegateMeta)
cert1_sig = yield delegate_eth_key.sign_typed_data(cert1_data, binary=False)
cert1_data['message']['csPubKey'] = b2a_hex(cert1_data['message']['csPubKey']).decode()
cert1_data['message']['delegate'] = self._w3.toChecksumAddress(cert1_data['message']['delegate'])
cert1_data['message']['verifyingContract'] = self._w3.toChecksumAddress(
cert1_data['message']['verifyingContract'])
# create intermediate authority certificate
#
cert2_data = create_eip712_authority_certificate(chainId=chainId, verifyingContract=verifyingContract,
validFrom=validFrom, issuer=issuer_cert2,
subject=subject_cert2,
realm=realm_cert2, capabilities=capabilities_cert2,
meta=meta_cert2)
cert2_sig = yield trustroot_eth_key.sign_typed_data(cert2_data, binary=False)
cert2_data['message']['verifyingContract'] = self._w3.toChecksumAddress(
cert2_data['message']['verifyingContract'])
cert2_data['message']['issuer'] = self._w3.toChecksumAddress(cert2_data['message']['issuer'])
cert2_data['message']['subject'] = self._w3.toChecksumAddress(cert2_data['message']['subject'])
cert2_data['message']['realm'] = self._w3.toChecksumAddress(cert2_data['message']['realm'])
# create root authority certificate
#
cert3_data = create_eip712_authority_certificate(chainId=chainId, verifyingContract=verifyingContract,
validFrom=validFrom, issuer=issuer_cert3,
subject=subject_cert3,
realm=realm_cert3, capabilities=capabilities_cert3,
meta=meta_cert3)
cert3_sig = yield trustroot_eth_key.sign_typed_data(cert3_data, binary=False)
cert3_data['message']['verifyingContract'] = self._w3.toChecksumAddress(
cert3_data['message']['verifyingContract'])
cert3_data['message']['issuer'] = self._w3.toChecksumAddress(cert3_data['message']['issuer'])
cert3_data['message']['subject'] = self._w3.toChecksumAddress(cert3_data['message']['subject'])
cert3_data['message']['realm'] = self._w3.toChecksumAddress(cert3_data['message']['realm'])
# create certificates chain
#
certificates = [(cert1_data, cert1_sig), (cert2_data, cert2_sig), (cert3_data, cert3_sig)]
if False:
from pprint import pprint
print()
pprint(certificates)
print()
# check certificates and certificate signatures of whole chain
#
self.assertEqual(certificates, self._certs_expected1)
yield self._sm.close()
@inlineCallbacks
def test_eip712_create_certificate_chain_highlevel(self):
yield self._sm.open()
# FIXME
yield self._sm.close()
@inlineCallbacks
def test_eip712_verify_certificate_chain_manual(self):
yield self._sm.open()
# keys originally used to sign the certificates in the certificate chain
trustroot_eth_key: EthereumKey = self._sm[0]
delegate_eth_key: EthereumKey = self._sm[1]
delegate_cs_key: CryptosignKey = self._sm[6]
# parse the whole certificate chain
cert_chain = []
cert_sigs = []
for cert_data, cert_sig in self._certs_expected1:
self.assertIn('domain', cert_data)
self.assertIn('message', cert_data)
self.assertIn('primaryType', cert_data)
self.assertIn('types', cert_data)
self.assertIn(cert_data['primaryType'], cert_data['types'])
self.assertIn(cert_data['primaryType'], ['EIP712DelegateCertificate', 'EIP712AuthorityCertificate'])
if cert_data['primaryType'] == 'EIP712DelegateCertificate':
cert = EIP712DelegateCertificate.parse(cert_data['message'])
elif cert_data['primaryType'] == 'EIP712AuthorityCertificate':
cert = EIP712AuthorityCertificate.parse(cert_data['message'])
else:
assert False, 'should not arrive here'
cert_chain.append(cert)
cert_sigs.append(cert_sig)
# FIXME: allow length 2 and length > 3
self.assertEqual(len(cert_chain), 3)
self.assertEqual(cert_chain[0].delegate, delegate_eth_key.address(binary=True))
self.assertEqual(cert_chain[0].csPubKey, delegate_cs_key.public_key(binary=True))
self.assertEqual(cert_chain[1].issuer, trustroot_eth_key.address(binary=True))
self.assertEqual(cert_chain[2].issuer, trustroot_eth_key.address(binary=True))
# Certificate Chain Rules (CCR):
#
# 1. **CCR-1**: The `chainId` and `verifyingContract` must match for all certificates to what we expect, and `validFrom` before current block number on the respective chain.
# 2. **CCR-2**: The `realm` must match for all certificates to the respective realm.
# 3. **CCR-3**: The type of the first certificate in the chain must be a `EIP712DelegateCertificate`, and all subsequent certificates must be of type `EIP712AuthorityCertificate`.
# 4. **CCR-4**: The last certificate must be self-signed (`issuer` equals `subject`), it is a root CA certificate.
# 5. **CCR-5**: The intermediate certificate's `issuer` must be equal to the `subject` of the previous certificate.
# 6. **CCR-6**: The root certificate must be `validFrom` before the intermediate certificate
# 7. **CCR-7**: The `capabilities` of intermediate certificate must be a subset of the root cert
# 8. **CCR-8**: The intermediate certificate's `subject` must be the delegate certificate `delegate`
# 9. **CCR-9**: The intermediate certificate must be `validFrom` before the delegate certificate
# 10. **CCR-10**: The root certificate's signature must be valid and signed by the root certificate's `issuer`.
# 11. **CCR-11**: The intermediate certificate's signature must be valid and signed by the intermediate certificate's `issuer`.
# 12. **CCR-12**: The delegate certificate's signature must be valid and signed by the `delegate`.
# CCR-3
self.assertIsInstance(cert_chain[0], EIP712DelegateCertificate)
for i in [1, len(cert_chain) - 1]:
self.assertIsInstance(cert_chain[i], EIP712AuthorityCertificate)
# CCR-1
chainId = cert_chain[2].chainId
verifyingContract = cert_chain[2].verifyingContract
for cert in cert_chain:
self.assertEqual(cert.chainId, chainId)
self.assertEqual(cert.verifyingContract, verifyingContract)
# CCR-2
realm = cert_chain[2].realm
for cert in cert_chain[1:]:
self.assertEqual(cert.realm, realm)
# CCR-4
self.assertEqual(cert_chain[2].subject, cert_chain[2].issuer)
# CCR-5
self.assertEqual(cert_chain[1].issuer, cert_chain[2].subject)
# CCR-6
self.assertLessEqual(cert_chain[2].validFrom, cert_chain[1].validFrom)
# CCR-7
self.assertTrue(cert_chain[2].capabilities == cert_chain[2].capabilities | cert_chain[1].capabilities)
# CCR-8
self.assertEqual(cert_chain[1].subject, cert_chain[0].delegate)
# CCR-9
self.assertLessEqual(cert_chain[1].validFrom, cert_chain[0].validFrom)
# CCR-10
_issuer = cert_chain[2].recover(a2b_hex(cert_sigs[2]))
self.assertEqual(_issuer, trustroot_eth_key.address(binary=True))
# CCR-11
_issuer = cert_chain[1].recover(a2b_hex(cert_sigs[1]))
self.assertEqual(_issuer, trustroot_eth_key.address(binary=True))
# CCR-12
_issuer = cert_chain[0].recover(a2b_hex(cert_sigs[0]))
self.assertEqual(_issuer, delegate_eth_key.address(binary=True))
yield self._sm.close()
@inlineCallbacks
def test_eip712_verify_certificate_chain_highlevel(self):
yield self._sm.open()
# keys originally used to sign the certificates in the certificate chain
trustroot_eth_key: EthereumKey = self._sm[0]
delegate_eth_key: EthereumKey = self._sm[1]
delegate_cs_key: CryptosignKey = self._sm[6]
certificates = parse_certificate_chain(self._certs_expected1)
self.assertEqual(certificates[2].issuer, trustroot_eth_key.address(binary=True))
self.assertEqual(certificates[0].delegate, delegate_eth_key.address(binary=True))
self.assertEqual(certificates[0].csPubKey, delegate_cs_key.public_key(binary=True))
yield self._sm.close()
|