commit b2e13b659428f120a314c6cab94daddbe5aba18a Author: Daniel Alvarez Date: Thu Nov 3 19:32:04 2016 +0100 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..72364f9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,89 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# IPython Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# dotenv +.env + +# virtualenv +venv/ +ENV/ + +# Spyder project settings +.spyderproject + +# Rope project settings +.ropeproject diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..68c771a --- /dev/null +++ b/LICENSE @@ -0,0 +1,176 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..c978a52 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,6 @@ +include AUTHORS +include ChangeLog +exclude .gitignore +exclude .gitreview + +global-exclude *.pyc diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..29d0a31 --- /dev/null +++ b/README.rst @@ -0,0 +1,89 @@ +######################################## +SoftToken OTP +######################################## + +SoftToken OTP is an application to generate One-Time-Passwords to be used as a +second factor authentication mechanism. +It can either print it when executed in the commandline or type it wherever +your focus is. This can be especially useful when assigning a keybind to use +your token. + +.. class:: no-web no-pdf + + +.. contents:: + +.. section-numbering:: + +.. raw:: pdf + + PageBreak oneColumn + + +============= +Main features +============= + +* Generate Time-Based One-Time Passwords +* Multiple tokens support +* Print OTP wherever the focus is (useful for keybindings) + +============= +Usage +============= + +Create a new token: + +.. code-block:: bash + + $ softtoken --new -t token1 --hash sha256 --digits 6 + + New Token created: + + token1 + ------------- + Seed (hex): 337ad0410038666829c6446448d0a0d851938193 + Seed (b32): GN5NAQIAHBTGQKOGIRSERUFA3BIZHAMT + +Delete a token: + +.. code-block:: bash + + $ softtoken --delete -t token1 + Token token1 successfully deleted + +List tokens: + +.. code-block:: bash + + $ softtoken --list + [*] token1 + [*] token2 + [*] token3 + [*] token4 + [*] token5 + +Generate an OTP: + +.. code-block:: bash + + $ softtoken -t token1 + 630567 + + +Generate an OTP and get it wherever your focus is: + +.. code-block:: bash + + $ softtoken -t token1 -X + 630567 + + +============= +TODO +============= + +* Add HOTP support +* Parametrize TOTP time +* Add support to copy the OTP automatically into the clipboard + diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..883b237 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,16 @@ +# The order of packages is significant, because pip processes them in the order +# of appearance. Changing the order has an impact on the overall integration +# process, which may cause wedges in the gate later. + +configparser==3.5.0 +flake8==2.5.5 +hacking==0.11.0 +mccabe==0.2.1 +pbr>=1.6 # Apache-2.0 +pep8==1.5.7 +pyflakes==0.8.1 +pyotp==2.2.1 +python-xlib==0.17 +PyUserInput==0.1.11 +six==1.10.0 + diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..af57bc0 --- /dev/null +++ b/setup.cfg @@ -0,0 +1 @@ +[bdist_wheel] diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..ea0a73b --- /dev/null +++ b/setup.py @@ -0,0 +1,81 @@ +from setuptools import setup, find_packages +from codecs import open +from os import path +from softtoken.softtoken import __version__ + +here = path.abspath(path.dirname(__file__)) + +# Get the long description from the README file +with open(path.join(here, 'README.rst'), encoding='utf-8') as f: + long_description = f.read() + + +setup( + name='softtoken', + + version=__version__, + description='One-Time Password Generator', + long_description=long_description, + + # The project's main homepage. + url='https://github.com/danalsan/softtoken', + + # Author details + author='Daniel ALvarez', + author_email='dalvarez@redhat.com', + + # Choose your license + license='Apache Software License', + + # See https://pypi.python.org/pypi?%3Aaction=list_classifiers + classifiers=[ + # How mature is this project? Common values are + # 3 - Alpha + # 4 - Beta + # 5 - Production/Stable + 'Development Status :: 3 - Alpha', + + # Indicate who your project is intended for + 'Intended Audience :: End Users/Desktop', + + # Pick your license as you wish (should match "license" above) + 'License :: OSI Approved :: Apache Software License', + 'Topic :: Utilities', + + # Specify the Python versions you support here. In particular, ensure + # that you indicate whether you support Python 2, Python 3 or both. + 'Programming Language :: Python :: 2.7', + ], + + # What does your project relate to? + keywords='token,softtoken,otp', + + # You can just specify the packages manually here if your project is + # simple. Or you can use find_packages(). + packages=find_packages(exclude=['contrib', 'docs', 'tests']), + + py_modules=['softtoken.softtoken'], + install_requires=[ + 'configparser==3.5.0', + 'flake8==2.5.5', + 'hacking==0.11.0', + 'mccabe==0.2.1', + 'pbr>=1.6', + 'pep8==1.5.7', + 'pyflakes==0.8.1', + 'pyotp==2.2.1', + 'python-xlib==0.17', + 'PyUserInput==0.1.11', + 'six==1.10.0' + ], + # extras_require={ + # 'dev': ['check-manifest'], + # 'test': ['coverage'], + # }, + + entry_points={ + 'console_scripts': [ + 'softtoken=softtoken.softtoken:main', + ], + }, +) diff --git a/softtoken/__init__.py b/softtoken/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/softtoken/softtoken.py b/softtoken/softtoken.py new file mode 100644 index 0000000..56cf92a --- /dev/null +++ b/softtoken/softtoken.py @@ -0,0 +1,164 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +from __future__ import print_function + +import argparse +import base64 +import configparser +import hashlib +from os import path +from os import urandom +import sys + +from pykeyboard import PyKeyboard +import pyotp + + +__version__ = '0.0.1' + +CONFIG_FILE = 'softtoken.conf' + + +def load_config(): + dir_path = path.join( + path.dirname(path.realpath(__file__)), + CONFIG_FILE) + cfg = configparser.SafeConfigParser() + cfg.read(dir_path) + return cfg + + +def save_config(cfg): + dir_path = path.join( + path.dirname(path.realpath(__file__)), + CONFIG_FILE) + try: + with open(dir_path, 'w+') as configfile: + cfg.write(configfile) + except Exception: + print('ERROR: Cannot write config file') + sys.exit(2) + + +def create_token(name, hash_function='sha256', digits=6, seed_length=20): + cfg = load_config() + if cfg.has_section(name): + print('Token %s already exists. Delete it first' % name) + sys.exit(2) + + seed = urandom(seed_length) + + cfg.add_section(name) + cfg.set(name, 'hash', hash_function) + cfg.set(name, 'digits', str(digits)) + cfg.set(name, 'seed', base64.b32encode(seed)) + + save_config(cfg) + + print('\nNew Token created:\n\n%s\n-------------' % name) + print('Seed (hex): %s' % seed.encode('hex')) + print('Seed (b32): %s\n' % base64.b32encode(seed)) + + +def delete_token(name): + cfg = load_config() + if not cfg.has_section(name): + print('Token %s does not exist' % name) + sys.exit(2) + cfg.remove_section(name) + save_config(cfg) + print("Token %s successfully deleted" % name) + + +def print_tokens(): + cfg = load_config() + for section in cfg.sections(): + print("[*] %s" % section) + + +def main(): + + parser = argparse.ArgumentParser(version=__version__) + parser.add_argument('--new', action='store_true', default=False, + dest='new_token', help='Generate a new Soft Token') + parser.add_argument('--delete', action='store_true', default=False, + dest='delete_token', help='Delete a Soft Token') + parser.add_argument('--list', action='store_true', default=False, + dest='list_tokens', help='List configured tokens') + parser.add_argument('--token', '-t', required=False, dest='token_name', + help='Soft Token name') + parser.add_argument('--hash', default='sha256', dest='hash_function', + choices=('sha1', 'sha256', 'sha512'), help='Hash ' + 'function to use (default is sha256)') + parser.add_argument('--digits', '-d', type=int, default=6, dest='digits', + help='OTP Length (default is 6)') + parser.add_argument('--length', '-l', type=int, default=20, + dest='seed_length', help='Seed length in bytes ' + '(default is 20)') + parser.add_argument('-X', action='store_true', default=False, + dest='print_focus', help='Output the OTP where ' + 'the current focus is') + + args = parser.parse_args() + + if args.list_tokens: + print_tokens() + sys.exit(0) + + if args.token_name is None: + print("A Token name is required for this action") + parser.print_help() + sys.exit(-1) + + if args.new_token: + create_token(args.token_name, + args.hash_function, + args.digits, + args.seed_length) + sys.exit(0) + + if args.delete_token: + delete_token(args.token_name) + sys.exit(0) + + if args.list_tokens: + print_tokens() + sys.exit(0) + + # Generate new OTP if the token exists + cfg = load_config() + if not cfg.has_section(args.token_name): + print('Token %s does not exist' % args.token_name) + sys.exit(2) + + if args.hash_function == 'sha1': + hf = hashlib.sha256 + elif args.hash_function == 'sha256': + hf = hashlib.sha256 + elif args.hash_function == 'sha512': + hf = hashlib.sha512 + + seed = cfg.get(args.token_name, 'seed') + totp = pyotp.TOTP(seed, digest=hf, digits=args.digits) + + otp = totp.now() + + if args.print_focus: + k = PyKeyboard() + k.type_string(otp) + else: + print(otp) + + +if __name__ == "__main__": + main() diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..a5031e2 --- /dev/null +++ b/tox.ini @@ -0,0 +1,40 @@ +[tox] +minversion = 2.0 +envlist = py27,pep8 +skipsdist = True + +[testenv] +usedevelop = True +install_command = pip install {opts} {packages} +setenv = + VIRTUAL_ENV={envdir} + PYTHONWARNINGS=default::DeprecationWarning +deps = -r{toxinidir}/requirements.txt +commands = python setup.py test --slowest --testr-args='{posargs}' + +[testenv:pep8] +commands = flake8 {posargs} + +[testenv:venv] +commands = {posargs} + +[testenv:cover] +commands = python setup.py test --coverage --testr-args='{posargs}' + +[testenv:docs] +commands = python setup.py build_sphinx + +[testenv:releasenotes] +commands = + sphinx-build -a -E -W -d releasenotes/build/doctrees -b html releasenotes/source releasenotes/build/html + +[testenv:debug] +commands = oslo_debug_helper {posargs} + +[flake8] +# E123, E125 skipped as they are invalid PEP-8. + +show-source = True +ignore = E123,E125 +builtins = _ +exclude=.venv,.git,.tox,dist,doc,*lib/python*,*egg,build