Esempio n. 1
0
    def test_04_logging_config_yaml(self):
        class Config(TestingConfig):
            PI_LOGCONFIG = "tests/testdata/logging.yml"

        with mock.patch.dict("privacyidea.config.config", {"testing": Config}):
            app = create_app(config_name='testing')
            # check the correct initialization of the logging from config file
            logger = logging.getLogger('privacyidea')
            self.assertEqual(logger.level, logging.INFO, logger)
            compare([
                Comparison(
                    'logging.handlers.RotatingFileHandler',
                    baseFilename=os.path.join(dirname, 'privacyidea.log'),
                    formatter=Comparison('privacyidea.lib.log.SecureFormatter',
                                         _fmt="[%(asctime)s][%(process)d]"
                                         "[%(thread)d][%(levelname)s]"
                                         "[%(name)s:%(lineno)d] "
                                         "%(message)s",
                                         strict=False),
                    backupCount=5,
                    level=logging.DEBUG,
                    strict=False)
            ], logger.handlers)
            logger = logging.getLogger('audit')
            self.assertEqual(logger.level, logging.INFO, logger)
            compare([
                Comparison('logging.handlers.RotatingFileHandler',
                           backupCount=14,
                           baseFilename=os.path.join(dirname, 'audit.log'),
                           level=logging.INFO,
                           formatter=None,
                           strict=False)
            ], logger.handlers)
Esempio n. 2
0
def main():
    from privacyidea.app import create_app
    from privacyidea.lib.token import get_tokens, unassign_token, assign_token
    from privacyidea.lib.user import User

    app = create_app(config_name="production",
                     config_file=PI_CONFIG,
                     silent=True)
    with app.app_context():
        tokens = get_tokens(resolver=FROM_RESOLVER)
        for token in tokens:
            user = token.user
            # find user in other resolver
            if user.exist():
                other_user = User(user.login,
                                  resolver=TO_RESOLVER,
                                  realm=MIGRATE_REALM)
                if other_user.exist():
                    print('{0!s}: {1!s} -> {2!s}'.format(
                        token.get_serial(), user, other_user))
                    unassign_token(token.get_serial())
                    token.add_user(other_user)
                else:
                    print(
                        '{0!s}: {1!s} -> Could not find user with login {2!s} '
                        'in resolver {3!s}'.format(token.get_serial(), user,
                                                   user.login, TO_RESOLVER))
            else:
                print('{0!s}: Could not find user for token in resolver '
                      '{1!s}'.format(token.get_serial(), FROM_RESOLVER))
Esempio n. 3
0
 def setUpClass(cls):
     cls.app = create_app('testing', "")
     cls.app_context = cls.app.app_context()
     cls.app_context.push()
     db.create_all()
     # Create an admin for tests.
     create_db_admin(cls.app, "testadmin", "*****@*****.**", "testpw")
    def test_02_app_local_store(self):
        store1 = get_app_local_store()
        store1["hello"] = "world"
        g.test_flag = True

        # We get the same store even if we push another app context for the same app
        with self.app.app_context():
            store2 = get_app_local_store()
            self.assertEqual(store1, store2)
            self.assertEqual(store2["hello"], "world")
            self.assertNotIn("test_flag", g)
            g.test_flag = False

        self.assertEqual(g.test_flag, True)
        g.pop("test_flag")

        # We get a different store if we push a context for another app
        new_app = create_app("testing", "")
        with new_app.app_context():
            store3 = get_app_local_store()
            self.assertNotIn("hello", store3)
            self.assertNotEqual(store3, store1)
            store3["hello"] = "no!"
            store4 = get_app_local_store()
            store3["something"] = "else"
            self.assertEqual(store4["hello"], "no!")
            self.assertEqual(store4["something"], "else")

        self.assertEqual(store1, store2)
        self.assertEqual(store2["hello"], "world")
Esempio n. 5
0
 def setUpClass(cls):
     cls.app = create_app('testing', "")
     cls.app_context = cls.app.app_context()
     cls.app_context.push()
     db.create_all()
     # Create an admin for tests.
     create_db_admin(cls.app, "testadmin", "*****@*****.**", "testpw")
