Пример #1
0
def generate_overcloud_passwords(output_file="tripleo-overcloud-passwords",
                                 create_password_file=False):
    """Create the passwords needed for the overcloud

    This will create the set of passwords required by the overcloud, store
    them in the output file path and return a dictionary of passwords. If the
    file already exists the existing passwords will be returned instead,
    """

    log = logging.getLogger(__name__ + ".generate_overcloud_passwords")

    log.debug("Using password file: {0}".format(os.path.abspath(output_file)))

    passwords = {}
    if os.path.isfile(output_file):
        with open(output_file) as f:
            passwords = dict(line.split('=') for line in f.read().splitlines())
    elif not create_password_file:
        raise exceptions.PasswordFileNotFound(
            "The password file could not be found!")

    for name in _PASSWORD_NAMES:
        if not passwords.get(name):
            passwords[name] = passutils.generate_password(
                size=_MIN_PASSWORD_SIZE)

    with open(output_file, 'w') as f:
        for name, password in passwords.items():
            f.write("{0}={1}\n".format(name, password))

    return passwords
Пример #2
0
def addTestData(users, request):
    for i in range(100):
        randPass = generate_password(randint(12, 18))
        user = User(chooseName(), users)
        user.password = randPass
        users.reindex(user)
    return Response('Done!')
Пример #3
0
    def post(self):
        """
        The initial reset step.


        :return:
        """
        parser = reqparse.RequestParser()
        parser.add_argument('team_email',
                            required=True,
                            help='The team email must not be blank')
        args = parser.parse_args()

        # Check if an account actually exists, but don't tell the user!
        result = _db_api_get_authenticated("/team/info/email/" +
                                           args['team_email'])
        if not result:
            return jsonify({'message':
                            'Unable to find team with that email!'}), 400
        else:
            key = generate_password(16)
            reset_args = {}
            reset_args['team_id'] = result['id']
            reset_args['team_email'] = args['team_email']
            set_captcha(key, reset_args)
            url = app.config['MY_URL'] + "/api/reset?key=" + key
            # Send the PW email
            send_verify_msg(args['team_email'], url)
            return jsonify({'message': 'Success'})
Пример #4
0
    def test_getrandstr(self):
        "test getrandstr()"
        def f(*a,**k):
            return utils.getrandstr(utils.rng, *a, **k)

        #count 0
        self.assertEqual(f('abc',0), '')

        #count <0
        self.assertRaises(ValueError, f, 'abc', -1)

        #letters 0
        self.assertRaises(ValueError, f, '', 0)

        #letters 1
        self.assertEqual(f('a',5), 'aaaaa')

        #letters
        x = f(u'abc', 16)
        y = f(u'abc', 16)
        self.assertIsInstance(x, unicode)
        self.assertNotEqual(x,y)
        self.assertEqual(sorted(set(x)), [u'a',u'b',u'c'])

        #bytes
        x = f(b('abc'), 16)
        y = f(b('abc'), 16)
        self.assertIsInstance(x, bytes)
        self.assertNotEqual(x,y)
        #NOTE: decoding this due to py3 bytes
        self.assertEqual(sorted(set(x.decode("ascii"))), [u'a',u'b',u'c'])

        #generate_password
        self.assertEqual(len(utils.generate_password(15)), 15)
Пример #5
0
def generate_overcloud_passwords(output_file="tripleo-overcloud-passwords",
                                 create_password_file=False):
    """Create the passwords needed for the overcloud

    This will create the set of passwords required by the overcloud, store
    them in the output file path and return a dictionary of passwords. If the
    file already exists the existing passwords will be returned instead,
    """

    log = logging.getLogger(__name__ + ".generate_overcloud_passwords")

    log.debug("Using password file: {0}".format(os.path.abspath(output_file)))

    passwords = {}
    if os.path.isfile(output_file):
        with open(output_file) as f:
            passwords = dict(line.split('=') for line in f.read().splitlines())
    elif not create_password_file:
        raise exceptions.PasswordFileNotFound(
            "The password file could not be found!")

    for name in _PASSWORD_NAMES:
        if not passwords.get(name):
            passwords[name] = passutils.generate_password(
                size=_MIN_PASSWORD_SIZE)

    with open(output_file, 'w') as f:
        for name, password in passwords.items():
            f.write("{0}={1}\n".format(name, password))

    return passwords
