aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBrian Dolbec <dolsen@gentoo.org>2014-12-20 13:17:27 -0800
committerBrian Dolbec <dolsen@gentoo.org>2014-12-22 14:57:48 -0800
commita153cacf6b47788c9a017c37f78469e009e4ffff (patch)
tree249a0ea9461276ed921ff5c56b08a474626080f8 /gkeys-gen/gkeygen
parentMerge pull request #35 from gentoo/dol-sen-PR (diff)
downloadgentoo-keys-a153cacf6b47788c9a017c37f78469e009e4ffff.tar.gz
gentoo-keys-a153cacf6b47788c9a017c37f78469e009e4ffff.tar.bz2
gentoo-keys-a153cacf6b47788c9a017c37f78469e009e4ffff.zip
Move the 3 pkgs into their own *-pkg dir
This makes releasing each pkg independently easier. testpath: Update paths for the new directory structure
Diffstat (limited to 'gkeys-gen/gkeygen')
-rw-r--r--gkeys-gen/gkeygen/__init__.py5
-rw-r--r--gkeys-gen/gkeygen/actions.py122
-rw-r--r--gkeys-gen/gkeygen/cli.py116
3 files changed, 243 insertions, 0 deletions
diff --git a/gkeys-gen/gkeygen/__init__.py b/gkeys-gen/gkeygen/__init__.py
new file mode 100644
index 0000000..7e8b64e
--- /dev/null
+++ b/gkeys-gen/gkeygen/__init__.py
@@ -0,0 +1,5 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+__version__ = 'Git'
+__license__ = 'GPLv2'
diff --git a/gkeys-gen/gkeygen/actions.py b/gkeys-gen/gkeygen/actions.py
new file mode 100644
index 0000000..22b3089
--- /dev/null
+++ b/gkeys-gen/gkeygen/actions.py
@@ -0,0 +1,122 @@
+#
+#-*- coding:utf-8 -*-
+
+"""
+ Gentoo-Keys - gkeygen/actions.py
+
+ Primary API interface module
+ @copyright: 2014 by Pavlos Ratis <dastergon@gentoo.org>
+ @license: GNU GPL2, see COPYING for details
+"""
+
+import gpgme
+import os
+import re
+import shutil
+import sys
+
+if sys.hexversion >= 0x30200f0:
+ from urllib.request import urlopen
+ py_input = input
+ _unicode = str
+else:
+ from urllib2 import urlopen
+ py_input = raw_input
+ _unicode = unicode
+
+from gkeys.fileops import ensure_dirs
+
+Available_Actions = ["genkey"]
+
+GPG_CONF = "https://api.gentoo.org/gentoo-keys/specs/glep63-gpg-conf.skel"
+SPEC = "https://api.gentoo.org/gentoo-keys/specs/glep63.spec"
+
+class Actions(object):
+
+ def __init__(self, config, output=None, logger=None):
+ self.config = config
+ self.output = output
+ self.logger = logger
+
+ def genkey(self, args):
+ '''Key generation action'''
+ if not args.homedir:
+ gpghome = os.path.join(os.getcwd(), 'gpghome')
+ else:
+ if os.path.exists(args.homedir):
+ gpghome = os.path.join(args.homedir, 'gpghome')
+ else:
+ self.output("Aborting... %s path does not exist." % args.homedir)
+ return False
+ self.logger.debug("MAIN: _action_genkey; setting gpghome destination: %s" % gpghome)
+ self.logger.debug("MAIN: _action_genkey; args= %s" % str(args))
+ key_params = self.get_input()
+ ack = None
+ while ack not in ["y", "yes", "n", "no"]:
+ ack = py_input("Continue?[y/n]: ").lower()
+ if ack in ["n", "no"]:
+ self.output("\nKey generation aborted.")
+ return False
+ elif ack in ["y", "yes"]:
+ # Set the environment to custom gpg directory
+ os.environ['GNUPGHOME'] = gpghome
+ gpghome_full_path = os.path.abspath(gpghome)
+ self.logger.info("MAIN: _action_genkey; create custom gpg directory: %s" % gpghome_full_path)
+ self.output("\n* Creating gpg folder at %s" % gpghome_full_path)
+ ensure_dirs(gpghome)
+ # Copy default gpg-conf.skel and append glep63 requirements
+ self.output("* Creating gpg.conf file at %s" % gpghome_full_path)
+ newgpgconfpath = os.path.join(gpghome, 'gpg.conf')
+ shutil.copy('/usr/share/gnupg/gpg-conf.skel', newgpgconfpath)
+ with open(newgpgconfpath, 'a') as conf:
+ for line in urlopen(GPG_CONF):
+ conf.write(_unicode(line))
+ # Key generation
+ ctx = gpgme.Context()
+ self.logger.info("MAIN: _action_genkey: Generating GPG key...")
+ self.output("""
+ ____________________
+ < Generating GPG key >
+ --------------------
+ \ ^__^
+ \ (oo)\_______
+ (__)\ )\/
+ ||----w |
+ || ||""")
+ self.output("\n* Give the password for the key. (Pick a strong one)\n")
+ try:
+ result = ctx.genkey(key_params)
+ except gpgme.GpgmeError:
+ self.logger.debug("MAIN: _action_genkey: Aborting... No given password.")
+ self.output("Aborting... No given password.")
+ return False
+ key = ctx.get_key(result.fpr, True)
+ self.logger.debug("MAIN: _action_genkey: Generated key: %s - %s"
+ % (key.uids[0].uid, key.subkeys[0].fpr))
+ self.output("Your new GLEP 63 based OpenPGP key has been created in %s" % gpghome_full_path)
+ self.output("""
+ GPG key info:
+ Full Name: %s,
+ Email: %s,
+ Fingerprint: %s
+ """ % (key.uids[0].name, key.uids[0].email,
+ key.subkeys[0].fpr))
+ self.output("In order to use your new key, place the new gpghome to your ~/.gnupg folder by running the following command:\n"
+ " mv %s ~/.gnupg\n"
+ "Important: If you have another old key in ~/.gnupg please make sure you backup it up first.\n\n"
+ "Please read the FAQ for post-generation steps that are available in: \n"
+ "https://wiki.gentoo.org/wiki/Project:Gentoo-keys/Generating_GLEP_63_based_OpenPGP_keys\n" % gpghome_full_path)
+ return True
+
+ def get_input(self):
+ '''Interactive user input'''
+ self.output("\nGPG key creator based on GLEP 63\n"
+ "(https://wiki.gentoo.org/wiki/GLEP:63)\n")
+ name = py_input("Give your Full Name: ")
+ email = py_input("Give your Email: ")
+ while not re.match(r'[\w.-]+@[\w.-]+', email):
+ self.output("\nBad email input. Try again.")
+ email = py_input("Give your Email: ")
+ print("\nReview:\n Full Name: %s\n Email: %s\n" % (name, email))
+ key_properties = urlopen(SPEC).read()
+ return _unicode(key_properties).format(name, email)
diff --git a/gkeys-gen/gkeygen/cli.py b/gkeys-gen/gkeygen/cli.py
new file mode 100644
index 0000000..e05ea1e
--- /dev/null
+++ b/gkeys-gen/gkeygen/cli.py
@@ -0,0 +1,116 @@
+#
+#-*- coding:utf-8 -*-
+
+from __future__ import print_function
+
+
+import sys
+import argparse
+
+from gkeys.config import GKeysConfig
+from gkeys.log import log_levels, set_logger
+from gkeygen.actions import Actions, Available_Actions
+
+class Main(object):
+ '''Main command line interface class'''
+
+
+ def __init__(self, root=None, config=None, print_results=True):
+ """ Main class init function.
+
+ @param root: string, root path to use
+ @param config: optional GKeysConfig instance, For API use
+ @param print_results: optional boolean, for API use
+ """
+ self.root = root or "/"
+ self.config = config or GKeysConfig(root=root)
+ self.print_results = print_results
+ self.args = None
+
+
+ def __call__(self, args=None):
+ """Main class call function
+
+ @param args: Optional list of argumanets to parse and action to run
+ Defaults to sys.argv[1:]
+ """
+ if args:
+ self.run(self.parse_args(args))
+ else:
+ self.run(self.parse_args(sys.argv[1:]))
+
+
+ def parse_args(self, args):
+ '''Parse a list of aruments
+
+ @param args: list
+ @returns argparse.Namespace object
+ '''
+ #logger.debug('MAIN: parse_args; args: %s' % args)
+ actions = Available_Actions
+ parser = argparse.ArgumentParser(
+ prog='gkeys-gen',
+ description='Gentoo Keys GPG key generator program',
+ epilog='''Caution: adding untrusted keys to these keyrings can
+ be hazardous to your system!''')
+ # actions
+ parser.add_argument('action', choices=actions, nargs='?',
+ default='genkey', help='Generate GPG key based on GLEP 63')
+ # options
+ parser.add_argument('-c', '--config', dest='config', default=None,
+ help='The path to an alternate config file')
+ parser.add_argument('-D', '--debug', default='DEBUG',
+ choices=list(log_levels),
+ help='The logging level to set for the logfile')
+ parser.add_argument('-H', '--homedir', dest='homedir', default=None,
+ help='The destination for the generated key')
+ parser.add_argument('-m', '--mail', dest='mail', default=None,
+ help='The email address to search for')
+ parser.add_argument('-n', '--nick', dest='nick', default=None,
+ help='The nick or user id (uid) to search for')
+ parser.add_argument('-N', '--name', dest='name', default=None,
+ help='The name to search for')
+ return parser.parse_args(args)
+
+
+ def run(self, args):
+ '''Run the args passed in
+
+ @param args: list or argparse.Namespace object
+ '''
+ global logger
+ message = None
+ if not args:
+ message = "Main: run; invalid args argument passed in"
+ if isinstance(args, list):
+ args = self.parse_args(args)
+ if args.config:
+ self.config.defaults['config'] = args.config
+ # now make it load the config file
+ self.config.read_config()
+
+ # establish our logger and update it in the imported files
+ logger = set_logger('gkeys-gen', self.config['logdir'], args.debug,
+ dirmode=int(self.config.get_key('permissions', 'directories'),0),
+ filemask=int(self.config.get_key('permissions', 'files'),0))
+ #config.logger = logger
+
+ if message:
+ logger.error(message)
+
+ # now that we have a logger, record the alternate config setting
+ if args.config:
+ logger.debug("Main: run; Found alternate config request: %s"
+ % args.config)
+
+ # establish our actions instance
+ self.actions = Actions(self.config, print, logger)
+
+ logger.info("Begin running action: %s" % args.action)
+
+ # run the action
+ func = getattr(self.actions, '%s' % args.action)
+
+ logger.debug('Main: run; Found action: %s' % args.action)
+ results = func(args)
+ return results