def add_tokeninfo_creation_time(serial, key, value):
    app = create_app(config_name="production",
                     config_file="/etc/privacyidea/pi.cfg",
                     silent=True)

    with app.app_context():
        add_tokeninfo(serial, key, value)
    def test_02_app_local_store(self):
        store1 = get_app_local_store()
        store1["hello"] = "world"
        g.test_flag = True

        # We get the same store even if we push another app context for the same app
        with self.app.app_context():
            store2 = get_app_local_store()
            self.assertEqual(store1, store2)
            self.assertEqual(store2["hello"], "world")
            self.assertNotIn("test_flag", g)
            g.test_flag = False

        self.assertEquals(g.test_flag, True)
        g.pop("test_flag")

        # We get a different store if we push a context for another app
        new_app = create_app("testing", "")
        with new_app.app_context():
            store3 = get_app_local_store()
            self.assertNotIn("hello", store3)
            self.assertNotEqual(store3, store1)
            store3["hello"] = "no!"
            store4 = get_app_local_store()
            store3["something"] = "else"
            self.assertEqual(store4["hello"], "no!")
            self.assertEqual(store4["something"], "else")

        self.assertEqual(store1, store2)
        self.assertEqual(store2["hello"], "world")
Esempio n. 8
0
def setpin(serial):
    app = create_app(config_name="production",
                     config_file="/etc/privacyidea/pi.cfg",
                     silent=True)

    with app.app_context():
        # Set global values
        set_pin(serial, PIN)
Esempio n. 9
0
def assign_ssh_token(serial, username):
    app = create_app(config_name='production',
                     config_file=PI_CONFIG,
                     silent=True)
    with app.app_context():
        attach_token(serial,
                     'ssh',
                     hostname=SSH_HOST,
                     options={'user': username})
Esempio n. 10
0
 def test_02_create_production_app(self):
     app = create_app(config_name='production')
     dc = config['production']()
     members = inspect.getmembers(dc, lambda a: not (inspect.isroutine(a)))
     conf = [
         m for m in members
         if not (m[0].startswith('__') and m[0].endswith('__'))
     ]
     self.assertTrue(all(app.config[k] == v for k, v in conf), app)
Esempio n. 11
0
 def setUpClass(cls):
     cls.app = create_app('altUI', "")
     cls.app_context = cls.app.app_context()
     cls.app_context.push()
     db.create_all()
     # save the current timestamp to the database to avoid hanging cached
     # data
     save_config_timestamp()
     db.session.commit()
Esempio n. 12
0
 def test_01_create_default_app(self):
     # This will create the app with the 'development' configuration
     app = create_app()
     self.assertIsInstance(app, flask.app.Flask, app)
     self.assertEqual(app.env, 'production', app)
     self.assertTrue(app.debug, app)
     self.assertFalse(app.testing, app)
     self.assertEqual(app.import_name, 'privacyidea.app', app)
     self.assertEqual(app.name, 'privacyidea.app', app)
     self.assertTrue(app.response_class == PiResponseClass, app)
     blueprints = [
         'validate_blueprint', 'token_blueprint', 'system_blueprint',
         'resolver_blueprint', 'realm_blueprint', 'defaultrealm_blueprint',
         'policy_blueprint', 'login_blueprint', 'jwtauth', 'user_blueprint',
         'audit_blueprint', 'machineresolver_blueprint',
         'machine_blueprint', 'application_blueprint',
         'caconnector_blueprint', 'cert_blueprint', 'ttype_blueprint',
         'register_blueprint', 'smtpserver_blueprint', 'recover_blueprint',
         'radiusserver_blueprint', 'periodictask_blueprint',
         'privacyideaserver_blueprint', 'eventhandling_blueprint',
         'smsgateway_blueprint', 'client_blueprint',
         'subscriptions_blueprint', 'monitoring_blueprint'
     ]
     self.assertTrue(all(k in app.before_request_funcs for k in blueprints),
                     app)
     self.assertTrue(all(k in app.blueprints for k in blueprints), app)
     extensions = ['sqlalchemy', 'migrate', 'babel']
     self.assertTrue(all(k in extensions for k in app.extensions), app)
     self.assertEqual(app.secret_key, 't0p s3cr3t', app)
     # TODO: check url_map and view_functions
     # check that the configuration was loaded successfully
     # the default configuration is 'development'
     dc = config['development']()
     members = inspect.getmembers(dc, lambda a: not (inspect.isroutine(a)))
     conf = [
         m for m in members
         if not (m[0].startswith('__') and m[0].endswith('__'))
     ]
     self.assertTrue(all(app.config[k] == v for k, v in conf), app)
     # check the correct initialization of the logging
     logger = logging.getLogger('privacyidea')
     self.assertEqual(logger.level, logging.DEBUG, logger)
     compare([
         Comparison('logging.handlers.RotatingFileHandler',
                    baseFilename=os.path.join(dirname, 'privacyidea.log'),
                    formatter=Comparison(
                        'privacyidea.lib.log.SecureFormatter',
                        _fmt="[%(asctime)s][%(process)d]"
                        "[%(thread)d][%(levelname)s]"
                        "[%(name)s:%(lineno)d] "
                        "%(message)s",
                        strict=False),
                    level=logging.DEBUG,
                    strict=False)
     ], logger.handlers)