Пример #6
0
def generate_token(key=None, stamp=None):
    """
    generate a pair of a secret key and a crypto token.

    you can use this to implement a password recovery functionality by
    calling generate_token() and transmitting the returned token to the
    (correct) user (e.g. by email) and storing the returned (secret) key
    into the user's profile on the server side.

    after the user received the token, he returns to the wiki, gives his
    user name or email address and the token he received. read the (secret)
    key from the user profile and call valid_token(key, token) to verify
    if the token is valid. if it is, consider the user authenticated, remove
    the secret key from his profile and let him reset his password.

    :param key: give it to recompute some specific token for verification
    :param stamp: give it to recompute some specific token for verification
    :rtype: 2-tuple
    :returns: key, token (both unicode)
    """
    if key is None:
        key = generate_password(size=32)
    if stamp is None:
        stamp = int(time.time())
    h = hmac.new(str(key), str(stamp), digestmod=hashlib.sha256).hexdigest()
    token = u"{0}-{1}".format(stamp, h)
    return unicode(key), token
Пример #7
0
def generate_token(key=None, stamp=None):
    """
    generate a pair of a secret key and a crypto token.

    you can use this to implement a password recovery functionality by
    calling generate_token() and transmitting the returned token to the
    (correct) user (e.g. by email) and storing the returned (secret) key
    into the user's profile on the server side.

    after the user received the token, he returns to the wiki, gives his
    user name or email address and the token he received. read the (secret)
    key from the user profile and call valid_token(key, token) to verify
    if the token is valid. if it is, consider the user authenticated, remove
    the secret key from his profile and let him reset his password.

    :param key: give it to recompute some specific token for verification
    :param stamp: give it to recompute some specific token for verification
    :rtype: 2-tuple
    :returns: key, token (both unicode)
    """
    if key is None:
        key = generate_password(size=32)
    if stamp is None:
        stamp = int(time.time())
    h = hmac.new(str(key), str(stamp), digestmod=hashlib.sha256).hexdigest()
    token = u"{0}-{1}".format(stamp, h)
    return unicode(key), token
Пример #8
0
    def test_getrandstr(self):
        "test getrandstr()"

        def f(*a, **k):
            return utils.getrandstr(utils.rng, *a, **k)

        #count 0
        self.assertEqual(f('abc', 0), '')

        #count <0
        self.assertRaises(ValueError, f, 'abc', -1)

        #letters 0
        self.assertRaises(ValueError, f, '', 0)

        #letters 1
        self.assertEqual(f('a', 5), 'aaaaa')

        #letters
        x = f(u'abc', 16)
        y = f(u'abc', 16)
        self.assertIsInstance(x, unicode)
        self.assertNotEqual(x, y)
        self.assertEqual(sorted(set(x)), [u'a', u'b', u'c'])

        #bytes
        x = f(b('abc'), 16)
        y = f(b('abc'), 16)
        self.assertIsInstance(x, bytes)
        self.assertNotEqual(x, y)
        #NOTE: decoding this due to py3 bytes
        self.assertEqual(sorted(set(x.decode("ascii"))), [u'a', u'b', u'c'])

        #generate_password
        self.assertEqual(len(utils.generate_password(15)), 15)
Пример #9
0
 def get(self):
     """
     The verify step in password resetting
     :return:
     """
     parser = reqparse.RequestParser()
     parser.add_argument('key',
                         required=True,
                         help='The key must not be empty')
     args = parser.parse_args()
     reset_args = get_captcha(args['key'])
     if reset_args:
         # Generate a new password
         reset_args['password'] = generate_password(16)
         result = _db_api_post_authenticated("/team/changepass", reset_args)
         if not result or result['result'] != 'success':
             # This one is to a human, don't send JSON
             return "Oops! An error occurred resetting your password.  Contact the admins!", 500
         else:
             print "bar"
             send_reset_msg(reset_args['team_email'],
                            reset_args['team_email'],
                            reset_args['password'])
             return "Your password has been reset.  Please check your email!", 200
     else:
         return "Your reset key is invalid! try reset_password() again to get a new one.", 403
