def test_19_emailtext(self): # create a EMAILTEXT policy: p = set_policy(name="emailtext", action="%s=%s" % (EMAILACTION.EMAILTEXT, "'Your <otp>'"), scope=SCOPE.AUTH) self.assertTrue(p > 0) g = FakeFlaskG() P = PolicyClass() g.policy_object = P options = {"g": g} smtpmock.setdata(response={"*****@*****.**": (200, "OK")}) transactionid = "123456098713" db_token = Token.query.filter_by(serial=self.serial1).first() token = EmailTokenClass(db_token) c = token.create_challenge(transactionid, options=options) self.assertTrue(c[0], c) display_message = c[1] self.assertTrue(c[3].get("state"), transactionid) self.assertEqual(display_message, "Enter the OTP from the Email:") # Test AUTOEMAIL p = set_policy(name="autoemail", action=EMAILACTION.EMAILAUTO, scope=SCOPE.AUTH) self.assertTrue(p > 0) g = FakeFlaskG() P = PolicyClass() g.policy_object = P options = {"g": g} r = token.check_otp("287922", options=options) self.assertTrue(r > 0, r)
def test_09_challenge_response_allowed(self): user = User("cornelius", realm="r1") pin = "test" g = FakeFlaskG() g.policy_object = PolicyClass() options = {"g": g} token = init_token({"type": "hotp", "otpkey": "1234", "pin": pin}, user=user) # With no policy, it will be no chal resp rv = token.is_challenge_request(pin, user=user, options=options) self.assertEqual(rv, False) # Now we set a policy with several tokentypes set_policy(name="pol_chal_resp_1", scope=SCOPE.AUTH, action="{0!s}=hotp tiqr totp".format(ACTION.CHALLENGERESPONSE)) set_policy(name="pol_chal_resp_2", scope=SCOPE.AUTH, action="{0!s}=hotp motp".format(ACTION.CHALLENGERESPONSE)) g = FakeFlaskG() g.policy_object = PolicyClass() g.audit_object = FakeAudit() options = {"g": g} rv = token.is_challenge_request(pin, user=user, options=options) self.assertEqual(rv, True) delete_policy("pol_chal_resp_1")
def test_27_get_default_settings(self): params = {} logged_in_user = {"user": "******", "realm": "default", "role": "user"} set_policy("pol1", scope=SCOPE.USER, action="hotp_hashlib=sha256," "hotp_otplen=8") pol = PolicyClass() p = HotpTokenClass.get_default_settings(params, logged_in_user=logged_in_user, policy_object=pol) self.assertEqual(p.get("otplen"), "8") self.assertEqual(p.get("hashlib"), "sha256") delete_policy("pol1") # the same should work for an admin user logged_in_user = {"user": "******", "realm": "super", "role": "admin"} set_policy("pol1", scope=SCOPE.ADMIN, action="hotp_hashlib=sha512," "hotp_otplen=8") pol = PolicyClass() p = HotpTokenClass.get_default_settings(params, logged_in_user=logged_in_user, policy_object=pol) self.assertEqual(p.get("otplen"), "8") self.assertEqual(p.get("hashlib"), "sha512") # test check if there is no logged in user p = HotpTokenClass.get_default_settings(params, policy_object=pol) self.assertEqual(p, {}) delete_policy("pol1")
def test_14_required_email(self): g.logged_in_user = {"username": "******", "role": "admin"} builder = EnvironBuilder(method='POST', data={'serial': "OATH123456"}, headers={}) env = builder.get_environ() # Set the remote address so that we can filter for it env["REMOTE_ADDR"] = "10.0.0.1" req = Request(env) # Set a mangle policy to change the username # and only use the last 4 characters of the username set_policy(name="email1", scope=SCOPE.REGISTER, action="%s=/.*@mydomain\..*" % ACTION.REQUIREDEMAIL) g.policy_object = PolicyClass() # request, that matches the policy req.all_data = {"email": "*****@*****.**"} # This emails is allowed r = required_email(req) self.assertTrue(r) # This email is not allowed req.all_data = {"email": "*****@*****.**"} # This emails is allowed self.assertRaises(RegistrationError, required_email, req) delete_policy("email1") g.policy_object = PolicyClass() # Without a policy, this email can register req.all_data = {"email": "*****@*****.**"} # This emails is allowed r = required_email(req) self.assertTrue(r)
def test_15_reset_password(self): builder = EnvironBuilder(method='POST', data={ 'user': "******", "realm": self.realm1 }, headers={}) env = builder.get_environ() # Set the remote address so that we can filter for it env["REMOTE_ADDR"] = "10.0.0.1" req = Request(env) # Set a mangle policy to change the username # and only use the last 4 characters of the username set_policy(name="recover", scope=SCOPE.USER, action="%s" % ACTION.RESYNC) g.policy_object = PolicyClass() req.all_data = {"user": "******", "realm": self.realm1} # There is a user policy without password reset, so an exception is # raised self.assertRaises(PolicyError, check_anonymous_user, req, ACTION.PASSWORDRESET) # The password reset is allowed set_policy(name="recover", scope=SCOPE.USER, action="%s" % ACTION.PASSWORDRESET) g.policy_object = PolicyClass() r = check_anonymous_user(req, ACTION.PASSWORDRESET) self.assertEqual(r, True)
def test_17_ui_get_rights(self): P = PolicyClass() logged_in_user = { "username": "******", "role": "admin", "realm": "realm1" } # Without policies, the admin gets all rights = P.ui_get_rights(SCOPE.ADMIN, "realm1", "admin") self.assertEqual(len(rights), 39) # An admin may only enroll Yubikeys set_policy(name="tokenEnroll", scope=SCOPE.ADMIN, action="enrollYUBIKEY") P = PolicyClass() rights = P.ui_get_rights(SCOPE.ADMIN, "realm1", "admin") self.assertEqual(rights, ["enrollYUBIKEY"]) # A user may do something else... set_policy(name="userpol", scope=SCOPE.USER, action="enable") P = PolicyClass() rights = P.ui_get_rights(SCOPE.USER, "realm2", "user") # there was still another policy... self.assertEqual(rights, ["enable", "disable"])
def test_13_remote_user(self): g.logged_in_user = {"username": "******", "role": "admin"} builder = EnvironBuilder(method='POST', data={'serial': "OATH123456"}, headers={}) env = builder.get_environ() # Set the remote address so that we can filter for it env["REMOTE_ADDR"] = "10.0.0.1" env["REMOTE_USER"] = "******" req = Request(env) # A user, for whom the login via REMOTE_USER is allowed. set_policy(name="ruser", scope=SCOPE.WEBUI, action="%s=%s" % (ACTION.REMOTE_USER, REMOTE_USER.ACTIVE)) g.policy_object = PolicyClass() r = is_remote_user_allowed(req) self.assertEqual(r, [REMOTE_USER.ACTIVE]) # Login for the REMOTE_USER is not allowed. # Only allowed for user "super", but REMOTE_USER=admin set_policy(name="ruser", scope=SCOPE.WEBUI, action="%s=%s" % (ACTION.REMOTE_USER, REMOTE_USER.ACTIVE), user="******") g.policy_object = PolicyClass() r = is_remote_user_allowed(req) self.assertEqual(r, []) delete_policy("ruser")
def test_27_get_default_settings(self): params = {} g = FakeFlaskG() g.audit_object = FakeAudit() g.logged_in_user = {"user": "******", "realm": "default", "role": "user"} set_policy("pol1", scope=SCOPE.USER, action="totp_hashlib=sha256," "totp_timestep=60," "totp_otplen=8") g.policy_object = PolicyClass() p = TotpTokenClass.get_default_settings(g, params) self.assertEqual(p.get("otplen"), "8") self.assertEqual(p.get("hashlib"), "sha256") self.assertEqual(p.get("timeStep"), "60") delete_policy("pol1") # the same should work for admins g.logged_in_user = {"user": "******", "realm": "super", "role": "admin"} set_policy("pol1", scope=SCOPE.ADMIN, action="totp_hashlib=sha512," "totp_timestep=60," "totp_otplen=8") g.policy_object = PolicyClass() p = TotpTokenClass.get_default_settings(g, params) self.assertEqual(p.get("otplen"), "8") self.assertEqual(p.get("hashlib"), "sha512") self.assertEqual(p.get("timeStep"), "60") # test check if there is no logged in user g.logged_in_user = None p = TotpTokenClass.get_default_settings(g, params) self.assertEqual(p, {}) delete_policy("pol1")
def test_16_admin_realm(self): P = PolicyClass() logged_in_user = { "username": "******", "role": "admin", "realm": "realm1" } # Without policies, the admin gets all tt = P.ui_get_enroll_tokentypes("127.0.0.1", logged_in_user) self.assertTrue("hotp" in tt) self.assertTrue("totp" in tt) self.assertTrue("motp" in tt) self.assertTrue("sms" in tt) self.assertTrue("spass" in tt) self.assertTrue("sshkey" in tt) self.assertTrue("email" in tt) self.assertTrue("certificate" in tt) self.assertTrue("yubico" in tt) self.assertTrue("yubikey" in tt) self.assertTrue("radius" in tt) # An admin in realm1 may only enroll Yubikeys set_policy(name="tokenEnroll", scope=SCOPE.ADMIN, adminrealm="realm1", action="enrollYUBIKEY") P = PolicyClass() tt = P.ui_get_enroll_tokentypes("127.0.0.1", logged_in_user) self.assertFalse("hotp" in tt) self.assertFalse("totp" in tt) self.assertFalse("motp" in tt) self.assertFalse("sms" in tt) self.assertFalse("spass" in tt) self.assertFalse("sshkey" in tt) self.assertFalse("email" in tt) self.assertFalse("certificate" in tt) self.assertFalse("yubico" in tt) self.assertTrue("yubikey" in tt) self.assertFalse("radius" in tt) # An admin in another admin realm may enroll nothing. logged_in_user = { "username": "******", "role": "admin", "realm": "OtherRealm" } tt = P.ui_get_enroll_tokentypes("127.0.0.1", logged_in_user) self.assertFalse("hotp" in tt) self.assertFalse("totp" in tt) self.assertFalse("motp" in tt) self.assertFalse("sms" in tt) self.assertFalse("spass" in tt) self.assertFalse("sshkey" in tt) self.assertFalse("email" in tt) self.assertFalse("certificate" in tt) self.assertFalse("yubico" in tt) self.assertFalse("yubikey" in tt) self.assertFalse("radius" in tt) delete_policy("tokenEnroll")
def test_06_remote_user(self): delete_all_policies() # test login when no policies are set self.assertEqual(len(PolicyClass().policies), 0, PolicyClass().policies) with self.app.test_request_context('/', method='GET', environ_base={'REMOTE_USER': '******'}): res = self.app.full_dispatch_request() self.assertTrue(res.status_code == 200, res) self.assertTrue( b"<input type=hidden id=REMOTE_USER value=\"\">" in res.data) # test login with remote_user policy set set_policy("remote_user", scope=SCOPE.WEBUI, action="{0!s}=allowed".format(ACTION.REMOTE_USER)) with self.app.test_request_context('/', method='GET', environ_base={'REMOTE_USER': '******'}): res = self.app.full_dispatch_request() self.assertTrue(res.status_code == 200, res) self.assertTrue(b"<input type=hidden id=REMOTE_USER value=\"foo\">" in res.data)
def test_05_get_default_settings(self): params = {} g = FakeFlaskG() g.audit_object = FakeAudit() # trusted path for a user g.logged_in_user = {"user": "******", "realm": "default", "role": "user"} set_policy("pol1", scope=SCOPE.USER, action="{0!s}=tests/testdata/attestation/".format( ACTION.TRUSTED_CA_PATH)) g.policy_object = PolicyClass() p = CertificateTokenClass.get_default_settings(g, params) self.assertEqual(["tests/testdata/attestation/"], p.get(ACTION.TRUSTED_CA_PATH)) delete_policy("pol1") # the same should work for an admin user g.logged_in_user = {"user": "******", "realm": "super", "role": "admin"} set_policy("pol1", scope=SCOPE.ADMIN, action="{0!s}=tests/testdata/attestation/".format( ACTION.TRUSTED_CA_PATH)) g.policy_object = PolicyClass() p = CertificateTokenClass.get_default_settings(g, params) self.assertEqual(["tests/testdata/attestation/"], p.get(ACTION.TRUSTED_CA_PATH)) delete_policy("pol1") # If we have no policy, we revert to default g.policy_object = PolicyClass() p = CertificateTokenClass.get_default_settings(g, params) self.assertEqual(["/etc/privacyidea/trusted_attestation_ca"], p.get(ACTION.TRUSTED_CA_PATH))
def test_19_emailtext(self): # create a EMAILTEXT policy: p = set_policy(name="emailtext", action="{0!s}={1!s}".format(EMAILACTION.EMAILTEXT, "'Your <otp>'"), scope=SCOPE.AUTH) self.assertTrue(p > 0) g = FakeFlaskG() P = PolicyClass() g.policy_object = P options = {"g": g} smtpmock.setdata(response={"*****@*****.**": (200, "OK")}) transactionid = "123456098713" db_token = Token.query.filter_by(serial=self.serial1).first() token = EmailTokenClass(db_token) c = token.create_challenge(transactionid, options=options) self.assertTrue(c[0], c) display_message = c[1] self.assertTrue(c[3].get("state"), transactionid) self.assertEqual(display_message, _("Enter the OTP from the Email:")) _n, mimetype = token._get_email_text_or_subject(options, EMAILACTION.EMAILTEXT) self.assertEqual(mimetype, "plain") # Test AUTOEMAIL p = set_policy(name="autoemail", action=EMAILACTION.EMAILAUTO, scope=SCOPE.AUTH) self.assertTrue(p > 0) g = FakeFlaskG() P = PolicyClass() g.policy_object = P options = {"g": g} r = token.check_otp("287922", options=options) self.assertTrue(r > 0, r) # create a EMAILTEXT policy with template p = set_policy(name="emailtext", action="{0!s}=file:{1!s}".format(EMAILACTION.EMAILTEXT, TEMPLATE_FILE), scope=SCOPE.AUTH) self.assertTrue(p > 0) g = FakeFlaskG() P = PolicyClass() g.policy_object = P options = {"g": g} smtpmock.setdata(response={"*****@*****.**": (200, "OK")}) transactionid = "123456098714" db_token = Token.query.filter_by(serial=self.serial1).first() token = EmailTokenClass(db_token) email_text, mimetype = token._get_email_text_or_subject(options, EMAILACTION.EMAILTEXT) self.assertTrue("<p>Hello,</p>" in email_text) self.assertEqual(mimetype, "html") c = token.create_challenge(transactionid, options=options) self.assertTrue(c[0], c) display_message = c[1] self.assertTrue(c[3].get("state"), transactionid) self.assertEqual(display_message, _("Enter the OTP from the Email:"))
def test_01_otppin(self): my_user = User("cornelius", realm="r1") set_policy(name="pol1", scope=SCOPE.AUTH, action="{0!s}={1!s}".format(ACTION.OTPPIN, ACTIONVALUE.NONE)) g = FakeFlaskG() P = PolicyClass() g.policy_object = P options = {"g": g} # NONE with empty PIN -> success r = auth_otppin(self.fake_check_otp, None, "", options=options, user=my_user) self.assertTrue(r) # NONE with empty PIN -> success, even if the authentication is done # for a serial and not a user, since the policy holds for all realms token = init_token({"type": "HOTP", "otpkey": "1234"}) r = auth_otppin(self.fake_check_otp, token, "", options=options, user=None) self.assertTrue(r) # NONE with some pin -> fail r = auth_otppin(self.fake_check_otp, None, "some pin", options=options, user=my_user) self.assertFalse(r) delete_policy("pol1") set_policy(name="pol1", scope=SCOPE.AUTH, action="{0!s}={1!s}".format(ACTION.OTPPIN, ACTIONVALUE.TOKENPIN)) g = FakeFlaskG() P = PolicyClass() g.policy_object = P options = {"g": g} r = auth_otppin(self.fake_check_otp, None, "FAKE", options=options, user=my_user) self.assertTrue(r) r = auth_otppin(self.fake_check_otp, None, "Wrong Pin", options=options, user=my_user) self.assertFalse(r) delete_policy("pol1")
def test_19_ui_get_menus(self): delete_all_policies() luser = {"username": "******", "role": "admin"} # Without policies, the admin gets all P = PolicyClass() menus = P.ui_get_main_menus(luser) self.assertTrue(MAIN_MENU.USERS in menus) self.assertTrue(MAIN_MENU.TOKENS in menus) self.assertTrue(MAIN_MENU.COMPONENTS in menus) self.assertTrue(MAIN_MENU.CONFIG in menus) self.assertTrue(MAIN_MENU.MACHINES in menus) # Admin has only right to enroll HOTP! :-) set_policy("pol1", scope=SCOPE.ADMIN, user="******", action="enrollHOTP") P = PolicyClass() menus = P.ui_get_main_menus(luser) # Thus he can only see the token menu self.assertTrue(MAIN_MENU.USERS not in menus) self.assertTrue(MAIN_MENU.TOKENS in menus) self.assertTrue(MAIN_MENU.COMPONENTS not in menus) self.assertTrue(MAIN_MENU.CONFIG not in menus) self.assertTrue(MAIN_MENU.MACHINES not in menus) set_policy("pol2", scope=SCOPE.ADMIN, user="******", action=ACTION.USERLIST) P = PolicyClass() menus = P.ui_get_main_menus(luser) # Thus he can only see the token menu self.assertTrue(MAIN_MENU.USERS in menus) self.assertTrue(MAIN_MENU.TOKENS in menus) self.assertTrue(MAIN_MENU.COMPONENTS not in menus) self.assertTrue(MAIN_MENU.CONFIG not in menus) self.assertTrue(MAIN_MENU.MACHINES not in menus) set_policy("pol3", scope=SCOPE.ADMIN, user="******", action=ACTION.MACHINELIST) P = PolicyClass() menus = P.ui_get_main_menus(luser) # Thus he can only see the token menu self.assertTrue(MAIN_MENU.USERS in menus) self.assertTrue(MAIN_MENU.TOKENS in menus) self.assertTrue(MAIN_MENU.COMPONENTS not in menus) self.assertTrue(MAIN_MENU.CONFIG not in menus) self.assertTrue(MAIN_MENU.MACHINES in menus) set_policy("pol4", scope=SCOPE.ADMIN, user="******", action=ACTION.SYSTEMDELETE) P = PolicyClass() menus = P.ui_get_main_menus(luser) # Thus he can only see the token menu self.assertTrue(MAIN_MENU.USERS in menus) self.assertTrue(MAIN_MENU.TOKENS in menus) self.assertTrue(MAIN_MENU.COMPONENTS not in menus) self.assertTrue(MAIN_MENU.CONFIG in menus) self.assertTrue(MAIN_MENU.MACHINES in menus) delete_all_policies()
def test_19_smstext(self): # The single quotes in the smstext "'Your <otp>'" is legacy and results in # the string without single quotes "Your <otp>". smstext_tests = { "'Your <otp>'": r"Your [0-9]{6}", "Your <otp>": r"Your [0-9]{6}", "{user} has the OTP: {otp}": r"Cornelius has the OTP: [0-9]{6}" } for pol_text, result_text in smstext_tests.items(): # create a SMSTEXT policy: p = set_policy(name="smstext", action="{0!s}={1!s}".format(SMSACTION.SMSTEXT, pol_text), scope=SCOPE.AUTH) self.assertTrue(p > 0) g = FakeFlaskG() P = PolicyClass() g.audit_object = FakeAudit() g.policy_object = P options = {"g": g, "user": User("cornelius", self.realm1)} responses.add(responses.POST, self.SMSHttpUrl, body=self.success_body) set_privacyidea_config("sms.providerConfig", self.SMSProviderConfig) db_token = Token.query.filter_by(serial=self.serial1).first() token = SmsTokenClass(db_token) c = token.create_challenge(options=options) self.assertTrue(c[0], c) display_message = c[1] self.assertEqual(display_message, _("Enter the OTP from the SMS:")) self.assertEqual(c[3].get("state"), None) smstext = token._get_sms_text(options) self.assertEqual(pol_text.strip("'"), smstext) r, message = token._send_sms(smstext, options) self.assertRegexpMatches(message, result_text) # Test AUTOSMS p = set_policy(name="autosms", action=SMSACTION.SMSAUTO, scope=SCOPE.AUTH) self.assertTrue(p > 0) g = FakeFlaskG() P = PolicyClass() g.policy_object = P g.audit_object = FakeAudit() options = {"g": g} r = token.check_otp(self.valid_otp_values[5 + len(smstext_tests)], options=options) self.assertTrue(r > 0, r)
def test_07_login_mode(self): # a realm: cornelius@r1: PW: test def check_webui_user_userstore(user_obj, password, options=None, superuser_realms=None, check_otp=False): self.assertEqual(check_otp, False) def check_webui_user_privacyidea(user_obj, password, options=None, superuser_realms=None, check_otp=False): self.assertEqual(check_otp, True) user_obj = User("cornelius", "r1") g = FakeFlaskG() P = PolicyClass() g.policy_object = P g.audit_object = FakeAudit() options = {"g": g} # No policy, the function is called with check_otp=False login_mode(check_webui_user_userstore, user_obj, "", options=options, superuser_realms="", check_otp=False) set_policy(name="pol2", scope=SCOPE.WEBUI, action="{0!s}={1!s}".format(ACTION.LOGINMODE, LOGINMODE.PRIVACYIDEA)) g = FakeFlaskG() P = PolicyClass() g.policy_object = P g.audit_object = FakeAudit() options = {"g": g} # Policy is set, the function is called with check_otp=True login_mode(check_webui_user_privacyidea, user_obj, "", options=options, superuser_realms="", check_otp=False) # Set policy, so that the user is not allowed to login at all set_policy(name="pol2", scope=SCOPE.WEBUI, action="{0!s}={1!s}".format(ACTION.LOGINMODE, LOGINMODE.DISABLE)) g = FakeFlaskG() P = PolicyClass() g.policy_object = P g.audit_object = FakeAudit() options = {"g": g} # Policy is set. Trying to login raises a policy error self.assertRaises(PolicyError, login_mode, check_webui_user_privacyidea, user_obj, "", options=options, superuser_realms="", check_otp=False) delete_policy("pol2")
def test_02_check_serial(self): # http://werkzeug.pocoo.org/docs/0.10/test/#environment-building builder = EnvironBuilder(method='POST', data={'serial': "HOTP123435"}, headers={}) env = builder.get_environ() # Set the remote address so that we can filter for it env["REMOTE_ADDR"] = "10.0.0.1" g.client_ip = env["REMOTE_ADDR"] req = Request(env) # The response contains the token type SPASS res = { "jsonrpc": "2.0", "result": { "status": True, "value": True }, "version": "privacyIDEA test", "id": 1, "detail": { "message": "matching 1 tokens", "serial": "HOTP123456", "type": "hotp" } } resp = Response(json.dumps(res)) # Set a policy, that does not allow the tokentype set_policy(name="pol1", scope=SCOPE.AUTHZ, action="serial=TOTP", client="10.0.0.0/8") g.policy_object = PolicyClass() # The token serial HOTP is not allowed on this client, so an exception # is raised. self.assertRaises(PolicyError, check_serial, req, resp) # A policy, that allows the token spass # Set a policy, that does not allow the tokentype set_policy(name="pol1", scope=SCOPE.AUTHZ, action="serial=HOTP", client="10.0.0.0/8") g.policy_object = PolicyClass() # The token type SPASS is not allowed on this client, so an exception # is raised. r = check_serial(req, resp) jresult = json.loads(r.data) self.assertTrue(jresult.get("result").get("value"))
def test_15_ui_tokentypes(self): P = PolicyClass() logged_in_user = { "username": "******", "role": "admin", "realm": "realm1" } # Without policies, the admin gets all tt = P.ui_get_enroll_tokentypes("127.0.0.1", logged_in_user) self.assertTrue("hotp" in tt) self.assertTrue("totp" in tt) self.assertTrue("motp" in tt) self.assertTrue("sms" in tt) self.assertTrue("spass" in tt) self.assertTrue("sshkey" in tt) self.assertTrue("email" in tt) self.assertTrue("certificate" in tt) self.assertTrue("yubico" in tt) self.assertTrue("yubikey" in tt) self.assertTrue("radius" in tt) # An admin may only enroll Yubikeys set_policy(name="tokenEnroll", scope=SCOPE.ADMIN, action="enrollYUBIKEY") P = PolicyClass() tt = P.ui_get_enroll_tokentypes("127.0.0.1", logged_in_user) self.assertFalse("hotp" in tt) self.assertFalse("totp" in tt) self.assertFalse("motp" in tt) self.assertFalse("sms" in tt) self.assertFalse("spass" in tt) self.assertFalse("sshkey" in tt) self.assertFalse("email" in tt) self.assertFalse("certificate" in tt) self.assertFalse("yubico" in tt) self.assertTrue("yubikey" in tt) self.assertFalse("radius" in tt) # A user may enroll nothing set_policy(name="someUserAction", scope=SCOPE.USER, action="disable") P = PolicyClass() tt = P.ui_get_enroll_tokentypes("127.0.0.1", { "username": "******", "realm": "realm", "role": "user" }) self.assertEqual(len(tt), 0) delete_policy("tokenEnroll")
def test_08_config_lost_token_policy(self): def func1(serial, validity=10, contents="Ccns", pw_len=16, options=None): self.assertEqual(validity, 10) self.assertEqual(contents, "Ccns") self.assertEqual(pw_len, 16) def func2(serial, validity=10, contents="Ccns", pw_len=16, options=None): self.assertEqual(validity, 5) self.assertEqual(contents, "C") self.assertEqual(pw_len, 3) init_token({ "serial": "LOST001", "type": "hotp", "genkey": 1 }, user=User("cornelius", realm="r1")) g = FakeFlaskG() P = PolicyClass() g.policy_object = P g.audit_object = FakeAudit() options = {"g": g} # No policy, the function is called with default values config_lost_token(func1, "LOST001", options=options) set_policy(name="lost_pol2", scope=SCOPE.ENROLL, action="%s=%s, %s=%s," "%s=%s" % (ACTION.LOSTTOKENPWCONTENTS, "C", ACTION.LOSTTOKENVALID, 5, ACTION.LOSTTOKENPWLEN, 3)) g = FakeFlaskG() P = PolicyClass() g.policy_object = P g.audit_object = FakeAudit() options = {"g": g} # Policy is set, the function is called with check_otp=True config_lost_token(func2, "LOST001", options=options)
def get_config_documentation(): """ returns an restructured text document, that describes the complete configuration. """ P = PolicyClass() config = get_from_config() resolvers = get_resolver_list() realms = get_realms() policies = P.list_policies() admins = get_db_admins() context = { "system": socket.getfqdn(socket.gethostname()), "date": datetime.datetime.now().strftime("%Y-%m-%d %H:%M"), "systemconfig": config, "appconfig": current_app.config, "resolverconfig": resolvers, "realmconfig": realms, "policyconfig": policies, "admins": admins } g.audit_object.log({"success": True}) # Three or more line breaks will be changed to two. return re.sub("\n{3,}", "\n\n", render_template("documentation.rst", context=context))
def before_request(): """ This is executed before the request """ ensure_no_config_object() request.all_data = get_all_params(request.values, request.data) privacyidea_server = current_app.config.get("PI_AUDIT_SERVERNAME") or \ request.host g.policy_object = PolicyClass() g.audit_object = getAudit(current_app.config) g.event_config = EventConfiguration() # access_route contains the ip adresses of all clients, hops and proxies. g.client_ip = get_client_ip(request, get_from_config(SYSCONF.OVERRIDECLIENT)) g.audit_object.log({ "success": False, "client": g.client_ip, "client_user_agent": request.user_agent.browser, "privacyidea_server": privacyidea_server, "action": "{0!s} {1!s}".format(request.method, request.url_rule), "action_detail": "", "info": "" })
def test_11_import_policy(self): with self.app.test_request_context('/policy/import/policy.cfg', method='POST', data=dict(file=(POLICYFILE, 'policy.cfg')), headers={'Authorization': self.at}): res = self.app.full_dispatch_request() self.assertTrue(res.status_code == 200, res) result = json.loads(res.data).get("result") self.assertTrue(result["status"] is True, result) self.assertTrue(result["value"] == 2, result) # check if policies are there P = PolicyClass() p1 = P.get_policies(name="importpol1") self.assertTrue(len(p1) == 1, p1) p2 = P.get_policies(name="importpol2") self.assertTrue(len(p2) == 1, p2) # import empty file with self.app.test_request_context( "/policy/import/" "policy_empty_file.cfg", method='POST', data=dict(file=(POLICYEMPTY, "policy_empty_file.cfg")), headers={'Authorization': self.at}): res = self.app.full_dispatch_request() self.assertTrue(res.status_code == 400, res)
def before_request(): """ This is executed before the request """ request.all_data = get_all_params(request.values, request.data) privacyidea_server = current_app.config.get("PI_AUDIT_SERVERNAME") or \ request.host # Create a policy_object, that reads the database audit settings # and contains the complete policy definition during the request. # This audit_object can be used in the postpolicy and prepolicy and it # can be passed to the innerpolicies. g.policy_object = PolicyClass() g.audit_object = getAudit(current_app.config) # access_route contains the ip adresses of all clients, hops and proxies. g.client_ip = request.access_route[0] if request.access_route else \ request.remote_addr g.audit_object.log({ "success": False, "action_detail": "", "client": g.client_ip, "client_user_agent": request.user_agent.browser, "privacyidea_server": privacyidea_server, "action": "{0!s} {1!s}".format(request.method, request.url_rule), "info": "" })
def before_request(): """ This is executed before the request """ privacyidea_server = current_app.config.get("PI_AUDIT_SERVERNAME") or \ request.host g.policy_object = PolicyClass() g.audit_object = getAudit(current_app.config) # We can add logic to use X-Forwarded-For g.client_ip = request.remote_addr g.audit_object.log({ "success": False, "client": g.client_ip, "client_user_agent": request.user_agent.browser, "privacyidea_server": privacyidea_server, "action": "{0!s} {1!s}".format(request.method, request.url_rule), "action_detail": "", "info": "" }) request.all_data = get_all_params(request.values, request.data)
def before_request(): """ This is executed before the request """ ensure_no_config_object() request.all_data = get_all_params(request) privacyidea_server = current_app.config.get("PI_AUDIT_SERVERNAME") or \ request.host # Create a policy_object, that reads the database audit settings # and contains the complete policy definition during the request. # This audit_object can be used in the postpolicy and prepolicy and it # can be passed to the innerpolicies. g.policy_object = PolicyClass() g.audit_object = getAudit(current_app.config) # access_route contains the ip adresses of all clients, hops and proxies. g.client_ip = get_client_ip(request, get_from_config(SYSCONF.OVERRIDECLIENT)) g.serial = getParam(request.all_data, "serial") or None g.audit_object.log({ "success": False, "action_detail": "", "client": g.client_ip, "client_user_agent": request.user_agent.browser, "privacyidea_server": privacyidea_server, "action": "{0!s} {1!s}".format(request.method, request.url_rule), "info": "" })
def is_remote_user_allowed(req): """ Checks if the REMOTE_USER server variable is allowed to be used. .. note:: This is not used as a decorator! :param req: The flask request, containing the remote user and the client IP :return: """ res = False if req.remote_user: loginname, realm = split_user(req.remote_user) realm = realm or get_default_realm() # Check if the remote user is allowed if "client_ip" not in g: g.client_ip = get_client_ip( req, get_from_config(SYSCONF.OVERRIDECLIENT)) if "policy_object" not in g: g.policy_object = PolicyClass() ruser_active = g.policy_object.get_action_values(ACTION.REMOTE_USER, scope=SCOPE.WEBUI, user=loginname, realm=realm, client=g.client_ip) res = ruser_active return res
def before_request(): """ This is executed before the request """ ensure_no_config_object() request.all_data = get_all_params(request.values, request.data) # get additional request information such as parameters in the # call path from the view_args request.all_data.update(request.view_args) request.User = get_user_from_param(request.all_data) privacyidea_server = current_app.config.get("PI_AUDIT_SERVERNAME") or \ request.host # Create a policy_object, that reads the database audit settings # and contains the complete policy definition during the request. # This audit_object can be used in the postpolicy and prepolicy and it # can be passed to the innerpolicies. g.policy_object = PolicyClass() g.audit_object = getAudit(current_app.config, g.startdate) g.event_config = EventConfiguration() # access_route contains the ip addresses of all clients, hops and proxies. g.client_ip = get_client_ip(request, get_from_config(SYSCONF.OVERRIDECLIENT)) # Save the HTTP header in the localproxy object g.request_headers = request.headers g.serial = getParam(request.all_data, "serial", default=None) g.audit_object.log({"success": False, "action_detail": "", "client": g.client_ip, "client_user_agent": request.user_agent.browser, "privacyidea_server": privacyidea_server, "action": "{0!s} {1!s}".format(request.method, request.url_rule), "info": ""})
def test_23_priorities_equal_actions(self): # create two policies with the same action values set_policy(name="email1", scope=SCOPE.AUTH, action="emailtext='text 1'", priority=1) set_policy(name="email2", scope=SCOPE.AUTH, action="emailtext='text 1'", priority=1) # this reduces the action values to unique values P = PolicyClass() self.assertEqual( P.get_action_values(scope=SCOPE.AUTH, action="emailtext"), ["text 1"]) # this is allowed if the policies agree self.assertEqual( P.get_action_values(scope=SCOPE.AUTH, action="emailtext", unique=True), ["text 1"]) set_policy(name="email2", action="emailtext='text 2'") P.reload_from_db() with self.assertRaises(PolicyError): P.get_action_values(scope=SCOPE.AUTH, action="emailtext", unique=True) delete_policy("email1") delete_policy("email2")
def test_01_create_simple_policy(self): p = set_policy(name="pol1", action="read", scope="system") self.assertTrue(p > 0) p = set_policy(name="pol2", action="tokentype=HOTP", scope=SCOPE.AUTHZ) self.assertTrue(p > 0) p = set_policy(name="pol3", action="serial=OATH", scope=SCOPE.AUTHZ) self.assertTrue(p > 0) p = set_policy(name="pol4", action="enroll, init, disable , enable", scope="admin") self.assertTrue(p > 0) P = PolicyClass() policies = P.get_policies(name="pol3") # only one policy found self.assertTrue(len(policies) == 1, len(policies)) policies = P.get_policies(scope=SCOPE.AUTHZ) self.assertTrue(len(policies) == 2, len(policies)) policies = P.get_policies(scope=SCOPE.AUTHZ, action="tokentype") self.assertTrue(len(policies) == 1, len(policies)) policies = P.get_policies(scope="admin", action="disable") self.assertTrue(len(policies) == 1, len(policies)) self.assertTrue(policies[0].get("name") == "pol4")
def test_09_realm_resolver_policy(self): set_policy(name="pol1", scope="s", realm="r1") set_policy(name="pol2", scope="s", realm="r1", resolver="reso1") set_policy(name="pol3", scope="s", realm="", resolver="reso2") set_policy(name="pol4", scope="s", realm="r2", active=True) P = PolicyClass() p = P.get_policies(realm="r1") self.assertTrue(len(p) == 3, p) self.assertTrue(_check_policy_name("pol1", p), p) self.assertTrue(_check_policy_name("pol2", p), p) self.assertTrue(_check_policy_name("pol3", p), p) self.assertFalse(_check_policy_name("pol4", p), p) p = P.get_policies(realm="r2") self.assertTrue(len(p) == 2, p) self.assertFalse(_check_policy_name("pol1", p), p) self.assertFalse(_check_policy_name("pol2", p), p) self.assertTrue(_check_policy_name("pol3", p), p) self.assertTrue(_check_policy_name("pol4", p), p) p = P.get_policies(resolver="reso1") self.assertEqual(len(p), 3) self.assertTrue(_check_policy_name("pol1", p), p) self.assertTrue(_check_policy_name("pol2", p), p) self.assertFalse(_check_policy_name("pol3", p), p) self.assertTrue(_check_policy_name("pol4", p), p) p = P.get_policies(resolver="reso2") self.assertTrue(len(p) == 3, p) self.assertTrue(_check_policy_name("pol1", p), p) self.assertFalse(_check_policy_name("pol2", p), p) self.assertTrue(_check_policy_name("pol3", p), p) self.assertTrue(_check_policy_name("pol4", p), p)