Esempio n. 13
0
 def setUpClass(cls):
     cls.app = create_app('testing', "")
     cls.app_context = cls.app.app_context()
     cls.app_context.push()
     db.create_all()
     # save the current timestamp to the database to avoid hanging cached
     # data
     save_config_timestamp()
     db.session.commit()
     # Create an admin for tests.
     create_db_admin(cls.app, "testadmin", "*****@*****.**", "testpw")
Esempio n. 14
0
 def setUpClass(cls):
     cls.app = create_app('testing', "")
     cls.app_context = cls.app.app_context()
     cls.app_context.push()
     db.create_all()
     # save the current timestamp to the database to avoid hanging cached
     # data
     save_config_timestamp()
     db.session.commit()
     # Create an admin for tests.
     create_db_admin(cls.app, "testadmin", "*****@*****.**", "testpw")
Esempio n. 15
0
 def setUpClass(cls):
     # Modified setup method to use SharedEngineRegistry
     cls.app = create_app('testing', "")
     cls.app.config['PI_ENGINE_REGISTRY_CLASS'] = 'shared'
     cls.app_context = cls.app.app_context()
     cls.app_context.push()
     db.create_all()
     # save the current timestamp to the database to avoid hanging cached
     # data
     save_config_timestamp()
     db.session.commit()
     # Create an admin for tests.
     create_db_admin(cls.app, "testadmin", "*****@*****.**", "testpw")
Esempio n. 16
0
def get_users(realm, include_inactive):
    app = create_app(config_name="production",
                     config_file="/etc/privacyidea/pi.cfg",
                     silent=True)

    with app.app_context():
        realm = realm or get_default_realm()
        params = {"realm": realm}
        ulist = get_user_list(params)
        active = None
        if include_inactive:
            active = True
        for user in ulist:
            user_obj = User(user.get("username"), realm, user.get("resolver"))
            toks = get_tokens(user=user_obj, active=active)
            if len(toks) == 0:
                print(user.get("username"))
Esempio n. 17
0
def create_token(username, realm, authorization):
    app = create_app(config_name="production",
                     config_file="/etc/privacyidea/pi.cfg",
                     silent=True)

    with app.app_context():

        params = {"type": TOKEN_TYPE, "genkey": 1}
        if username:
            params["user"] = username.strip()
            if realm:
                params["realm"] = realm
            r = requests.post('https://localhost/token/init',
                              verify=False,
                              data=params,
                              headers={"Authorization": authorization})
            serial = r.json().get("detail").get("serial")
            return serial
def create_token(username, realm):
    app = create_app(config_name="production",
                     config_file="/etc/privacyidea/pi.cfg",
                     silent=True)

    with app.app_context():
        # Set global values
        params = {"type": LOCAL_TOKEN}
        if username:
            user = User(username, realm)
        else:
            user = User()

        if LOCAL_TOKEN == "remote":
            # For a remote token, we need some additional parameters
            params["remote.server"] = REMOTE_SERVER
            params["remote.user"] = username
            params["remote.realm"] = REMOTE_REALM
            params_remote = {"type": REMOTE_TOKEN}
            remote_user = User(username, REMOTE_REALM)
            remote_token = init_token(params_remote, remote_user)
        else:
            # For other tokens, we need genkey=1
            params["genkey"] = 1

        if CREATE_LOCAL_TOKEN_VIA_API:
            params["user"] = username
            params["realm"] = realm
            r = requests.post('https://localhost/auth',
                              verify=False,
                              data={
                                  "username": API_USER,
                                  "password": API_PASSWORD
                              })
            authorization = r.json().get("result").get("value").get("token")
            r = requests.post('https://localhost/token/init',
                              verify=False,
                              data=params,
                              headers={"Authorization": authorization})
            serial = r.json().get("detail").get("serial")
        else:
            tok = init_token(params, user)
            serial = tok.token.serial
        return serial