Пример #10
0
def generate_passwords(mistralclient=None, stack_env=None):
    """Create the passwords needed for deploying OpenStack via t-h-t.

    This will create the set of passwords required by the undercloud and
    overcloud installers that use tripleo-heat-templates and return them
    as a dict. The mistralclient is optional and only used to obtain
    the previously stored SnmpdReadonlyUserPassword supplied by the
    undercloud to the overcloud deployment.
    """

    passwords = {}

    for name in constants.PASSWORD_PARAMETER_NAMES:
        # Support users upgrading from Mitaka or otherwise creating a plan for
        # a Heat stack that already exists.
        if stack_env and name in stack_env.get('parameter_defaults', {}):
            passwords[name] = stack_env['parameter_defaults'][name]
        elif name.startswith("Ceph"):
            if name == "CephClusterFSID":
                # The FSID must be a UUID
                passwords[name] = six.text_type(uuid.uuid1())
            else:
                # CephX keys aren't random strings
                passwords[name] = create_cephx_key()
        # Since by default generate_password uses all digits and ascii upper
        # & lowercase letters, it provides ~5.95 entropy per character.
        # Make the size of the default authkey 4096 bytes, which should give us
        # ~24000 bits of randomness
        elif name.startswith("PacemakerRemoteAuthkey"):
            passwords[name] = passutils.generate_password(
                size=4096)
        # The underclouds SnmpdReadonlyUserPassword is stored in a mistral env
        # for the overcloud.
        elif mistralclient and name == 'SnmpdReadonlyUserPassword':
            passwords[name] = get_snmpd_readonly_user_password(mistralclient)
        elif name in ('KeystoneCredential0', 'KeystoneCredential1',
                      'KeystoneFernetKey0', 'KeystoneFernetKey1'):
            passwords[name] = create_keystone_credential()
        elif name == 'KeystoneFernetKeys':
            passwords[name] = create_fernet_keys_repo_structure_and_keys()
        elif name == 'MigrationSshKey':
            passwords[name] = create_ssh_keypair()
        else:
            passwords[name] = passutils.generate_password(
                size=_MIN_PASSWORD_SIZE)
    return passwords
Пример #11
0
def generate_passwords(mistralclient=None, stack_env=None):
    """Create the passwords needed for deploying OpenStack via t-h-t.

    This will create the set of passwords required by the undercloud and
    overcloud installers that use tripleo-heat-templates and return them
    as a dict. The mistralclient is optional and only used to obtain
    the previously stored SnmpdReadonlyUserPassword supplied by the
    undercloud to the overcloud deployment.
    """

    passwords = {}

    for name in constants.PASSWORD_PARAMETER_NAMES:
        # Support users upgrading from Mitaka or otherwise creating a plan for
        # a Heat stack that already exists.
        if stack_env and name in stack_env.get('parameter_defaults', {}):
            passwords[name] = stack_env['parameter_defaults'][name]
        elif name.startswith("Ceph"):
            if name == "CephClusterFSID":
                # The FSID must be a UUID
                passwords[name] = six.text_type(uuid.uuid1())
            else:
                # CephX keys aren't random strings
                passwords[name] = create_cephx_key()
        # Since by default generate_password uses all digits and ascii upper
        # & lowercase letters, it provides ~5.95 entropy per character.
        # Make the size of the default authkey 4096 bytes, which should give us
        # ~24000 bits of randomness
        elif name.startswith("PacemakerRemoteAuthkey"):
            passwords[name] = passutils.generate_password(size=4096)
        # The underclouds SnmpdReadonlyUserPassword is stored in a mistral env
        # for the overcloud.
        elif mistralclient and name == 'SnmpdReadonlyUserPassword':
            passwords[name] = get_snmpd_readonly_user_password(mistralclient)
        elif name in ('KeystoneCredential0', 'KeystoneCredential1',
                      'KeystoneFernetKey0', 'KeystoneFernetKey1'):
            passwords[name] = create_keystone_credential()
        elif name == 'KeystoneFernetKeys':
            passwords[name] = create_fernet_keys_repo_structure_and_keys()
        elif name == 'MigrationSshKey':
            passwords[name] = create_ssh_keypair()
        else:
            passwords[name] = passutils.generate_password(
                size=_MIN_PASSWORD_SIZE)
    return passwords
Пример #12
0
 def __init__(self, parent):
     Table.__init__(self, parent, ['name'])
     # create the root user
     randPass = generate_password(randint(12, 18))
     root = User('root', self)
     root.password = randPass
     root.groups = ['group:admin']
     self.reindex(root)
     print "#%d %s:%s" % (root.key, root.name, randPass)
