Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

_userkey.py 9.7KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. ###############################################################################
  2. #
  3. # The MIT License (MIT)
  4. #
  5. # Copyright (c) typedef int GmbH
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining a copy
  8. # of this software and associated documentation files (the "Software"), to deal
  9. # in the Software without restriction, including without limitation the rights
  10. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. # copies of the Software, and to permit persons to whom the Software is
  12. # furnished to do so, subject to the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be included in
  15. # all copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. # THE SOFTWARE.
  24. #
  25. ###############################################################################
  26. import re
  27. import os
  28. import binascii
  29. import socket
  30. from collections import OrderedDict
  31. import getpass
  32. import click
  33. from nacl.signing import SigningKey
  34. from nacl.encoding import HexEncoder
  35. from eth_keys import KeyAPI
  36. from eth_keys.backends import NativeECCBackend
  37. from autobahn.util import utcnow, write_keyfile, parse_keyfile
  38. from autobahn.wamp import cryptosign
  39. if 'USER' in os.environ:
  40. _DEFAULT_EMAIL_ADDRESS = '{}@{}'.format(os.environ['USER'], socket.getfqdn())
  41. else:
  42. _DEFAULT_EMAIL_ADDRESS = 'unknown'
  43. class EmailAddress(click.ParamType):
  44. """
  45. Email address validator.
  46. """
  47. name = 'Email address'
  48. def __init__(self):
  49. click.ParamType.__init__(self)
  50. def convert(self, value, param, ctx):
  51. if re.match(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$", value):
  52. return value
  53. self.fail('invalid email address "{}"'.format(value))
  54. def _user_id(yes_to_all=False):
  55. if yes_to_all:
  56. return _DEFAULT_EMAIL_ADDRESS
  57. while True:
  58. value = click.prompt('Please enter your email address', type=EmailAddress(), default=_DEFAULT_EMAIL_ADDRESS)
  59. if click.confirm('We will send an activation code to "{}", ok?'.format(value), default=True):
  60. break
  61. return value
  62. def _creator(yes_to_all=False):
  63. """
  64. for informational purposes, try to identify the creator (user@hostname)
  65. """
  66. if yes_to_all:
  67. return _DEFAULT_EMAIL_ADDRESS
  68. else:
  69. try:
  70. user = getpass.getuser()
  71. except BaseException:
  72. user = 'unknown'
  73. try:
  74. hostname = socket.gethostname()
  75. except BaseException:
  76. hostname = 'unknown'
  77. return '{}@{}'.format(user, hostname)
  78. class UserKey(object):
  79. def __init__(self, privkey, pubkey, yes_to_all=True):
  80. self._privkey_path = privkey
  81. self._pubkey_path = pubkey
  82. self.key = None
  83. self._creator = None
  84. self._created_at = None
  85. self.user_id = None
  86. self._privkey = None
  87. self._privkey_hex = None
  88. self._pubkey = None
  89. self._pubkey_hex = None
  90. self._load_and_maybe_generate(self._privkey_path, self._pubkey_path, yes_to_all)
  91. def __str__(self):
  92. return 'UserKey(privkey="{}", pubkey="{}" [{}])'.format(self._privkey_path, self._pubkey_path,
  93. self._pubkey_hex)
  94. def _load_and_maybe_generate(self, privkey_path, pubkey_path, yes_to_all=False):
  95. if os.path.exists(privkey_path):
  96. # node private key seems to exist already .. check!
  97. priv_tags = parse_keyfile(privkey_path, private=True)
  98. for tag in ['creator', 'created-at', 'user-id', 'public-key-ed25519', 'private-key-ed25519']:
  99. if tag not in priv_tags:
  100. raise Exception("Corrupt user private key file {} - {} tag not found".format(privkey_path, tag))
  101. creator = priv_tags['creator']
  102. created_at = priv_tags['created-at']
  103. user_id = priv_tags['user-id']
  104. privkey_hex = priv_tags['private-key-ed25519']
  105. privkey = SigningKey(privkey_hex, encoder=HexEncoder)
  106. pubkey = privkey.verify_key
  107. pubkey_hex = pubkey.encode(encoder=HexEncoder).decode('ascii')
  108. if priv_tags['public-key-ed25519'] != pubkey_hex:
  109. raise Exception(("Inconsistent user private key file {} - public-key-ed25519 doesn't"
  110. " correspond to private-key-ed25519").format(pubkey_path))
  111. eth_pubadr = None
  112. eth_privkey = None
  113. eth_privkey_seed_hex = priv_tags.get('private-key-eth', None)
  114. if eth_privkey_seed_hex:
  115. eth_privkey_seed = binascii.a2b_hex(eth_privkey_seed_hex)
  116. eth_privkey = KeyAPI(NativeECCBackend).PrivateKey(eth_privkey_seed)
  117. eth_pubadr = eth_privkey.public_key.to_checksum_address()
  118. if 'public-adr-eth' in priv_tags:
  119. if priv_tags['public-adr-eth'] != eth_pubadr:
  120. raise Exception(("Inconsistent node private key file {} - public-adr-eth doesn't"
  121. " correspond to private-key-eth").format(privkey_path))
  122. if os.path.exists(pubkey_path):
  123. pub_tags = parse_keyfile(pubkey_path, private=False)
  124. for tag in ['creator', 'created-at', 'user-id', 'public-key-ed25519']:
  125. if tag not in pub_tags:
  126. raise Exception("Corrupt user public key file {} - {} tag not found".format(pubkey_path, tag))
  127. if pub_tags['public-key-ed25519'] != pubkey_hex:
  128. raise Exception(("Inconsistent user public key file {} - public-key-ed25519 doesn't"
  129. " correspond to private-key-ed25519").format(pubkey_path))
  130. if pub_tags.get('public-adr-eth', None) != eth_pubadr:
  131. raise Exception(
  132. ("Inconsistent user public key file {} - public-adr-eth doesn't"
  133. " correspond to private-key-eth in private key file {}").format(pubkey_path, privkey_path))
  134. else:
  135. # public key is missing! recreate it
  136. pub_tags = OrderedDict([
  137. ('creator', priv_tags['creator']),
  138. ('created-at', priv_tags['created-at']),
  139. ('user-id', priv_tags['user-id']),
  140. ('public-key-ed25519', pubkey_hex),
  141. ('public-adr-eth', eth_pubadr),
  142. ])
  143. msg = 'Crossbar.io user public key\n\n'
  144. write_keyfile(pubkey_path, pub_tags, msg)
  145. click.echo('Re-created user public key from private key: {}'.format(pubkey_path))
  146. else:
  147. # user private key does not yet exist: generate one
  148. creator = _creator(yes_to_all)
  149. created_at = utcnow()
  150. user_id = _user_id(yes_to_all)
  151. privkey = SigningKey.generate()
  152. privkey_hex = privkey.encode(encoder=HexEncoder).decode('ascii')
  153. pubkey = privkey.verify_key
  154. pubkey_hex = pubkey.encode(encoder=HexEncoder).decode('ascii')
  155. eth_privkey_seed = os.urandom(32)
  156. eth_privkey_seed_hex = binascii.b2a_hex(eth_privkey_seed).decode()
  157. eth_privkey = KeyAPI(NativeECCBackend).PrivateKey(eth_privkey_seed)
  158. eth_pubadr = eth_privkey.public_key.to_checksum_address()
  159. # first, write the public file
  160. tags = OrderedDict([
  161. ('creator', creator),
  162. ('created-at', created_at),
  163. ('user-id', user_id),
  164. ('public-key-ed25519', pubkey_hex),
  165. ('public-adr-eth', eth_pubadr),
  166. ])
  167. msg = 'Crossbar.io user public key\n\n'
  168. write_keyfile(pubkey_path, tags, msg)
  169. os.chmod(pubkey_path, 420)
  170. # now, add the private key and write the private file
  171. tags['private-key-ed25519'] = privkey_hex
  172. tags['private-key-eth'] = eth_privkey_seed_hex
  173. msg = 'Crossbar.io user private key - KEEP THIS SAFE!\n\n'
  174. write_keyfile(privkey_path, tags, msg)
  175. os.chmod(privkey_path, 384)
  176. click.echo('New user public key generated: {}'.format(pubkey_path))
  177. click.echo('New user private key generated ({}): {}'.format('keep this safe!', privkey_path))
  178. # fix file permissions on node public/private key files
  179. # note: we use decimals instead of octals as octal literals have changed between Py2/3
  180. if os.stat(pubkey_path).st_mode & 511 != 420: # 420 (decimal) == 0644 (octal)
  181. os.chmod(pubkey_path, 420)
  182. click.echo('File permissions on user public key fixed!')
  183. if os.stat(privkey_path).st_mode & 511 != 384: # 384 (decimal) == 0600 (octal)
  184. os.chmod(privkey_path, 384)
  185. click.echo('File permissions on user private key fixed!')
  186. # load keys into object
  187. self._creator = creator
  188. self._created_at = created_at
  189. self._privkey = privkey
  190. self._privkey_hex = privkey_hex
  191. self._pubkey = pubkey
  192. self._pubkey_hex = pubkey_hex
  193. self._eth_pubadr = eth_pubadr
  194. self._eth_privkey_seed_hex = eth_privkey_seed_hex
  195. self._eth_privkey = eth_privkey
  196. self.user_id = user_id
  197. self.key = cryptosign.CryptosignKey(privkey, can_sign=True)