Esempio n. 19
0
def create_token(serial, username):
    app = create_app(config_name="production",
                     config_file="/etc/privacyidea/pi.cfg",
                     silent=True)

    with app.app_context():
        # Set global values
        params = {"type": TOKENTYPE}
        if username:
            user = User(username, REALM)
        else:
            user = User()
        if serial:
            params["serial"] = serial
        password = generate_password(size=PW_LEN, characters=BASE58)
        params["otplen"] = PW_LEN
        params["otpkey"] = password
        tok = init_token(params, user)
        return tok.token.serial, password
Esempio n. 20
0
def import_token(tokenrealm, serial, seed, counter, user):
    app = create_app(config_name="production",
                     config_file="/etc/privacyidea/pi.cfg",
                     silent=True)

    with app.app_context():
        try:
            print(" +- Processing token {0!s}".format(serial))

            if len(seed) == 40:
                hash = "sha1"
            elif len(seed) == 64:
                hash = "sha256"
            else:
                raise Exception("Unsupported seed length: {0!s}.".format(
                    len(seed)))
            init_param = {
                'serial': serial,
                'otpkey': seed,
                'hashlib': hash,
                'description': "imported"
            }
            user_obj = None
            if user.strip():
                # If we have a username, we create a user_obj
                try:
                    user_obj = User(user, tokenrealm)
                except Exception:
                    sys.stderr.write(
                        "+-- Failed to create user {0!s}.".format(user))
            # Imported tokens are usually hardware tokens, with the given user
            token = init_token(init_param,
                               user=user_obj,
                               tokenrealms=[tokenrealm],
                               tokenkind=TOKENKIND.HARDWARE)
            # Set the last OTP counter if it is higher than in the system
            if token.get_otp_count() < int(counter):
                token.set_otp_count(int(counter))
        except Exception as err:
            sys.stderr.write(
                " +-- Failed importing token {0!s}: {1!s}.\n".format(
                    serial, err))
def modify_token(username, realm, ttype):
    app = create_app(config_name="production",
                     config_file="/etc/privacyidea/pi.cfg",
                     silent=True)

    with app.app_context():
        user_obj = User(username, realm)
        if user_obj:
            # Get all active tokens of this types from this user
            toks = get_tokens(user=user_obj, tokentype=ttype, active=True)
            # Delete all SMS tokens.
            for tok_obj in toks:
                serial = tok_obj.token.serial
                if ACTION == "delete":
                    tok_obj.delete_token()
                else:
                    enable_token(serial, False)
                with open(LOGFILE, "a") as f:
                    f.write(u"{0!s}, {1!s}, {2!s}, {3!s}, {4!s}\n".format(
                        datetime.datetime.now().strftime("%Y-%m-%dT%H:%M"),
                        args.username, args.realm, ACTION, serial))
Esempio n. 22
0
def assign_user(resolver, realm, username, email, givenname, surname, serial, pin):
    app = create_app(config_name="production",
                     config_file="/etc/privacyidea/pi.cfg",
                     silent=True)

    with app.app_context():
        # User operations
        try:
            print("+ Processing user {0!s} in {1!s}/{2!s}.".format(username, resolver, realm))
            user_obj = User(username, realm, resolver=resolver)
        except UserError as err:
            sys.stderr.write(" +-- Failed finding user: {0!s}.\n".format(err))
            return

        if not user_obj.exist():
            print(" +- Creating user {0!s} in {1!s}/{2!s}.".format(username, resolver, realm))
            try:
                create_user(resolver, {"username": username,
                                       "email": email,
                                       "givenname": givenname,
                                       "surname": surname}, password="")
                user_obj = User(username, realm, resolver=resolver)
            except UserError as err:
                sys.stderr.write("+-- Failed to create user: {0!s}.\n".format(err))
                return
            except Exception as err:
                sys.stderr.write("+-- Failed to create user: {0!s}.\n".format(err))
                return

        # Token operations
        try:
            print(" +- Processing token {0!s}".format(serial))
            t = assign_token(serial, user_obj, pin)
            print(" +-- Assigned token to user {0!s}.".format(user_obj))
        except TokenAdminError as err:
            sys.stderr.write(" +-- Failed assigning token {0!s}: {1!s}.\n".format(serial, err))
        except ResourceNotFoundError as err:
            sys.stderr.write(" +-- Failed assigning token {0!s}: {1!s}.\n".format(serial, err))