Пример #13
0
    def login(self, login, password):
        if (login == '' or password == ''):
            return 1
        try:
            #Obtention du verrou pour éviter les accès concurrents à la base de données
            self.lock.acquire()
            #On se connecte à la BDD
            conn = psycopg2.connect("dbname=puissance5 user=puissance5 password=Disco<3")

            #On récupère le hash de l'utilisateur
            cur = conn.cursor()
            cur.execute("SELECT password FROM users WHERE login=%s;", (login,))

            #On vérifie qu'un utilisateur de ce nom existe
            if not cur.rowcount:
                self.lock.release()
                return 1

            row = cur.fetchone()

            verify = pbkdf2_sha1.verify(password, row[0])

            #On vérifie que le mot de passe est le bon
            if not verify:
                self.lock.release()
                return 1

            cur.close()
            conn.close()
            self.lock.release()

        except Exception as e:
            self.lock.release()
            print("Echec de l'authentification du client : \n", e)
            return 4

        #Création d'un code aléatoire de 20 caractères qui permettra au serveur de jeu d'identifier le client
        self.magic_code = generate_password(size=20)
        sb = StringBuilder()
        sb.add("4")
        sb.add(login)
        sb.add(str(self.magic_code))
        game_server = Network(False)
        game_server.setHostAddress(self.game_server_address, self.game_server_port)
        game_server.connectToHost()
        #On envoie au serveur de jeu l'information que le client 'login' a le droit de se connecter en présentant le code magic_code
        game_server.send(sb.data.encode())
        res = game_server.receive()
        response = StringExtract(res)
        if response[1] != '0':
            return 4
        game_server.close()
        return 0
Пример #14
0
 def remember_user(self):
     remember_token = generate_password(size=40)
     self.remember_token_hash = pass_handler.encrypt(remember_token)
     try:
         self.storage_handler.call(
             action.update_user,
             self.user_id,
             new_remember_token_hash=self.remember_token_hash,
             new_remember_hash_type="sha512_crypt")
     except:
         raise
     else:
         self.remember_token = remember_token
Пример #15
0
def verify_captcha():
    parser = reqparse.RequestParser()
    parser.add_argument(
        'response',
        location='json',
        required=True,
        help='The 8-letter uppercase CAPTCHA response must not be blank')
    args = parser.parse_args()
    response = args['response'].strip()
    # with open('/tmp/cap.pkl', 'rb') as f:
    #     app.captchas = pickle.load(f)
    #     f.close()
    acct_args = get_captcha(response)
    if acct_args:
        # Generate a password.
        password = generate_password(16)
        acct_args['team_password'] = password
        result = _db_api_post_authenticated("/team/add", acct_args)
        if not result:
            return jsonify(
                {'message': 'An unknown error occurred.  Try again!'}), 400
        if result['result'] != 'success':
            return jsonify({
                'message':
                "Account creation failed because: " + result['fail_reason']
            }), 400
        team_id = result['team_id']
        md = acct_args['metadata']
        try:
            resp = requests.post(
                app.config['DB_API_URL_BASE'] + "/team/metadata/add/" +
                str(team_id),
                data={'label_data_json': json.dumps(md)},
                params={'secret': app.config['DB_API_SECRET']})
            if resp.status_code != 200:
                return jsonify({
                    'message':
                    "A weird error occurred on metadata submission.  Please contact the admins!"
                }), 500
        except:
            return jsonify({
                'message':
                "A weird error occurred on metadata submission.  Please contact the admins!"
            }), 500

        send_password_msg(acct_args['team_email'], acct_args['team_email'],
                          password)
        #return '{"password": '******'"}'
        return jsonify({'message': 'success'})
    else:
        return '{"message": "Incorrect CAPTCHA response!"}', 400
Пример #16
0
 def initiate_confirm(self, timestamp=None):
     if timestamp is None:
         timestamp = datetime.utcnow()
     expire_timestamp = timestamp + timedelta(days=3)
     confirmation_id = generate_password(size=60)
     confirmation_id_hash = pass_handler.encrypt(confirmation_id)
     redis_api.store_confirm(self.email, confirmation_id_hash,
                             expire_timestamp)
     self.request_confirm.apply_async(args=[confirmation_id, 3])
     self.request_confirm.apply_async(args=[confirmation_id, 1],
                                      eta=timestamp + timedelta(days=2))
     self.expire_confirm.apply_async(args=[confirmation_id_hash],
                                     eta=expire_timestamp)
     return confirmation_id
