From e297c0696cf594f8f700dd82fdcdda582e348eda Mon Sep 17 00:00:00 2001 From: Simeon Simeonov Date: Mon, 6 Apr 2020 10:28:46 +0200 Subject: Add a simple CLI interface with tests and update README.md --- otp2289/__main__.py | 293 ++++++++++++++++++++++++++++++++++++++++++++++++++++ otp2289/server.py | 18 ++-- 2 files changed, 305 insertions(+), 6 deletions(-) create mode 100644 otp2289/__main__.py (limited to 'otp2289') diff --git a/otp2289/__main__.py b/otp2289/__main__.py new file mode 100644 index 0000000..2962d29 --- /dev/null +++ b/otp2289/__main__.py @@ -0,0 +1,293 @@ +# -*- coding: utf-8 -*- +# SPDX-License-Identifier: BSD-2-Clause-FreeBSD +# +# Copyright (c) 2020, Simeon Simeonov +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" +CLI entry point for the otp2289 package + +Examples: +python -m otp2289 --initiate-new-sequence -s TesT + +python -m otp2289 --generate-otp-response -c "otp-md5 499 TesT " -f token +python -m otp2289 --generate-otp-response -s TesT -i 499 -f token +""" +import argparse +import errno +import getpass +import os +import secrets +import string +import sys + +import otp2289 + + +def eprint(*arg, **kwargs): + """stdderr print wrapper""" + print(*arg, file=sys.stderr, flush=True, **kwargs) + + +def generate_otp_response(args): + """ + Generates a response based on the parameters sent from the parser + + :param args: The arguments assigned from argparse + :type args: argparse.Namespace + + :raises OTPChallengeException: In case of invalid challenge + + :raises OTPGeneratorException: In case of wrong generator parameters + + :return: The response string + :rtype: str + """ + generator = otp2289.generator.OTPGenerator( + args.password.encode(), + args.seed, + args.hash_algo) + if args.challenge_string: + if args.output_format == 'token': + return generator.generate_otp_words_from_challenge( + args.challenge_string) + return generator.generate_otp_hexdigest_from_challenge( + args.challenge_string) + # regular parameters + header = '' + if not args.quiet: + header = (f'Seed: {args.seed}, Step: {args.step}, ' + f'Hash: {args.hash_algo}{os.linesep}') + if args.output_format == 'token': + return header + generator.generate_otp_words(args.step) + return header + generator.generate_otp_hexdigest(args.step) + + +def generate_otp_range(args): + """ + Generates range of responses based on the parameters sent from the parser + + :param args: The arguments assigned from argparse + :type args: argparse.Namespace + + :raises OTPChallengeException: In case of invalid challenge + + :raises OTPGeneratorException: In case of wrong generator parameters + + :return: The responses string + :rtype: str + """ + generator = otp2289.generator.OTPGenerator( + args.password.encode(), + args.seed, + args.hash_algo) + if args.output_format == 'token': + method = generator.generate_otp_words + else: + method = generator.generate_otp_hexdigest + # handle most cases explicitly + if args.range == 1: + return f'{args.step}: ' + method(args.step) + if args.range > args.step + 1: + args.range = args.step + 1 + # any need for quiet? + header = '' + if not args.quiet: + header = (f'Seed: {args.seed}, Step: {args.step}, ' + f'Hash: {args.hash_algo}, Range: {args.range}{os.linesep}') + return header + os.linesep.join( + [f'{step}: ' + method(step) for step in range( + args.step, args.step - args.range, -1)]) + + +def get_rnd_seed(): + """ + Returns a random seed in the format: + + 2 random letters (capitalize()) + 5 random digits + """ + rnd = secrets.SystemRandom() + return (''.join(rnd.choices(string.ascii_lowercase, k=2)).capitalize() + + ''.join(rnd.choices(string.digits, k=5))) + + +def initiate_new_sequence(args): + """ + Generates a new sequence based on the parameters sent from the parser. + + :param args: The arguments assigned from argparse + :type args: argparse.Namespace + + :raises OTPChallengeException: In case of invalid challenge + + :raises OTPGeneratorException: In case of wrong generator parameters + + :return: The response string + :rtype: str + """ + if not args.seed: + args.seed = get_rnd_seed() + header = '' + if not args.quiet: + header = (f'Seed: {args.seed}, Step: {args.step}, ' + f'Hash: {args.hash_algo}{os.linesep}') + generator = otp2289.generator.OTPGenerator( + args.password.encode(), + args.seed, + args.hash_algo) + if args.challenge_string: + return header + generator.generate_otp_hexdigest_from_challenge( + args.challenge_string) + return header + generator.generate_otp_hexdigest(args.step) + + +def main(args=None): + """the main entry point""" + parser = argparse.ArgumentParser( + prog=__package__, + epilog=(f'%(prog)s {otp2289.__version__} by Simeon Simeonov ' + '(sgs @ Freenode)'), + description='The following options are available') + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument( + '--generate-otp-range', + action='store_true', + dest='generate_otp_range', + default=False, + help='Generates a range of OTP responses') + group.add_argument( + '--generate-otp-response', + action='store_true', + dest='generate_otp_response', + default=False, + help='Generates a new OTP response') + group.add_argument( + '--initiate-new-sequence', + action='store_true', + dest='initiate_new_sequence', + default=False, + help=('Initiates a new OTP sequence. Essentially the same as ' + '--generate-otp-response only it prompts twice for password ' + 'and always outputs hex (ignores -f).')) + parser.add_argument( + '-a', '--hash-algorithm', + metavar='', + type=str, + dest='hash_algo', + default='md5', + help='The hash algorithm to use. Possible values: md5 (default), sha1') + parser.add_argument( + '-c', '--challenge-string', + metavar='', + type=str, + dest='challenge_string', + default='', + help='Use challenge string when generating response') + parser.add_argument( + '-f', '--output-format', + metavar='', + type=str, + dest='output_format', + default='hex', + help='The output format to use. Possible values: hex (default), token') + parser.add_argument( + '-i', '--step', + metavar='', + type=int, + dest='step', + default=500, + help='The step. Default for initiating a new sequence is: 500') + parser.add_argument( + '-p', '--password', + metavar='', + type=str, + dest='password', + default='', + help=('The password or path to password file ' + '(default & recommended: prompt for passwd)')) + parser.add_argument( + '-q', '--quiet', + action='store_true', + dest='quiet', + default=False, + help='Dot not show headers. Only hex / tokens') + parser.add_argument( + '-r', '--range', + metavar='', + type=int, + dest='range', + default=1, + help='Amount of consecutive OTP hex/tokens to generate. default: 1') + parser.add_argument( + '-s', '--seed', + metavar='[seed]', + type=str, + dest='seed', + default='', + help=('The seed to use (1 to 16 alphanumeric characters) ' + '(default & recommended: random seed)')) + parser.add_argument( + '-v', '--version', + action='version', + version=f'%(prog)s {otp2289.__version__}', + help='display program-version and exit') + args = parser.parse_args(args) + # handle the password before everything else + if not args.password: + try: + while True: + args.password = getpass.getpass() + if ( + not args.initiate_new_sequence or + args.password == getpass.getpass('Repeat password: ') + ): + break + eprint('The passwords do not match') + except KeyboardInterrupt: + eprint(os.linesep + 'Prompt terminated') + sys.exit(errno.EACCES) + elif os.path.isfile(args.password): + try: + with open(args.password, 'r') as fp: + args.password = fp.readline().strip() + except Exception as exp: + eprint(f'Unable to open password file: {exp}') + sys.exit(1) + try: + if args.initiate_new_sequence: + print(initiate_new_sequence(args)) + if args.generate_otp_range: + print(generate_otp_range(args)) + if args.generate_otp_response: + print(generate_otp_response(args)) + sys.exit(0) + except otp2289.generator.OTPGeneratorException as exp: + eprint(f'GeneratorException: {exp}') + except otp2289.generator.OTPChallengeException as exp: + eprint(f'ChallengeException: {exp}') + except Exception as exp: + eprint(f'Unknown error: {exp}') + sys.exit(1) + + +if __name__ == '__main__': + main() diff --git a/otp2289/server.py b/otp2289/server.py index b765af6..fca3f06 100644 --- a/otp2289/server.py +++ b/otp2289/server.py @@ -58,10 +58,9 @@ class OTPState: Constructs an OTPState object with the given arguments. Keyword Arguments: - :param ot_hex: The one-time hex from the last successful - authentication or the first OTP of a newly - initialized sequence - :type ot_hex: str + :param ot_hex: The one-time hex from the last successful authentication + or None for a newly initialized sequence. + :type ot_hex: str or None :param current_step: The current step that is sent with the challenge :type current_step: int @@ -81,7 +80,9 @@ class OTPState: self._step = OTPGenerator.validate_step(current_step) except OTPGeneratorException as exp: raise OTPStateException(exp.args[0]) - self._current_digest = self.validate_hex(ot_hex) + self._current_digest = None + if ot_hex is not None: + self._current_digest = self.validate_hex(ot_hex) self._new_digest_hex = None # set upon a successful validation @property @@ -223,6 +224,7 @@ class OTPState: if self._hash_algo == 'md5': digest = hashlib.md5(response_bytes).digest() if ( + self._current_digest is None or OTPGenerator.strxor(digest[0:8], digest[8:]) == self._current_digest ): @@ -234,6 +236,7 @@ class OTPState: if self._hash_algo == 'sha1': digest = hashlib.sha1(response_bytes).digest() if ( + self._current_digest is None or OTPGenerator.sha1_digest_folding( hashlib.sha1( response_bytes).digest()) == self._current_digest @@ -255,7 +258,10 @@ class OTPState: :return: The dict representation of the object :rtype: dict """ - return {'ot_hex': binascii.hexlify(self._current_digest).decode(), + ot_hex = self._current_digest + if ot_hex is not None: + ot_hex = binascii.hexlify(self._current_digest).decode() + return {'ot_hex': ot_hex, 'current_step': self._step, 'seed': self._seed, 'hash_algo': self._hash_algo} -- cgit v1.3