Esempio n. 23
0
    def test_05_logging_config_broken_yaml(self):
        class Config(TestingConfig):
            PI_LOGCONFIG = "tests/testdata/logging_broken.yaml"

        with mock.patch.dict("privacyidea.config.config", {"testing": Config}):
            app = create_app(config_name='testing')
            # check the correct initialization of the logging with the default
            # values since the yaml file is broken
            logger = logging.getLogger('privacyidea')
            self.assertEqual(logger.level, logging.INFO, logger)
            compare([
                Comparison(
                    'logging.handlers.RotatingFileHandler',
                    baseFilename=os.path.join(dirname, 'privacyidea.log'),
                    formatter=Comparison('privacyidea.lib.log.SecureFormatter',
                                         _fmt="[%(asctime)s][%(process)d]"
                                         "[%(thread)d][%(levelname)s]"
                                         "[%(name)s:%(lineno)d] "
                                         "%(message)s",
                                         strict=False),
                    level=logging.INFO,
                    strict=False)
            ], logger.handlers)
Esempio n. 24
0
    def test_01_create_app_graciously(self):
        class Config(TestingConfig):
            PI_JOB_QUEUE_CLASS = "obviously.invalid"

        with mock.patch.dict("privacyidea.config.config", {"testing": Config}):
            app = create_app("testing", "")  # we do not throw an exception
Esempio n. 25
0
#!/usr/bin/env python

import sys
sys.stdout = sys.stderr

from privacyidea.app import create_app
# Now we can select the config file:
application = create_app(config_name="production",
                         config_file="/etc/privacyidea/pi.cfg")
from privacyidea.app import create_app
# Now we can select the config file:
application = create_app(config_name="production",
                         config_file="/etc/privacyidea/pi.cfg")
Esempio n. 27
0
def migrate(config_obj):

    from_app = create_app(config_name="production",
                          config_file=config_obj.PRIVACYIDEA_FROM,
                          silent=True)

    to_app = create_app(config_name="production",
                        config_file=config_obj.PRIVACYIDEA_TO,
                        silent=True)

    new_users = []
    new_tokens = []

    with from_app.app_context():
        # find all the users
        userlist = get_user_list(param=config_obj.MIGRATE_USER_FIND)
        for user in userlist:
            if re.match(config_obj.MIGRATE_USER_PATTERN, user.get("username")):
                new_username = re.sub(config_obj.MIGRATE_USER_PATTERN,
                                      config_obj.MIGRATE_USER_REPLACE,
                                      user.get("username"))
                new_user = {"username": new_username, "tokenlist": []}
                for attr in config_obj.MIGRATE_ATTRIBUTES:
                    new_user[attr] = user.get(attr)

                tokens = get_tokens(
                    user=User(user.get("username"),
                              realm=config_obj.MIGRATE_USER_FIND.get("realm")))
                for token in tokens:
                    new_tokens.append(token_to_dict(token.token))
                    new_user["tokenlist"].append(token.token.serial)
                new_users.append(new_user)

    with to_app.app_context():
        # create the new tokens
        for tok in new_tokens:
            if config_obj.MIGRATE_SERIAL_PATTERN:
                tok["serial"] = re.sub(config_obj.MIGRATE_SERIAL_PATTERN,
                                       config_obj.MIGRATE_SERIAL_REPLACE,
                                       tok["serial"])
            info_list = tok.get("info_list")
            del (tok["info_list"])
            toks = get_tokens(serial=tok.get("serial"))
            if len(toks) > 0:
                print("New token {0!s} aleady exists.".format(
                    tok.get("serial")))
            else:
                create_token_from_dict(tok, info_list)

        # create the new users
        for user in new_users:
            tokenlist = user.get("tokenlist")
            del (user["tokenlist"])

            ul = get_user_list({
                "username": user.get("username"),
                "realm": config_obj.TO_REALM,
                "resolver": config_obj.TO_RESOLVER
            })
            if not ul:
                uid = create_user(config_obj.TO_RESOLVER, user)
                print("Created user {0!s}".format(uid))
            else:
                print("User already exists!")
            user_obj = User(login=user.get("username"),
                            realm=config_obj.TO_REALM,
                            resolver=config_obj.TO_RESOLVER)

            # Assign token
            for serial in tokenlist:
                serial = re.sub(config_obj.MIGRATE_SERIAL_PATTERN,
                                config_obj.MIGRATE_SERIAL_REPLACE, serial)
                print("Assigning token {0!s} to user {1!s}".format(
                    serial, user_obj))
                try:
                    assign_token(serial, user_obj)
                except Exception:
                    print(
                        "Error assigning token - probably the token is already assigned."
                    )