Пример #17
0
def create_token(user_id, expires=None):
	if expires is None:
		expires = token_expire_time()

	token = generate_password(conf.AUTH_TOKEN_LENGTH)

	conf.DB_CONN.execute("""
		INSERT INTO Sessions
			(token, user_id, expires)
		VALUES
			(?, ?, ?)
		""", (token, user_id, expires)
	)
	conf.DB_CONN.commit()

	return token
Пример #18
0
def create_token(user_id, duration=None):
  if duration is None:
    duration = timedelta(minutes=5)

  token = generate_password(token_length)

  db.conn.execute("""
    INSERT INTO Sessions
      (token, user_id, duration, last_accessed)
    VALUES
      (?, ?, ?, ?)
    """, (token, user_id, duration.seconds, datetime.now())
  )
  db.conn.commit()

  return token
Пример #19
0
 def send_new_password(self, email):
     user = self.users.getUsers({'email': email})
     if not user:
         raise EmailError('Email %s not on file' % email)
     password = generate_password(size=10)
     user = user[0]
     self.db.startTransaction()
     try:
         encrypt_password = sha256_crypt.encrypt(password)
         user = self.users.update({'password': encrypt_password}, email)
         self.db.commit()
     except Exception, e:
         emsg = \
             'Unable to change user password: '******'Error: %s' \
             % (e)
         self.logger.error(emsg)
         self.db.rollback()
         raise
Пример #20
0
 def post(self, *args, **kwargs):
     email = self.get_argument('email', None)
     if email:
         data = Data()
         pwd = generate_password(10)
         user = dict(
             email=email,
             pwd=sha256_crypt.encrypt(pwd),
             role='public'
         )
         try:
             data.db.users.insert(user)
         except DuplicateKeyError:
             raise tornado.web.HTTPError(500)
         if mailing.send_register_mail(user, pwd):
             self.finish()
         else:
             raise tornado.web.HTTPError(501)
     else:
         raise tornado.web.HTTPError(500)
Пример #21
0
    def login(self, login, password):
        if (login == '' or password == ''):
            return 1
        try:
            #On se connecte à la boîte à monsieurs
            conn = psycopg2.connect(
                "dbname=puissance5 user=puissance5 password=Disco<3")

            #On récupère le hash du monsieur
            cur = conn.cursor()
            cur.execute("SELECT password FROM users WHERE login=%s;",
                        (login, ))
            if not cur.rowcount:
                return 1

            row = cur.fetchone()
            verify = pbkdf2_sha1.verify(password, row[0])
            if not verify:
                return 1

            cur.close()
            conn.close()

        except Exception as e:
            print("Echec de l'authentification du client : \n", e)
            return 4

        #magic_code = getrandstr(rng, count=20)
        self.magic_code = generate_password(size=20)
        sb = StringBuilder()
        sb.add("4")
        sb.add(login)
        sb.add(str(self.magic_code))
        game_server = Network(False)
        game_server.setHostAddress(self.game_server_address,
                                   self.game_server_port)
        game_server.connectToHost()
        game_server.send(sb.data.encode())
        res = game_server.receive()
        game_server.close()
        return 0
Пример #22
0
    def login(self, login, password):
        if (login == '' or password == ''):
            return 1
        try:
            #On se connecte à la boîte à monsieurs
            conn = psycopg2.connect("dbname=puissance5 user=puissance5 password=Disco<3")

            #On récupère le hash du monsieur
            cur = conn.cursor()
            cur.execute("SELECT password FROM users WHERE login=%s;", (login,))
            if not cur.rowcount:
                return 1

            row = cur.fetchone()
            verify = pbkdf2_sha1.verify(password, row[0])
            if not verify:
                return 1

            cur.close()
            conn.close()

        except Exception as e:
            print("Echec de l'authentification du client : \n", e)
            return 4

        #magic_code = getrandstr(rng, count=20)
        self.magic_code = generate_password(size=20)
        sb = StringBuilder()
        sb.add("4")
        sb.add(login)
        sb.add(str(self.magic_code))
        game_server = Network(False)
        game_server.setHostAddress(self.game_server_address, self.game_server_port)
        game_server.connectToHost()
        game_server.send(sb.data.encode())
        res = game_server.receive()
        game_server.close()
        return 0
