ckeygen.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. # -*- test-case-name: twisted.conch.test.test_ckeygen -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Implementation module for the `ckeygen` command.
  6. """
  7. from __future__ import print_function
  8. import sys, os, getpass, socket
  9. from functools import wraps
  10. from imp import reload
  11. if getpass.getpass == getpass.unix_getpass:
  12. try:
  13. import termios # hack around broken termios
  14. termios.tcgetattr, termios.tcsetattr
  15. except (ImportError, AttributeError):
  16. sys.modules['termios'] = None
  17. reload(getpass)
  18. from twisted.conch.ssh import keys
  19. from twisted.python import failure, filepath, log, usage
  20. from twisted.python.compat import raw_input, _PY3
  21. supportedKeyTypes = dict()
  22. def _keyGenerator(keyType):
  23. def assignkeygenerator(keygenerator):
  24. @wraps(keygenerator)
  25. def wrapper(*args, **kwargs):
  26. return keygenerator(*args, **kwargs)
  27. supportedKeyTypes[keyType] = wrapper
  28. return wrapper
  29. return assignkeygenerator
  30. class GeneralOptions(usage.Options):
  31. synopsis = """Usage: ckeygen [options]
  32. """
  33. longdesc = "ckeygen manipulates public/private keys in various ways."
  34. optParameters = [['bits', 'b', None, 'Number of bits in the key to create.'],
  35. ['filename', 'f', None, 'Filename of the key file.'],
  36. ['type', 't', None, 'Specify type of key to create.'],
  37. ['comment', 'C', None, 'Provide new comment.'],
  38. ['newpass', 'N', None, 'Provide new passphrase.'],
  39. ['pass', 'P', None, 'Provide old passphrase.'],
  40. ['format', 'o', 'sha256-base64', 'Fingerprint format of key file.']]
  41. optFlags = [['fingerprint', 'l', 'Show fingerprint of key file.'],
  42. ['changepass', 'p', 'Change passphrase of private key file.'],
  43. ['quiet', 'q', 'Quiet.'],
  44. ['no-passphrase', None, "Create the key with no passphrase."],
  45. ['showpub', 'y', 'Read private key file and print public key.']]
  46. compData = usage.Completions(
  47. optActions={"type": usage.CompleteList(list(supportedKeyTypes.keys()))})
  48. def run():
  49. options = GeneralOptions()
  50. try:
  51. options.parseOptions(sys.argv[1:])
  52. except usage.UsageError as u:
  53. print('ERROR: %s' % u)
  54. options.opt_help()
  55. sys.exit(1)
  56. log.discardLogs()
  57. log.deferr = handleError # HACK
  58. if options['type']:
  59. if options['type'].lower() in supportedKeyTypes:
  60. print('Generating public/private %s key pair.' % (options['type']))
  61. supportedKeyTypes[options['type'].lower()](options)
  62. else:
  63. sys.exit(
  64. 'Key type was %s, must be one of %s'
  65. % (options['type'], ', '.join(supportedKeyTypes.keys())))
  66. elif options['fingerprint']:
  67. printFingerprint(options)
  68. elif options['changepass']:
  69. changePassPhrase(options)
  70. elif options['showpub']:
  71. displayPublicKey(options)
  72. else:
  73. options.opt_help()
  74. sys.exit(1)
  75. def enumrepresentation(options):
  76. if options['format'] == 'md5-hex':
  77. options['format'] = keys.FingerprintFormats.MD5_HEX
  78. return options
  79. elif options['format'] == 'sha256-base64':
  80. options['format'] = keys.FingerprintFormats.SHA256_BASE64
  81. return options
  82. else:
  83. raise keys.BadFingerPrintFormat(
  84. 'Unsupported fingerprint format: %s' % (options['format'],))
  85. def handleError():
  86. global exitStatus
  87. exitStatus = 2
  88. log.err(failure.Failure())
  89. raise
  90. @_keyGenerator('rsa')
  91. def generateRSAkey(options):
  92. from cryptography.hazmat.backends import default_backend
  93. from cryptography.hazmat.primitives.asymmetric import rsa
  94. if not options['bits']:
  95. options['bits'] = 1024
  96. keyPrimitive = rsa.generate_private_key(
  97. key_size=int(options['bits']),
  98. public_exponent=65537,
  99. backend=default_backend(),
  100. )
  101. key = keys.Key(keyPrimitive)
  102. _saveKey(key, options)
  103. @_keyGenerator('dsa')
  104. def generateDSAkey(options):
  105. from cryptography.hazmat.backends import default_backend
  106. from cryptography.hazmat.primitives.asymmetric import dsa
  107. if not options['bits']:
  108. options['bits'] = 1024
  109. keyPrimitive = dsa.generate_private_key(
  110. key_size=int(options['bits']),
  111. backend=default_backend(),
  112. )
  113. key = keys.Key(keyPrimitive)
  114. _saveKey(key, options)
  115. @_keyGenerator('ecdsa')
  116. def generateECDSAkey(options):
  117. from cryptography.hazmat.backends import default_backend
  118. from cryptography.hazmat.primitives.asymmetric import ec
  119. if not options['bits']:
  120. options['bits'] = 256
  121. # OpenSSH supports only mandatory sections of RFC5656.
  122. # See https://www.openssh.com/txt/release-5.7
  123. curve = b'ecdsa-sha2-nistp' + str(options['bits']).encode('ascii')
  124. keyPrimitive = ec.generate_private_key(
  125. curve=keys._curveTable[curve],
  126. backend=default_backend()
  127. )
  128. key = keys.Key(keyPrimitive)
  129. _saveKey(key, options)
  130. def printFingerprint(options):
  131. if not options['filename']:
  132. filename = os.path.expanduser('~/.ssh/id_rsa')
  133. options['filename'] = raw_input('Enter file in which the key is (%s): ' % filename)
  134. if os.path.exists(options['filename']+'.pub'):
  135. options['filename'] += '.pub'
  136. options = enumrepresentation(options)
  137. try:
  138. key = keys.Key.fromFile(options['filename'])
  139. print('%s %s %s' % (
  140. key.size(),
  141. key.fingerprint(options['format']),
  142. os.path.basename(options['filename'])))
  143. except keys.BadKeyError:
  144. sys.exit('bad key')
  145. def changePassPhrase(options):
  146. if not options['filename']:
  147. filename = os.path.expanduser('~/.ssh/id_rsa')
  148. options['filename'] = raw_input(
  149. 'Enter file in which the key is (%s): ' % filename)
  150. try:
  151. key = keys.Key.fromFile(options['filename'])
  152. except keys.EncryptedKeyError as e:
  153. # Raised if password not supplied for an encrypted key
  154. if not options.get('pass'):
  155. options['pass'] = getpass.getpass('Enter old passphrase: ')
  156. try:
  157. key = keys.Key.fromFile(
  158. options['filename'], passphrase=options['pass'])
  159. except keys.BadKeyError:
  160. sys.exit('Could not change passphrase: old passphrase error')
  161. except keys.EncryptedKeyError as e:
  162. sys.exit('Could not change passphrase: %s' % (e,))
  163. except keys.BadKeyError as e:
  164. sys.exit('Could not change passphrase: %s' % (e,))
  165. if not options.get('newpass'):
  166. while 1:
  167. p1 = getpass.getpass(
  168. 'Enter new passphrase (empty for no passphrase): ')
  169. p2 = getpass.getpass('Enter same passphrase again: ')
  170. if p1 == p2:
  171. break
  172. print('Passphrases do not match. Try again.')
  173. options['newpass'] = p1
  174. try:
  175. newkeydata = key.toString('openssh', extra=options['newpass'])
  176. except Exception as e:
  177. sys.exit('Could not change passphrase: %s' % (e,))
  178. try:
  179. keys.Key.fromString(newkeydata, passphrase=options['newpass'])
  180. except (keys.EncryptedKeyError, keys.BadKeyError) as e:
  181. sys.exit('Could not change passphrase: %s' % (e,))
  182. with open(options['filename'], 'wb') as fd:
  183. fd.write(newkeydata)
  184. print('Your identification has been saved with the new passphrase.')
  185. def displayPublicKey(options):
  186. if not options['filename']:
  187. filename = os.path.expanduser('~/.ssh/id_rsa')
  188. options['filename'] = raw_input('Enter file in which the key is (%s): ' % filename)
  189. try:
  190. key = keys.Key.fromFile(options['filename'])
  191. except keys.EncryptedKeyError:
  192. if not options.get('pass'):
  193. options['pass'] = getpass.getpass('Enter passphrase: ')
  194. key = keys.Key.fromFile(
  195. options['filename'], passphrase = options['pass'])
  196. displayKey = key.public().toString('openssh')
  197. if _PY3:
  198. displayKey = displayKey.decode("ascii")
  199. print(displayKey)
  200. def _saveKey(key, options):
  201. """
  202. Persist a SSH key on local filesystem.
  203. @param key: Key which is persisted on local filesystem.
  204. @type key: C{keys.Key} implementation.
  205. @param options:
  206. @type options: L{dict}
  207. """
  208. KeyTypeMapping = {'EC': 'ecdsa', 'RSA': 'rsa', 'DSA': 'dsa'}
  209. keyTypeName = KeyTypeMapping[key.type()]
  210. if not options['filename']:
  211. defaultPath = os.path.expanduser(u'~/.ssh/id_%s' % (keyTypeName,))
  212. newPath = raw_input(
  213. 'Enter file in which to save the key (%s): ' % (defaultPath,))
  214. options['filename'] = newPath.strip() or defaultPath
  215. if os.path.exists(options['filename']):
  216. print('%s already exists.' % (options['filename'],))
  217. yn = raw_input('Overwrite (y/n)? ')
  218. if yn[0].lower() != 'y':
  219. sys.exit()
  220. if options.get('no-passphrase'):
  221. options['pass'] = b''
  222. elif not options['pass']:
  223. while 1:
  224. p1 = getpass.getpass('Enter passphrase (empty for no passphrase): ')
  225. p2 = getpass.getpass('Enter same passphrase again: ')
  226. if p1 == p2:
  227. break
  228. print('Passphrases do not match. Try again.')
  229. options['pass'] = p1
  230. comment = '%s@%s' % (getpass.getuser(), socket.gethostname())
  231. filepath.FilePath(options['filename']).setContent(
  232. key.toString('openssh', options['pass']))
  233. os.chmod(options['filename'], 33152)
  234. filepath.FilePath(options['filename'] + '.pub').setContent(
  235. key.public().toString('openssh', comment))
  236. options = enumrepresentation(options)
  237. print('Your identification has been saved in %s' % (options['filename'],))
  238. print('Your public key has been saved in %s.pub' % (options['filename'],))
  239. print('The key fingerprint in %s is:' % (options['format'],))
  240. print(key.fingerprint(options['format']))
  241. if __name__ == '__main__':
  242. run()