Esempio n. 28
0
    def test_01_create_app_graciously(self):
        class Config(TestingConfig):
            PI_JOB_QUEUE_CLASS = "obviously.invalid"

        with mock.patch.dict("privacyidea.config.config", {"testing": Config}):
            app = create_app("testing", "") # we do not throw an exception
Esempio n. 29
0
def create_default_tokens(realm, auth_token=None, username=None,
                          userinfo_key=None, userinfo_value=None,
                          tokentype=None, check_existing_tokentype=None):
    """
    This method creates the default tokens for the users in the given realm.
    You may add a userinfo condition.
    """
    # for reasons of speed in the unprivileged case, imports are placed here
    from privacyidea.lib.token import init_token, get_tokens
    from privacyidea.lib.user import User, get_user_list
    from privacyidea.app import create_app

    tokentypes = [tokentype] if tokentype else PRIMARY_TOKEN_TYPES

    app = create_app(config_name="production",
                     config_file="/etc/privacyidea/pi.cfg",
                     silent=True)

    with app.app_context():
        # if no username is given, get all users from the specified realm
        if not username:
            user_list = get_user_list({"realm": realm})
            user_objects = [User(user["username"], realm)
                            for user in user_list]
        # else, get only the specified user
        else:
            user_objects = [User(username, realm)]
        for user_obj in user_objects:
            if user_obj.exist():
                if check_userinfo(user_obj, userinfo_key, userinfo_value):
                    for type in tokentypes:
                        serial = None
                        tokens = get_tokens(user=user_obj, tokentype=check_existing_tokentype)
                        # if no token of the specified type exists, create one
                        # create sms token only if mobile number exists
                        if len(tokens) == 0:
                            if (type == "email" and not user_obj.info.get("email")) or \
                               (type == "sms" and not user_obj.get_user_phone(index=0,
                                                                              phone_type='mobile')):
                                log.info("User attribute missing for user {0!s}@{1!s}."
                                         "Cannot create {2!s} token.".format(user_obj.login,
                                                                             user_obj.realm, type))
                                continue
                            else:
                                params = {"type": type}
                                params.update(ADD_PARAMS[type])
                                params.update({"user": user_obj.login, "realm": user_obj.realm})
                                if INIT_VIA_API:
                                    # enroll token via API (triggers event handlers at token_init)
                                    r = requests.post(URL + '/token/init', verify=VERIFY,
                                                      data=params,
                                                      headers={"Authorization": auth_token})
                                    status = r.json().get("result").get("status")
                                    if status is True:
                                        serial = r.json().get("detail").get("serial")
                                    else:
                                        error = r.json().get("result").get("error")
                                        log.info("Enrolling {0!s} token for user {1!s} in realm "
                                                 "{2!s} via API: {3!s}".format(type,
                                                                               user_obj.login,
                                                                               user_obj.realm,
                                                                               error.get("message")))
                                else:
                                    # enroll token via lib method (faster)
                                    token_obj = init_token(params, user_obj)
                                    serial = token_obj.token.serial
                                if serial:
                                    log.info('Enrolled a primary {0!s} token for '
                                             'user {1!s} in realm {2!s}'.format(type,
                                                                                user_obj.login,
                                                                                user_obj.realm))
                        else:
                            log.info("User {0!s} in realm {1!s} already has a {2!s} token. "
                                     "Not creating another one.".format(user_obj.login,
                                                                        user_obj.realm,
                                                                        check_existing_tokentype or "**any**"))
            else:
                log.info('User {0!s} does not exists in any resolver in '
                         'realm {1!s}'.format(user_obj.login, user_obj.realm))