Пример #23
0
    def test_getrandstr(self):
        """test getrandstr()"""
        from passlib.utils import getrandstr, rng

        def f(*a, **k):
            return getrandstr(rng, *a, **k)

        # count 0
        self.assertEqual(f('abc', 0), '')

        # count <0
        self.assertRaises(ValueError, f, 'abc', -1)

        # letters 0
        self.assertRaises(ValueError, f, '', 0)

        # letters 1
        self.assertEqual(f('a', 5), 'aaaaa')

        # letters
        x = f(u('abc'), 32)
        y = f(u('abc'), 32)
        self.assertIsInstance(x, unicode)
        self.assertNotEqual(x, y)
        self.assertEqual(sorted(set(x)), [u('a'), u('b'), u('c')])

        # bytes
        x = f(b'abc', 32)
        y = f(b'abc', 32)
        self.assertIsInstance(x, bytes)
        self.assertNotEqual(x, y)
        # NOTE: decoding this due to py3 bytes
        self.assertEqual(sorted(set(x.decode("ascii"))),
                         [u('a'), u('b'), u('c')])

        # generate_password
        from passlib.utils import generate_password
        self.assertEqual(len(generate_password(15)), 15)
Пример #24
0
def generate_overcloud_passwords(output_file="tripleo-overcloud-passwords"):
    """Create the passwords needed for the overcloud

    This will create the set of passwords required by the overcloud, store
    them in the output file path and return a dictionary of passwords. If the
    file already exists the existing passwords will be returned instead,
    """

    passwords = {}
    if os.path.isfile(output_file):
        with open(output_file) as f:
            passwords = dict(line.split('=') for line in f.read().splitlines())

    for name in _PASSWORD_NAMES:
        if not passwords.get(name):
            passwords[name] = passutils.generate_password(
                size=_MIN_PASSWORD_SIZE)

    with open(output_file, 'w') as f:
        for name, password in passwords.items():
            f.write("{0}={1}\n".format(name, password))

    return passwords
Пример #25
0
def generate_overcloud_passwords(output_file="tripleo-overcloud-passwords"):
    """Create the passwords needed for the overcloud

    This will create the set of passwords required by the overcloud, store
    them in the output file path and return a dictionary of passwords. If the
    file already exists the existing passwords will be returned instead,
    """

    passwords = {}
    if os.path.isfile(output_file):
        with open(output_file) as f:
            passwords = dict(line.split('=') for line in f.read().splitlines())

    for name in _PASSWORD_NAMES:
        if not passwords.get(name):
            passwords[name] = passutils.generate_password(
                size=_MIN_PASSWORD_SIZE)

    with open(output_file, 'w') as f:
        for name, password in passwords.items():
            f.write("{0}={1}\n".format(name, password))

    return passwords
Пример #26
0
    def test_getrandstr(self):
        """test getrandstr()"""
        from passlib.utils import getrandstr, rng
        def f(*a,**k):
            return getrandstr(rng, *a, **k)

        # count 0
        self.assertEqual(f('abc',0), '')

        # count <0
        self.assertRaises(ValueError, f, 'abc', -1)

        # letters 0
        self.assertRaises(ValueError, f, '', 0)

        # letters 1
        self.assertEqual(f('a',5), 'aaaaa')

        # letters
        x = f(u('abc'), 32)
        y = f(u('abc'), 32)
        self.assertIsInstance(x, unicode)
        self.assertNotEqual(x,y)
        self.assertEqual(sorted(set(x)), [u('a'),u('b'),u('c')])

        # bytes
        x = f(b'abc', 32)
        y = f(b'abc', 32)
        self.assertIsInstance(x, bytes)
        self.assertNotEqual(x,y)
        # NOTE: decoding this due to py3 bytes
        self.assertEqual(sorted(set(x.decode("ascii"))), [u('a'),u('b'),u('c')])

        # generate_password
        from passlib.utils import generate_password
        self.assertEqual(len(generate_password(15)), 15)
Пример #27
0
def generate_overcloud_passwords(output_file="tripleo-overcloud-passwords"):
    """Create the passwords needed for the overcloud

    This will create the set of passwords required by the overcloud, store
    them in the output file path and return a dictionary of passwords. If the
    file already exists the existing passwords will be returned instead,
    """

    if os.path.isfile(output_file):
        with open(output_file) as f:
            return dict(line.split('=') for line in f.read().splitlines())

    password_names = (
        "OVERCLOUD_ADMIN_PASSWORD",
        "OVERCLOUD_ADMIN_TOKEN",
        "OVERCLOUD_CEILOMETER_PASSWORD",
        "OVERCLOUD_CEILOMETER_SECRET",
        "OVERCLOUD_CINDER_PASSWORD",
        "OVERCLOUD_DEMO_PASSWORD",
        "OVERCLOUD_GLANCE_PASSWORD",
        "OVERCLOUD_HEAT_PASSWORD",
        "OVERCLOUD_HEAT_STACK_DOMAIN_PASSWORD",
        "OVERCLOUD_NEUTRON_PASSWORD",
        "OVERCLOUD_NOVA_PASSWORD",
        "OVERCLOUD_SWIFT_HASH",
        "OVERCLOUD_SWIFT_PASSWORD",
    )

    passwords = dict((p, passutils.generate_password(size=_MIN_PASSWORD_SIZE))
                     for p in password_names)

    with open(output_file, 'w') as f:
        for name, password in passwords.items():
            f.write("{0}={1}\n".format(name, password))

    return passwords
