def __init__(self): """Initialise the Cryptographic Engine params is a dictionary. Valid keys are: algorithm: Which cipher to use callback: Callback class. keycrypted: This should be set by the database layer. timeout: Time after which key will be forgotten. Default is -1 (disabled). """ algo = config.get_value("Encryption", "algorithm") if len(algo) > 0: self._algo = algo else: raise CryptoException("Parameters missing [%s]" % (e)) callback = config.get_value("Encryption", "callback") if isinstance(callback, Callback): self._callback = callback else: self._callback = None keycrypted = config.get_value("Encryption", "keycrypted") if len(keycrypted) > 0: self._keycrypted = keycrypted else: self._keycrypted = None timeout = config.get_value("Encryption", "timeout") if timeout.isdigit(): self._timeout = timeout else: self._timeout = -1 self._cipher = None
def __init__(self, args, config): self.dbname = config.get_value('Database', 'filename') self.dbtype = config.get_value("Database", "type") if not args.output: self.newdb_name = self.dbname else: self.newdb_name = '.new-%s'.join(os.path.splitext(self.dbname))
def __init__(self): """Initialise the Cryptographic Engine params is a dictionary. Valid keys are: algorithm: Which cipher to use callback: Callback class. keycrypted: This should be set by the database layer. timeout: Time after which key will be forgotten. Default is -1 (disabled). """ algo = config.get_value("Encryption", "algorithm") if len(algo) > 0: self._algo = algo else: raise CryptoException("Parameters missing, no algorithm given") callback = config.get_value("Encryption", "callback") if isinstance(callback, Callback): self._callback = callback else: self._callback = None keycrypted = config.get_value("Encryption", "keycrypted") if len(keycrypted) > 0: self._keycrypted = keycrypted else: self._keycrypted = None timeout = config.get_value("Encryption", "timeout") if timeout.isdigit(): self._timeout = timeout else: self._timeout = -1 self._cipher = None
def get_pass_conf(): numerics = config.get_value("Generator", "numerics").lower() == 'true' # TODO: allow custom leetifying through the config leetify = config.get_value("Generator", "leetify").lower() == 'true' special_chars = config.get_value("Generator", "special_chars" ).lower() == 'true' return numerics, leetify, special_chars
def get(cls, dbver=0.5): """ CryptoEngine.get() -> CryptoEngine Return an instance of CryptoEngine. If no instance is found, a CryptoException is raised. """ if CryptoEngine._instance: return CryptoEngine._instance if CryptoEngine._instance_new: return CryptoEngine._instance_new keycrypted = config.get_value("Encryption", "keycrypted") algo = config.get_value("Encryption", "algorithm") if not algo: raise CryptoException("Parameters missing, no algorithm given") try: timeout = int(config.get_value("Encryption", "timeout")) except ValueError: timeout = -1 kwargs = {'keycrypted': keycrypted, 'algorithm': algo, 'timeout': timeout} if dbver < 0.5: CryptoEngine._instance = CryptoEngineOld(**kwargs) return CryptoEngine._instance if dbver >= 0.5: CryptoEngine._instance_new = CryptoEngine(**kwargs) return CryptoEngine._instance_new
def clean(self): if os.path.exists(config.get_value('Database', 'filename')): os.remove(config.get_value('Database', 'filename')) if os.path.exists(os.path.join(os.path.dirname(__file__), 'testing_config')): os.remove(os.path.join(os.path.dirname(__file__), 'testing_config'))
def get_password(self, default=""): password = getpassword("Password (Blank to generate): ", _defaultwidth, False) if len(password) == 0: length = getinput("Password length (default 7): ", "7") length = int(length) numerics = config.get_value("Generator", "numerics") == 'true'; leetify = config.get_value("Generator", "leetify") == 'true'; (password, dumpme) = generator.generate_password(length, length, True, leetify, numerics) print "New password: %s" % (password) return password else: return password
def get_conf_options(args, OSX): config = get_conf_file(args) xselpath = config.get_value("Global", "xsel") if not xselpath: set_xsel(config, OSX) set_win_colors(config) set_db(args) set_umask(config) set_algorithm(args, config) dbtype = config.get_value("Database", "type") if not dbtype: raise Exception("Could not read the Database type from the config!") return xselpath, dbtype
def print_node(self, node): width = str(tools._defaultwidth) print "Node %d." % (node.get_id()) print ("%" + width + "s %s") % (tools.typeset("Username:"******"%" + width + "s %s") % (tools.typeset("Password:"******"%" + width + "s %s") % (tools.typeset("Url:", Fore.RED), node.get_url()) print ("%" + width + "s %s") % (tools.typeset("Notes:", Fore.RED), node.get_notes()) print tools.typeset("Tags: ", Fore.RED), for t in node.get_tags(): print " %s " % t print def heardEnter(): i, o, e = uselect.select([sys.stdin], [], [], 0.0001) for s in i: if s == sys.stdin: sys.stdin.readline() return True return False def waituntil_enter(somepredicate, timeout, period=0.25): mustend = time.time() + timeout while time.time() < mustend: cond = somepredicate() if cond: break time.sleep(period) self.do_cls("") flushtimeout = int(config.get_value("Global", "cls_timeout")) if flushtimeout > 0: print "Type Enter to flush screen (autoflash in " + "%d sec.)" % flushtimeout waituntil_enter(heardEnter, flushtimeout)
def setUp(self): "test that the right db instance was created" dbver = __DB_FORMAT__ self.dbtype = config.get_value("Database", "type") self.db = factory.create(self.dbtype, dbver) self.tester = SetupTester(dbver) self.tester.create()
def __init__(self, db, hasxsel, callback): """ initialize CLI interface, set up the DB connecion, see if we have xsel ... """ cmd.Cmd.__init__(self) self.intro = "%s %s (c) visit: %s" % (pwman.appname, pwman.version, pwman.website) self._historyfile = config.get_value("Readline", "history") self.hasxsel = hasxsel try: enc = CryptoEngine.get() enc._callback = callback() self._db = db # this cascades down all the way to setting the database key self._db.open() except Exception as e: # pragma: no cover self.error(e) sys.exit(1) try: readline.read_history_file(self._historyfile) except IOError as e: # pragma: no cover pass self.prompt = "pwman> "
def do_set(self, args): argstrs = args.split() try: if len(argstrs) == 0: conf = config.get_conf() for s in conf.keys(): for n in conf[s].keys(): print ("%s.%s = %s" % (s, n, conf[s][n])) elif len(argstrs) == 1: r = re.compile("(.+)\.(.+)") m = r.match(argstrs[0]) if m is None or len(m.groups()) != 2: print ("Invalid option format") self.help_set() return print ("%s.%s = %s" % (m.group(1), m.group(2), config.get_value(m.group(1), m.group(2)))) elif len(argstrs) == 2: r = re.compile("(.+)\.(.+)") m = r.match(argstrs[0]) if m is None or len(m.groups()) != 2: print ("Invalid option format") self.help_set() return config.set_value(m.group(1), m.group(2), argstrs[1]) else: self.help_set() except Exception as e: self.error(e)
def create(self): dbtype = config.get_value("Database", "type") if self.filename: db = factory.create(dbtype, self.dbver, self.filename) else: db = factory.create(dbtype, self.dbver) self.cli = PwmanCliNew(db, self.xselpath, DummyCallback)
def do_set(self, args): argstrs = args.split() try: if len(argstrs) == 0: conf = config.get_conf() for s in conf.keys(): for n in conf[s].keys(): print "%s.%s = %s" % (s, n, conf[s][n]) elif len(argstrs) == 1: r = re.compile("(.+)\.(.+)") m = r.match(argstrs[0]) if m is None or len(m.groups()) != 2: print "Invalid option format" self.help_set() return print "%s.%s = %s" % (m.group(1), m.group(2), config.get_value(m.group(1), m.group(2))) elif len(argstrs) == 2: r = re.compile("(.+)\.(.+)") m = r.match(argstrs[0]) if m is None or len(m.groups()) != 2: print "Invalid option format" self.help_set() return config.set_value(m.group(1), m.group(2), argstrs[1]) else: self.help_set() except Exception, e: self.error(e)
def print_node(self, node): width = tools._defaultwidth print("Node {}.".format(node._id)) print("{} {}".format(tools.typeset("Username:"******"{} {}".format(tools.typeset("Password:"******"{} {}".format(tools.typeset("Url:", Fore.RED).ljust(width), node.url)) print("{} {}".format(tools.typeset("Notes:", Fore.RED).ljust(width), node.notes)) print("{}".format(tools.typeset("Tags: ", Fore.RED)), end=" ") for t in node.tags: print(t) def heardEnterWin(): c = msvcrt.kbhit() if c == 1: ret = msvcrt.getch() if ret is not None: return True return False def waituntil_enter(somepredicate, timeout, period=0.25): mustend = time.time() + timeout while time.time() < mustend: cond = somepredicate() if cond: break time.sleep(period) self.do_cls('') flushtimeout = int(config.get_value("Global", "cls_timeout")) if flushtimeout > 0: print("Press any key to flush screen (autoflash " "in %d sec.)" % flushtimeout) waituntil_enter(heardEnterWin, flushtimeout)
def do_new(self, args): """ can override default config settings the following way: Pwman3 0.2.1 (c) visit: http://github.com/pwman3/pwman3 pwman> n {'leetify':False, 'numerics':True, 'special_chars':True} Password (Blank to generate): """ errmsg = """could not parse config override, please input some"""\ + """ kind of dictionary, e.g.: n {'leetify':False, """\ + """'numerics':True, 'special_chars':True}""" try: username = self.get_username() if args: try: args = ast.literal_eval(args) except Exception: raise Exception(errmsg) if not isinstance(args, dict): raise Exception(errmsg) password = self.get_password(1, **args) else: numerics = config.get_value( "Generator", "numerics").lower() == 'true' # TODO: allow custom leetifying through the config leetify = config.get_value( "Generator", "leetify").lower() == 'true' special_chars = config.get_value( "Generator", "special_chars").lower() == 'true' password = self.get_password(0, numerics=numerics, symbols=leetify, special_signs=special_chars) url = self.get_url() notes = self.get_notes() node = NewNode() node.username = username node.password = password node.url = url node.notes = notes tags = self.get_tags() node.tags = tags self._db.addnodes([node]) print("Password ID: %d" % (node._id)) # when done with node erase it zerome(password) except Exception as e: self.error(e)
def get_password(self, default=""): password = getpassword("Password (Blank to generate): ", _defaultwidth, False) if len(password) == 0: length = getinput("Password length (default 7): ", "7") length = int(length) numerics = config.get_value("Generator", "numerics") == 'true' leetify = config.get_value("Generator", "leetify") == 'true' (password, dumpme) = generator.generate_password(length, length, True, leetify, numerics) print "New password: %s" % (password) return password else: return password
def __init__(self): """Initialise SQLitePwmanDatabase instance.""" Database.__init__(self) try: self._filename = config.get_value('Database', 'filename') except KeyError, e: raise DatabaseException("SQLite: missing parameter [%s]" % (e))
def get_db_version(config, dbtype, args): if os.path.exists(config.get_value("Database", "filename")): dbver = factory.check_db_version(dbtype) if dbver < 0.4 and not args.dbconvert: print(_db_warn) else: dbver = __DB_FORMAT__ return dbver
def __init__(self): """Initialise SQLitePwmanDatabase instance.""" Database.__init__(self) try: self._filename = config.get_value('Database', 'filename') except KeyError, e: raise DatabaseException( "SQLite: missing parameter [%s]" % (e))
def setUp(self): "test that the right db instance was created" dbver = 0.4 self.dbtype = config.get_value("Database", "type") self.db = factory.create(self.dbtype, dbver) self.tester = SetupTester(dbver) self.tester.create() self.orig_config = config._conf.copy() self.orig_config['Encryption'] = {'algorithm': 'AES'}
def backup_old_db(self): print("Will convert the following Database: %s " % self.dbname) if os.path.exists(config.get_value("Database", "filename")): dbver = pwman.data.factory.check_db_version(self.dbtype) self.dbver = float(dbver) backup = '.backup-%s'.join(os.path.splitext(self.dbname)) % \ time.strftime( '%Y-%m-%d-%H:%M') shutil.copy(self.dbname, backup) print("backup created in ", backup)
def typeset(text, color, bold=False, underline=False): # pragma: no cover """ print colored strings using colorama """ if not config.get_value("Global", "colors") == 'yes': return text if bold: text = colorama.Style.BRIGHT + text if underline and not 'win32' in sys.platform: text = ANSI.Underscore + text return color + text + colorama.Style.RESET_ALL
def typeset(text, color, bold=False, underline=False): if not config.get_value("Global", "colors") == "yes": return text if bold: bold = "%d;" % (ANSI.Bold) else: bold = "" if underline: underline = "%d;" % (ANSI.Underline) else: underline = "" return "\033[%s%s%sm%s\033[%sm" % (bold, underline, color, text, ANSI.Reset)
def __init__(self, db): cmd.Cmd.__init__(self) self.intro = "%s %s (c) %s <%s>" % (pwman.appname, pwman.version, pwman.author, pwman.authoremail) self._historyfile = config.get_value("Readline", "history") try: enc = CryptoEngine.get() enc.set_callback(CLICallback()) self._db = db self._db.open() except Exception, e: self.error(e) sys.exit(1)
def get(cls): """ CryptoEngine.get() -> CryptoEngine Return an instance of CryptoEngine. If no instance is found, a CryptoException is raised. """ if (CryptoEngine._instance == None): algo = config.get_value("Encryption", "algorithm") if algo == "Dummy": CryptoEngine._instance = DummyCryptoEngine() else: CryptoEngine._instance = CryptoEngine() return CryptoEngine._instance
def typeset(text, color, bold=False, underline=False): if not config.get_value("Global", "colors") == 'yes': return text if (bold): bold = "%d;" % (ANSI.Bold) else: bold = "" if (underline): underline = "%d;" % (ANSI.Underline) else: underline = "" return "\033[%s%s%sm%s\033[%sm" % (bold, underline, color, text, ANSI.Reset)
def get(cls): """ get() -> CryptoEngine Return an instance of CryptoEngine. If no instance is found, a CryptoException is raised. """ if (CryptoEngine._instance == None): algo = config.get_value("Encryption", "algorithm") if algo == "Dummy": CryptoEngine._instance = DummyCryptoEngine() else: CryptoEngine._instance = CryptoEngine() return CryptoEngine._instance
def __init__(self, filename=None, dbformat=__DB_FORMAT__): """Initialise SQLitePwmanDatabase instance.""" #Database.__init__(self) super(SQLiteDatabaseNewForm, self).__init__() # error handling is implemented in config.get_value # so there's no need to try... except here... if not filename: self._filename = config.get_value('Database', 'filename') else: self._filename = filename if not self._filename: raise DatabaseException(("SQLite: missing config parameter:" " filename")) self.dbformat = dbformat
def check_db_version(): """ check the data base version query the right table """ filename = config.get_value('Database', 'filename') con = sqlite.connect(filename) cur = con.cursor() cur.execute("PRAGMA TABLE_INFO(DBVERSION)") row = cur.fetchone() if row is None: return "0.3" # pragma: no cover try: return row[-2] except IndexError: # pragma: no cover raise DatabaseException("Something seems fishy with the DB")
def __init__(self, db, hasxsel): """ initialize CLI interface, set up the DB connecion, see if we have xsel ... """ cmd.Cmd.__init__(self) self.intro = "%s %s (c) visit: %s" % (pwman.appname, pwman.version, pwman.website) self._historyfile = config.get_value("Readline", "history") self.hasxsel = hasxsel try: enc = CryptoEngine.get() enc.set_callback(CLICallback()) self._db = db self._db.open() except Exception, e: self.error(e) sys.exit(1)
def __init__(self, db, hasxsel): """ initialize CLI interface, set up the DB connecion, see if we have xsel ... """ _dbwarning = ( "\n*** WARNNING: You are using the old db format which" + " uses cPickle, please upgrade your db !!! ***" ) cmd.Cmd.__init__(self) self.intro = "%s %s (c) visit: %s %s" % (pwman.appname, pwman.version, pwman.website, _dbwarning) self._historyfile = config.get_value("Readline", "history") self.hasxsel = hasxsel try: enc = CryptoEngine.get() enc.set_callback(CLICallback()) self._db = db self._db.open() except Exception, e: self.error(e) sys.exit(1)
def getpassword(question, argsgiven=None, width=_defaultwidth, echo=False, reader=getpass.getpass, numerics=False, leetify=False, symbols=False, special_signs=False, length=None): # pragma: no cover # TODO: getpassword should recieve a config insatnce # and generate the policy according to it, # so that getpassword in cli would be simplified if argsgiven == 1 or length: while not length: try: default_length = config.get_value( 'Generator', 'default_pw_length') or '7' length = getinput( "Password length (default %s): " % default_length, default=default_length) length = int(length) except ValueError: print("please enter a proper integer") password, dumpme = generator.generate_password( length, length, True, symbols=leetify, numerics=numerics, special_chars=special_signs) print ("New password: %s" % (password)) return password # no args given while True: a1 = reader(question.ljust(width)) if not a1: return getpassword( '', argsgiven=1, width=width, echo=echo, reader=reader, numerics=numerics, leetify=leetify, symbols=symbols, special_signs=special_signs, length=length) a2 = reader("[Repeat] %s" % (question.ljust(width))) if a1 == a2: if leetify: return generator.leetify(a1) else: return a1 else: print ("Passwords don't match. Try again.")
def print_node(self, node): width = str(tools._defaultwidth) print "Node %d." % (node.get_id()) print ("%" + width+"s %s") % (tools.typeset("Username:"******"%"+width+"s %s") % (tools.typeset("Password:"******"%"+width+"s %s") % (tools.typeset("Url:", Fore.RED), node.get_url()) print ("%"+width+"s %s") % (tools.typeset("Notes:", Fore.RED), node.get_notes()) print tools.typeset("Tags: ", Fore.RED), for t in node.get_tags(): print " %s \n" % t.get_name(), def heardEnterWin(): c = msvcrt.kbhit() if c == 1: ret = msvcrt.getch() if ret is not None: return True return False def waituntil_enter(somepredicate, timeout, period=0.25): mustend = time.time() + timeout while time.time() < mustend: cond = somepredicate() if cond: break time.sleep(period) self.do_cls('') flushtimeout = int(config.get_value("Global", "cls_timeout")) if flushtimeout > 0: print "Press any key to flush screen (autoflash "\ + "in %d sec.)" % flushtimeout waituntil_enter(heardEnterWin, flushtimeout)
def __init__(self): """Initialise MySQLDatabase instance.""" Database.__init__(self) self._tagidcache = {} config.add_defaults({"Database" : {"server": "localhost", "port" : "3306", "database" : "pwman", "table_prefix" : "pwman_"}}) try: self._server = config.get_value('Database', 'server') self._port = config.get_value('Database', 'port') self._user = config.get_value('Database', 'user') self._password = config.get_value('Database', 'password') self._database = config.get_value('Database', 'database') self._prefix = config.get_value('Database', 'table_prefix') except KeyError, e: raise DatabaseException( "MySQL: missing parameter [%s]" % (e))
def __init__(self): """Initialise PostgresqlDatabase instance.""" Database.__init__(self) self._tagidcache = {} config.add_defaults({"Database" : {"server": "localhost", "port" : "5432", "database" : "pwman", "table_prefix" : "pwman_"}}) try: self._server = config.get_value('Database', 'server') self._port = config.get_value('Database', 'port') self._user = config.get_value('Database', 'user') self._password = config.get_value('Database', 'password') self._database = config.get_value('Database', 'database') self._prefix = config.get_value('Database', 'table_prefix') except KeyError, e: raise DatabaseException( "Postgresql: missing parameter [%s]" % (e))
def get_db_version(config, args): dburi = check_db_version(config.get_value("Database", "dburi")) return dburi