Esempio n. 30
0
def create_token(resolver, realm, tokentype, username, email, givenname,
                 surname, pin):
    app = create_app(config_name="production",
                     config_file="/etc/privacyidea/pi.cfg",
                     silent=True)

    with app.app_context():
        # User operations
        try:
            print("+ Processing user {0!s} in {1!s}/{2!s}.".format(
                username, resolver, realm))
            user_obj = User(username, realm, resolver=resolver)
        except UserError as err:
            sys.stderr.write(" +-- Failed finding user: {0!s}.\n".format(err))
            return

        if not user_obj.exist():
            print(" +- Creating user {0!s} in {1!s}/{2!s}.".format(
                username, resolver, realm))
            try:
                create_user(resolver, {
                    "username": username,
                    "email": email,
                    "givenname": givenname,
                    "surname": surname
                },
                            password="")
            except UserError as err:
                sys.stderr.write(
                    " +-- Failed to create user: {0!s}.\n".format(err))
                return
            except Exception as err:
                sys.stderr.write(
                    " +-- Failed to create user: {0!s}.\n".format(err))
                return

        # Token operations
        try:
            params = {}
            params["user"] = username
            params["realm"] = realm
            params["type"] = tokentype
            params["genkey"] = 1
            params["pin"] = pin
            r = requests.post('https://localhost/auth',
                              verify=False,
                              data={
                                  "username": API_USER,
                                  "password": API_PASSWORD
                              })
            authorization = r.json().get("result").get("value").get("token")
            r = requests.post('https://localhost/token/init',
                              verify=False,
                              data=params,
                              headers={"Authorization": authorization})
            result = r.json().get("result")
            detail = r.json().get("detail")
            if not result.get("status"):
                sys.stderr.write(" +-- Failed to create token: {0!s}\n".format(
                    result.get("error", {}).get("message")))
            if result.get("value"):
                print(" +-- Created token {0!s}.".format(detail.get("serial")))
        except Exception as err:
            sys.stderr.write(
                " +-- Failed to communicated to privacyIDEA: {0!s}\n".format(
                    err))
        for tok in get_tokens(user=user_obj, tokentype=tokentype, active=active,
                              tokeninfo=TOKENINFO or None):
            if tok.token.serial and tok.token.serial != serial:
                remove_token(serial=tok.token.serial)
                log.debug("- Remove token with serial {0!s}".format(tok.token.serial))
        # check remaining tokens
        remaining_tokens = get_tokens(user=user_obj)
        log.debug("User {0!s}@{1!s} has {2!s} remaining tokens."
                  "".format(username, realm, len(remaining_tokens)))
        for tok in remaining_tokens:
            log.debug("~ a {0!s} token with serial {1!s}".format(tok.type.upper(),
                                                                 tok.token.serial))

parser = argparse.ArgumentParser()
parser.add_argument('--serial', required=True, dest='serial',
                    help="The serial of the enrolled token.")
parser.add_argument('--user', required=True, dest='username',
                    help="The username of the user of whom other tokens will be removed.")
parser.add_argument('--realm', required=True, dest='realm',
                    help="The realm of the user to act on.")
args = parser.parse_args()

app = create_app(config_name="production",
                 config_file="/etc/privacyidea/pi.cfg",
                 silent=True)

with app.app_context():
    log.info("Starting script to remove tokens different from {0!s} per {1!s} with tokeninfo {2}"
             "".format(args.serial, REMOVE_OTHER_TOKENS_PER, TOKENINFO))
    remove_other_tokens(args.serial, args.username, args.realm)