Пример #28
0
def default_pass(size=100):
    '''Used to generate a new default (unused) password for users.'''
    return generate_password(size)
Пример #29
0
def generate_random_password(password_length=None,
                             datastore=None,
                             alpha_first=True):
    """
    Generate and return a random password string.

    :param password_length: Length of password to create. If value is None,
    the default_password_length set in the configuration will be used.
    :param datastore: Datastore name to generate random password for. If
    value is None, default values set in the configuration will be used.
    :param alpha_first: Specify whether the generated password should begin
    with an alphabet.
    :return: A randomly generated password string
    """
    lower_case = 'abcdefghjkmnpqrstuvwxyz'
    upper_case = 'ABCDEFGHJKMNPQRTUVWXYZ'
    numbers = '2346789'
    min_lower_case = cfg.get_configuration_property('password_min_lower_case',
                                                    datastore)
    min_upper_case = cfg.get_configuration_property('password_min_upper_case',
                                                    datastore)
    min_numbers = cfg.get_configuration_property('password_min_numbers',
                                                 datastore)
    min_special_chars = cfg.get_configuration_property(
        'password_min_special_chars', datastore)
    special_chars = cfg.get_configuration_property('password_special_charset',
                                                   datastore)
    password_length = (password_length or cfg.get_configuration_property(
        'default_password_length', datastore))
    choices = [lower_case, upper_case, numbers, special_chars]
    mins = [min_lower_case, min_upper_case, min_numbers, min_special_chars]
    all_choices = (lower_case + upper_case + numbers + special_chars)

    password = bytearray()
    if password_length < 1:
        raise RuntimeError("Length cannot be less than 1")
    total_min = 0
    for index, value in enumerate(mins):
        total_min += value
        if value:
            password.extend(
                passlib_utils.generate_password(
                    size=value, charset=choices[index]).encode('utf-8'))
        if index == 1:
            random.shuffle(password)
    remainder = password_length - total_min
    if total_min > password_length:
        raise RuntimeError("Length cannot be less than %d" % total_min)
    if remainder > 0:
        password.extend(
            passlib_utils.generate_password(
                size=password_length - total_min,
                charset=all_choices).encode('utf-8'))
    if alpha_first:
        last_part = bytearray(password[1:])
        random.shuffle(last_part)
        password = password[:1]
        password.extend(last_part)
    else:
        random.shuffle(password)

    try:
        return password.decode('utf-8')
    except AttributeError:
        return str(password)
Пример #30
0
def generate_random_password(password_length=None, datastore=None,
                             alpha_first=True):
    """
    Generate and return a random password string.

    :param password_length: Length of password to create. If value is None,
    the default_password_length set in the configuration will be used.
    :param datastore: Datastore name to generate random password for. If
    value is None, default values set in the configuration will be used.
    :param alpha_first: Specify whether the generated password should begin
    with an alphabet.
    :return: A randomly generated password string
    """
    lower_case = 'abcdefghjkmnpqrstuvwxyz'
    upper_case = 'ABCDEFGHJKMNPQRTUVWXYZ'
    numbers = '2346789'
    min_lower_case = cfg.get_configuration_property(
        'password_min_lower_case', datastore)
    min_upper_case = cfg.get_configuration_property(
        'password_min_upper_case', datastore)
    min_numbers = cfg.get_configuration_property(
        'password_min_numbers', datastore)
    min_special_chars = cfg.get_configuration_property(
        'password_min_special_chars', datastore)
    special_chars = cfg.get_configuration_property(
        'password_special_charset', datastore)
    password_length = (
        password_length or
        cfg.get_configuration_property('default_password_length', datastore)
    )
    choices = [lower_case, upper_case, numbers, special_chars]
    mins = [min_lower_case, min_upper_case, min_numbers, min_special_chars]
    all_choices = (lower_case + upper_case + numbers + special_chars)

    password = bytearray()
    if password_length < 1:
        raise RuntimeError("Length cannot be less than 1")
    total_min = 0
    for index, value in enumerate(mins):
        total_min += value
        if value:
            password.extend(passlib_utils.generate_password(
                size=value, charset=choices[index]).encode('utf-8'))
        if index == 1:
            random.shuffle(password)
    remainder = password_length - total_min
    if total_min > password_length:
        raise RuntimeError("Length cannot be less than %d" % total_min)
    if remainder > 0:
        password.extend(passlib_utils.generate_password(
            size=password_length - total_min, charset=all_choices)
            .encode('utf-8'))
    if alpha_first:
        last_part = bytearray(password[1:])
        random.shuffle(last_part)
        password = password[:1]
        password.extend(last_part)
    else:
        random.shuffle(password)

    try:
        return password.decode('utf-8')
    except AttributeError:
        return str(password)
