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.

292 lines
9.7 KiB

  1. # Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # https://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Commandline scripts.
  15. These scripts are called by the executables defined in setup.py.
  16. """
  17. import abc
  18. import sys
  19. import typing
  20. import optparse
  21. import rsa
  22. import rsa.key
  23. import rsa.pkcs1
  24. HASH_METHODS = sorted(rsa.pkcs1.HASH_METHODS.keys())
  25. Indexable = typing.Union[typing.Tuple, typing.List[str]]
  26. def keygen() -> None:
  27. """Key generator."""
  28. # Parse the CLI options
  29. parser = optparse.OptionParser(usage='usage: %prog [options] keysize',
  30. description='Generates a new RSA keypair of "keysize" bits.')
  31. parser.add_option('--pubout', type='string',
  32. help='Output filename for the public key. The public key is '
  33. 'not saved if this option is not present. You can use '
  34. 'pyrsa-priv2pub to create the public key file later.')
  35. parser.add_option('-o', '--out', type='string',
  36. help='Output filename for the private key. The key is '
  37. 'written to stdout if this option is not present.')
  38. parser.add_option('--form',
  39. help='key format of the private and public keys - default PEM',
  40. choices=('PEM', 'DER'), default='PEM')
  41. (cli, cli_args) = parser.parse_args(sys.argv[1:])
  42. if len(cli_args) != 1:
  43. parser.print_help()
  44. raise SystemExit(1)
  45. try:
  46. keysize = int(cli_args[0])
  47. except ValueError:
  48. parser.print_help()
  49. print('Not a valid number: %s' % cli_args[0], file=sys.stderr)
  50. raise SystemExit(1)
  51. print('Generating %i-bit key' % keysize, file=sys.stderr)
  52. (pub_key, priv_key) = rsa.newkeys(keysize)
  53. # Save public key
  54. if cli.pubout:
  55. print('Writing public key to %s' % cli.pubout, file=sys.stderr)
  56. data = pub_key.save_pkcs1(format=cli.form)
  57. with open(cli.pubout, 'wb') as outfile:
  58. outfile.write(data)
  59. # Save private key
  60. data = priv_key.save_pkcs1(format=cli.form)
  61. if cli.out:
  62. print('Writing private key to %s' % cli.out, file=sys.stderr)
  63. with open(cli.out, 'wb') as outfile:
  64. outfile.write(data)
  65. else:
  66. print('Writing private key to stdout', file=sys.stderr)
  67. sys.stdout.buffer.write(data)
  68. class CryptoOperation(metaclass=abc.ABCMeta):
  69. """CLI callable that operates with input, output, and a key."""
  70. keyname = 'public' # or 'private'
  71. usage = 'usage: %%prog [options] %(keyname)s_key'
  72. description = ''
  73. operation = 'decrypt'
  74. operation_past = 'decrypted'
  75. operation_progressive = 'decrypting'
  76. input_help = 'Name of the file to %(operation)s. Reads from stdin if ' \
  77. 'not specified.'
  78. output_help = 'Name of the file to write the %(operation_past)s file ' \
  79. 'to. Written to stdout if this option is not present.'
  80. expected_cli_args = 1
  81. has_output = True
  82. key_class = rsa.PublicKey # type: typing.Type[rsa.key.AbstractKey]
  83. def __init__(self) -> None:
  84. self.usage = self.usage % self.__class__.__dict__
  85. self.input_help = self.input_help % self.__class__.__dict__
  86. self.output_help = self.output_help % self.__class__.__dict__
  87. @abc.abstractmethod
  88. def perform_operation(self, indata: bytes, key: rsa.key.AbstractKey,
  89. cli_args: Indexable) -> typing.Any:
  90. """Performs the program's operation.
  91. Implement in a subclass.
  92. :returns: the data to write to the output.
  93. """
  94. def __call__(self) -> None:
  95. """Runs the program."""
  96. (cli, cli_args) = self.parse_cli()
  97. key = self.read_key(cli_args[0], cli.keyform)
  98. indata = self.read_infile(cli.input)
  99. print(self.operation_progressive.title(), file=sys.stderr)
  100. outdata = self.perform_operation(indata, key, cli_args)
  101. if self.has_output:
  102. self.write_outfile(outdata, cli.output)
  103. def parse_cli(self) -> typing.Tuple[optparse.Values, typing.List[str]]:
  104. """Parse the CLI options
  105. :returns: (cli_opts, cli_args)
  106. """
  107. parser = optparse.OptionParser(usage=self.usage, description=self.description)
  108. parser.add_option('-i', '--input', type='string', help=self.input_help)
  109. if self.has_output:
  110. parser.add_option('-o', '--output', type='string', help=self.output_help)
  111. parser.add_option('--keyform',
  112. help='Key format of the %s key - default PEM' % self.keyname,
  113. choices=('PEM', 'DER'), default='PEM')
  114. (cli, cli_args) = parser.parse_args(sys.argv[1:])
  115. if len(cli_args) != self.expected_cli_args:
  116. parser.print_help()
  117. raise SystemExit(1)
  118. return cli, cli_args
  119. def read_key(self, filename: str, keyform: str) -> rsa.key.AbstractKey:
  120. """Reads a public or private key."""
  121. print('Reading %s key from %s' % (self.keyname, filename), file=sys.stderr)
  122. with open(filename, 'rb') as keyfile:
  123. keydata = keyfile.read()
  124. return self.key_class.load_pkcs1(keydata, keyform)
  125. def read_infile(self, inname: str) -> bytes:
  126. """Read the input file"""
  127. if inname:
  128. print('Reading input from %s' % inname, file=sys.stderr)
  129. with open(inname, 'rb') as infile:
  130. return infile.read()
  131. print('Reading input from stdin', file=sys.stderr)
  132. return sys.stdin.buffer.read()
  133. def write_outfile(self, outdata: bytes, outname: str) -> None:
  134. """Write the output file"""
  135. if outname:
  136. print('Writing output to %s' % outname, file=sys.stderr)
  137. with open(outname, 'wb') as outfile:
  138. outfile.write(outdata)
  139. else:
  140. print('Writing output to stdout', file=sys.stderr)
  141. sys.stdout.buffer.write(outdata)
  142. class EncryptOperation(CryptoOperation):
  143. """Encrypts a file."""
  144. keyname = 'public'
  145. description = ('Encrypts a file. The file must be shorter than the key '
  146. 'length in order to be encrypted.')
  147. operation = 'encrypt'
  148. operation_past = 'encrypted'
  149. operation_progressive = 'encrypting'
  150. def perform_operation(self, indata: bytes, pub_key: rsa.key.AbstractKey,
  151. cli_args: Indexable = ()) -> bytes:
  152. """Encrypts files."""
  153. assert isinstance(pub_key, rsa.key.PublicKey)
  154. return rsa.encrypt(indata, pub_key)
  155. class DecryptOperation(CryptoOperation):
  156. """Decrypts a file."""
  157. keyname = 'private'
  158. description = ('Decrypts a file. The original file must be shorter than '
  159. 'the key length in order to have been encrypted.')
  160. operation = 'decrypt'
  161. operation_past = 'decrypted'
  162. operation_progressive = 'decrypting'
  163. key_class = rsa.PrivateKey
  164. def perform_operation(self, indata: bytes, priv_key: rsa.key.AbstractKey,
  165. cli_args: Indexable = ()) -> bytes:
  166. """Decrypts files."""
  167. assert isinstance(priv_key, rsa.key.PrivateKey)
  168. return rsa.decrypt(indata, priv_key)
  169. class SignOperation(CryptoOperation):
  170. """Signs a file."""
  171. keyname = 'private'
  172. usage = 'usage: %%prog [options] private_key hash_method'
  173. description = ('Signs a file, outputs the signature. Choose the hash '
  174. 'method from %s' % ', '.join(HASH_METHODS))
  175. operation = 'sign'
  176. operation_past = 'signature'
  177. operation_progressive = 'Signing'
  178. key_class = rsa.PrivateKey
  179. expected_cli_args = 2
  180. output_help = ('Name of the file to write the signature to. Written '
  181. 'to stdout if this option is not present.')
  182. def perform_operation(self, indata: bytes, priv_key: rsa.key.AbstractKey,
  183. cli_args: Indexable) -> bytes:
  184. """Signs files."""
  185. assert isinstance(priv_key, rsa.key.PrivateKey)
  186. hash_method = cli_args[1]
  187. if hash_method not in HASH_METHODS:
  188. raise SystemExit('Invalid hash method, choose one of %s' %
  189. ', '.join(HASH_METHODS))
  190. return rsa.sign(indata, priv_key, hash_method)
  191. class VerifyOperation(CryptoOperation):
  192. """Verify a signature."""
  193. keyname = 'public'
  194. usage = 'usage: %%prog [options] public_key signature_file'
  195. description = ('Verifies a signature, exits with status 0 upon success, '
  196. 'prints an error message and exits with status 1 upon error.')
  197. operation = 'verify'
  198. operation_past = 'verified'
  199. operation_progressive = 'Verifying'
  200. key_class = rsa.PublicKey
  201. expected_cli_args = 2
  202. has_output = False
  203. def perform_operation(self, indata: bytes, pub_key: rsa.key.AbstractKey,
  204. cli_args: Indexable) -> None:
  205. """Verifies files."""
  206. assert isinstance(pub_key, rsa.key.PublicKey)
  207. signature_file = cli_args[1]
  208. with open(signature_file, 'rb') as sigfile:
  209. signature = sigfile.read()
  210. try:
  211. rsa.verify(indata, signature, pub_key)
  212. except rsa.VerificationError:
  213. raise SystemExit('Verification failed.')
  214. print('Verification OK', file=sys.stderr)
  215. encrypt = EncryptOperation()
  216. decrypt = DecryptOperation()
  217. sign = SignOperation()
  218. verify = VerifyOperation()