Esempio n. 32
0
def assign_user(resolver, realm, username, email, givenname, surname, serial,
                pin, validity, hard_or_soft):
    app = create_app(config_name="production",
                     config_file="/etc/privacyidea/pi.cfg",
                     silent=True)

    with app.app_context():
        # User operations
        try:
            print("+ Processing user {0!s} in {1!s}/{2!s}.".format(
                username, resolver, realm))
            user_obj = User(username, realm, resolver=resolver)
        except UserError as err:
            sys.stderr.write(" +-- Failed finding user: {0!s}.\n".format(err))
            return

        if not user_obj.exist():
            # Create new user
            print(" +- Creating user {0!s} in {1!s}/{2!s}.".format(
                username, resolver, realm))
            try:
                create_user(resolver, {
                    "username": username,
                    "email": email,
                    "givenname": givenname,
                    "surname": surname
                },
                            password="")
                user_obj = User(username, realm, resolver=resolver)
            except UserError as err:
                sys.stderr.write(
                    "+-- Failed to create user: {0!s}.\n".format(err))
                return
            except Exception as err:
                sys.stderr.write(
                    "+-- Failed to create user: {0!s}.\n".format(err))
                return
        else:
            # Update existing user
            print(" +- Updating user {0!s} in {1!s}/{2!s}.".format(
                username, resolver, realm))
            user_obj.update_user_info({
                "email": email,
                "givenname": givenname,
                "surname": surname
            })

        # Token operations

        ## Assign token or create registration code
        if hard_or_soft.strip().upper() == HARDWARE:
            if serial:
                # Assign an existing token
                try:
                    print(" +- Processing token {0!s}".format(serial))
                    t = assign_token(serial, user_obj, pin)
                    print(
                        " +-- Assigned token to user {0!s}.".format(user_obj))
                except TokenAdminError as err:
                    sys.stderr.write(
                        " +-- Failed assigning token {0!s}: {1!s}.\n".format(
                            serial, err))
                except ResourceNotFoundError as err:
                    sys.stderr.write(
                        " +-- Failed assigning token {0!s}: {1!s}.\n".format(
                            serial, err))
            else:
                sys.stderr.write(
                    "+-- User {0!s} is supposed to get a hardware token, but no serial defined!"
                    .format(user_obj))
        elif hard_or_soft.strip().upper() == SOFTWARE:
            # Create a registration code, since no serial number is given
            print(" +- Creating token of type {0!s}.".format(TOKEN_TYPE))
            params = {
                "type": TOKEN_TYPE,
                "genkey": 1,
                "user": user_obj.login,
                "realm": user_obj.realm
            }
            r = requests.post('https://localhost/token/init',
                              verify=False,
                              data=params,
                              headers={"Authorization": get_auth_tok()})
            if not r.json().get("result").get("status"):
                sys.stderr.write(
                    " +-- Failed to create token for user {0!s}.".format(
                        user_obj))
        else:
            sys.stderr.write(
                "+-- Unknown Hard/Soft specifier for user {0!s}: {1!s}".format(
                    user_obj, hard_or_soft))

        # Create RADIUS token with validity period
        print(" +- Creating RADIUS token for user {0!s}.".format(user_obj))
        tok = init_token(
            {
                "type": "radius",
                "radius.identifier": RADIUS_IDENTIFIER,
                "radius.user": user_obj.login
            },
            user=user_obj)
        for k, v in TOKENINFO.items():
            tok.add_tokeninfo(k, v)
        validity_end = datetime.datetime.now() + datetime.timedelta(
            int(validity))
        tok.set_validity_period_end(
            validity_end.strftime("%Y-%m-%d %H:%M:00 CET"))
Esempio n. 33
0
from subprocess import call, Popen
from getpass import getpass
from privacyidea.lib.security.default import DefaultSecurityModule
from privacyidea.lib.auth import (create_db_admin, list_db_admin,
                                  delete_db_admin)
from privacyidea.lib.policy import (delete_policy, enable_policy,
                                    PolicyClass, set_policy)
from privacyidea.app import create_app
from flask.ext.script import Manager
from privacyidea.app import db
from flask.ext.migrate import MigrateCommand
# Wee need to import something, so that the models will be created.
from privacyidea.models import Admin
from Crypto.PublicKey import RSA

app = create_app(config_name='production')
manager = Manager(app)
admin_manager = Manager(usage='Create new administrators or modify existing '
                              'ones.')
backup_manager = Manager(usage='Create database backup and restore')
realm_manager = Manager(usage='Create new realms')
resolver_manager = Manager(usage='Create new resolver')
policy_manager = Manager(usage='Manage policies')
manager.add_command('db', MigrateCommand)
manager.add_command('admin', admin_manager)
manager.add_command('backup', backup_manager)
manager.add_command('realm', realm_manager)
manager.add_command('resolver', resolver_manager)
manager.add_command('policy', policy_manager)

Esempio n. 34
0
def unassign_ssh_token(serial):
    app = create_app(config_name='production',
                     config_file=PI_CONFIG,
                     silent=True)
    with app.app_context():
        detach_token(serial, 'ssh', hostname=SSH_HOST)