Пример #31
0
def generate_captcha():
    font = random_font()
    fg = pyfiglet.Figlet(font)
    code = generate_password(8,charset="ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    captcha = fg.renderText(code)
    return captcha,code
Пример #32
0
def generate_random_password(password_length=CONF.default_password_length):
    return passlib_utils.generate_password(size=password_length)
Пример #33
0
def generate_random_password(password_length=None):
    password_length = password_length or CONF.default_password_length
    return passlib_utils.generate_password(size=password_length)
Пример #34
0
#!/usr/bin/env python

import sys
from passlib.hash import pbkdf2_sha256
from passlib.utils import generate_password

try:
    plaintext = sys.argv[1]
except IndexError:
    plaintext = generate_password()

print(plaintext, pbkdf2_sha256.encrypt(plaintext, rounds=200000, salt_size=16))
Пример #35
0
def generate_random_password(password_length=None):
    password_length = (
        password_length
        or cfg.get_configuration_property('default_password_length'))
    return passlib_utils.generate_password(size=password_length)
Пример #36
0
 def test_generate_password(self):
     """generate_password()"""
     from passlib.utils import generate_password
     warnings.filterwarnings("ignore", "The function.*generate_password\(\) is deprecated")
     self.assertEqual(len(generate_password(15)), 15)
Пример #37
0
def generate_random_password(password_length=None):
    password_length = password_length or CONF.default_password_length
    return passlib_utils.generate_password(size=password_length)
Пример #38
0
 def test_generate_password(self):
     """generate_password()"""
     from passlib.utils import generate_password
     warnings.filterwarnings("ignore", "The function.*generate_password\(\) is deprecated")
     self.assertEqual(len(generate_password(15)), 15)
Пример #39
0
def generate_random_password(password_length=None):
    password_length = (
        password_length or
        cfg.get_configuration_property('default_password_length')
    )
    return passlib_utils.generate_password(size=password_length)
Пример #40
0
def generate_auth_code():
    from passlib.utils import generate_password
    code = generate_password(size=15)
    return code
Пример #41
0
import requests
from passlib.utils import generate_password
import sys
from config import config


def _db_api_post_authenticated(endpoint, args):
    try:
        ret = requests.post(config['DB_API_URL_BASE'] + endpoint,
                            data=args,
                            params={'secret': config['DB_API_SECRET']})
        if ret.status_code == 200:
            result_json = ret.json()
            return result_json
        else:
            raise RuntimeError(ret.text)
    except ValueError:
        return
    except:
        raise


team_id = sys.argv[1]
password = generate_password(16)
print password
reset_args = {}
reset_args['team_id'] = team_id
reset_args['password'] = password
result = _db_api_post_authenticated("/team/changepass", reset_args)
print result
Пример #42
0
def generate(**kwargs):
    """Generate a secure password."""
    return generate_password(**kwargs)
Пример #43
0
 def set_password(self, password=None):
     if password is None:
         password = generate_password()
     self.password = password
Пример #44
0
def generate_random_password(password_length=CONF.default_password_length):
    return passlib_utils.generate_password(size=password_length)
Пример #45
0
#!/usr/bin/env python

import sys
from passlib.hash import pbkdf2_sha256
from passlib.utils import generate_password

try:
  plaintext = sys.argv[1]
except IndexError:
  plaintext = generate_password()

print plaintext, pbkdf2_sha256.encrypt(plaintext, rounds=200000, salt_size=16)