def test_04_do_request_success(self):
     radiusmock.setdata(success=True)
     set_privacyidea_config("radius.dictfile", DICT_FILE)
     db_token = Token.query.filter(Token.serial == self.serial1).first()
     token = RadiusTokenClass(db_token)
     otpcount = token.check_otp("123456")
     self.assertTrue(otpcount >= 0, otpcount)
示例#2
0
    def test_00_get_config(self):
        # set the config
        set_privacyidea_config(key="Hallo", value="What?", typ="string",
                               desc="Some dumb value")

        # get the complete config
        conf = get_from_config()
        self.assertTrue("Hallo" in conf, conf)

        conf = get_from_config("Hallo")
        self.assertTrue(conf == "What?", conf)

        conf = get_from_config("Hello", "Does not exist")
        self.assertTrue(conf == "Does not exist", conf)

        conf = get_privacyidea_config()
        self.assertTrue("Hallo" in conf, conf)

        # delete privacyidea config
        delete_privacyidea_config("Hallo")
        conf = get_from_config("Hallo")
        self.assertFalse(conf == "What?", conf)

        # set more values to create a timestamp and overwrite
        set_privacyidea_config(key="k1", value="v1")
        set_privacyidea_config(key="k2", value="v2")
        set_privacyidea_config(key="k3", value="v3")
        conf = get_from_config("k3")
        self.assertTrue(conf == "v3", conf)
        set_privacyidea_config(key="k3", value="new", typ="string", desc="n")
        conf = get_from_config("k3")
        self.assertTrue(conf == "new", conf)
示例#3
0
    def test_10_saml_check(self):
        # test successful authentication
        set_privacyidea_config("ReturnSamlAttributes", "0")
        with self.app.test_request_context(
            "/validate/samlcheck", method="POST", data={"user": "******", "pass": "******"}
        ):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 200, res)
            result = json.loads(res.data).get("result")
            detail = json.loads(res.data).get("detail")
            value = result.get("value")
            attributes = value.get("attributes")
            self.assertEqual(value.get("auth"), True)
            # No SAML return attributes
            self.assertEqual(attributes.get("email"), None)

        set_privacyidea_config("ReturnSamlAttributes", "1")

        with self.app.test_request_context(
            "/validate/samlcheck", method="POST", data={"user": "******", "pass": "******"}
        ):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 200, res)
            result = json.loads(res.data).get("result")
            detail = json.loads(res.data).get("detail")
            value = result.get("value")
            attributes = value.get("attributes")
            self.assertEqual(value.get("auth"), True)
            self.assertEqual(attributes.get("email"), "*****@*****.**")
            self.assertEqual(attributes.get("givenname"), "Cornelius")
            self.assertEqual(attributes.get("mobile"), "+491111111")
            self.assertEqual(attributes.get("phone"), "+491234566")
            self.assertEqual(attributes.get("realm"), "realm1")
            self.assertEqual(attributes.get("username"), "cornelius")
    def test_10_api_endpoint(self):
        fixed = "ebedeeefegeheiej"
        otpkey = "cc17a4d77eaed96e9d14b5c87a02e718"
        uid = "000000000000"
        otps = ["ebedeeefegeheiejtjtrutblehenfjljrirgdihrfuetljtt",
                "ebedeeefegeheiejlekvlrlkrcluvctenlnnjfknrhgtjned",
                "ebedeeefegeheiejktudedbktcnbuntrhdueikggtrugckij",
                "ebedeeefegeheiejjvjncbnffdrvjcvrbgdfufjgndfetieu",
                "ebedeeefegeheiejdruibhvlvktcgfjiruhltketifnitbuk"
        ]

        token = init_token({"type": "yubikey",
                            "otpkey": otpkey,
                            "otplen": len(otps[0]),
                            "yubikey.prefix": fixed,
                            "serial": "UBAM12345678_1"})

        builder = EnvironBuilder(method='GET',
                                 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)
        nonce = "random nonce"
        apiid = "hallo"
        apikey = "1YMEbMZijD3DzL21UfKGnOOI13c="
        set_privacyidea_config("yubikey.apiid.{0!s}".format(apiid), apikey)
        req.all_data = {'id': apiid,
                        "otp": otps[0],
                        "nonce": nonce}
        text_type, result = YubikeyTokenClass.api_endpoint(req, g)
        self.assertEqual(text_type, "plain")
        self.assertTrue("status=OK" in result, result)
        self.assertTrue("nonce={0!s}".format(nonce) in result, result)
示例#5
0
    def test_16_autoresync_hotp(self):
        serial = "autosync1"
        token = init_token({"serial": serial,
                            "otpkey": self.otpkey,
                            "pin": "async"}, User("cornelius", self.realm2))
        set_privacyidea_config("AutoResync", True)
        token.set_sync_window(10)
        token.set_count_window(5)
        # counter = 8, is out of sync
        with self.app.test_request_context('/validate/check',
                                           method='POST',
                                           data={"user":
                                                    "******"+self.realm2,
                                                 "pass": "******"}):
            res = self.app.full_dispatch_request()
            self.assertEqual(res.status_code, 200)
            result = json.loads(res.data).get("result")
            self.assertEqual(result.get("value"), False)

        # counter = 9, will be autosynced.
        # Authentication is successful
        with self.app.test_request_context('/validate/check',
                                           method='POST',
                                           data={"user":
                                                    "******"+self.realm2,
                                                 "pass": "******"}):
            res = self.app.full_dispatch_request()
            self.assertEqual(res.status_code, 200)
            result = json.loads(res.data).get("result")
            self.assertEqual(result.get("value"), True)

        delete_privacyidea_config("AutoResync")
 def test_08_config_object(self):
     set_privacyidea_config(key="k1", value="v1")
     self.assertEqual(get_config_object().get_config("k1"), "v1")
     set_privacyidea_config(key="k1", value="v2")
     # not updated yet
     self.assertEqual(get_config_object().get_config("k1"), "v1")
     # updated now
     self.assertEqual(update_config_object().get_config("k1"), "v2")
    def test_20_questionnaire(self):
        pin = "pin"
        serial = "QUST1234"
        questions = {"frage1": "antwort1",
                     "frage2": "antwort2",
                     "frage3": "antwort3"}
        j_questions = json.dumps(questions)

        with self.app.test_request_context('/token/init',
                                           method='POST',
                                           data={"type": "question",
                                                 "pin": pin,
                                                 "serial": serial,
                                                 "questions": j_questions},
                                           headers={'Authorization': self.at}):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 400, res)

        set_privacyidea_config("question.num_answers", 2)
        with self.app.test_request_context('/token/init',
                                           method='POST',
                                           data={"type": "question",
                                                 "pin": pin,
                                                 "serial": serial,
                                                 "questions": j_questions},
                                           headers={'Authorization': self.at}):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 200, res)
            result = json.loads(res.data).get("result")
            value = result.get("value")
            self.assertEqual(value, True)

        # Start a challenge
        with self.app.test_request_context('/validate/check',
                                           method='POST',
                                           data={"serial": serial,
                                                 "pass": pin}):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 200, res)
            result = json.loads(res.data).get("result")
            self.assertFalse(result.get("value"))
            detail = json.loads(res.data).get("detail")
            transaction_id = detail.get("transaction_id")
            question = detail.get("message")
            self.assertTrue(question in questions)

        # Respond to the challenge
        answer = questions[question]
        with self.app.test_request_context('/validate/check',
                                           method='POST',
                                           data={"serial": serial,
                                                 "transaction_id":
                                                     transaction_id,
                                                 "pass": answer}):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 200, res)
            result = json.loads(res.data).get("result")
            self.assertEqual(result.get("value"), True)
示例#8
0
    def test_000_setup_realms(self):
        self.setUp_user_realms()
        # U2F is not configured yet
        with self.app.test_request_context('/ttype/u2f',
                                           method='GET'):
            res = self.app.full_dispatch_request()
            self.assertEqual(res.status_code, 400)

        set_privacyidea_config("u2f.appId", "http://localhost:5000")
示例#9
0
    def test_06_u2f_enrollment_fails_wrong_issuer(self):
        # test data taken from
        # https://fidoalliance.org/specs/fido-u2f-v1.0-ps-20141009/fido-u2f-raw-message-formats-ps-20141009.html#examples
        serial = "U2F0010BF6F"
        set_privacyidea_config("u2f.appId",
                               "https://puck.az.intern")
        pin = "test"
        # Registration data
        client_data = "eyJ0eXAiOiJuYXZpZ2F0b3IuaWQuZmluaXNoRW5yb2xsbWVudCIsImNoYWxsZW5nZSI6ImpIakIxaEM2VjA3dDl4ZnNNaDRfOEQ3U1JuSHRFY1BqUTdsaVl3cWxkX009Iiwib3JpZ2luIjoiaHR0cHM6Ly9wdWNrLmF6LmludGVybiIsImNpZF9wdWJrZXkiOiJ1bnVzZWQifQ"
        reg_data = "BQRHjwxEYFCkLHz3xdrmifKOHl2h17BmRJQ_S1Y9PRAhS2R186T391YE-ryqWis9HSmdp0XpRqUaKk9L8lxJTPpTQF_xFJ_LAsKkPTzKIwUlPIjGZDsLmv0en2Iya17Yz8X8OS89fuxwZOvEok-NQOKUTJP3att_RVe3dEAbq_iOtyAwggJEMIIBLqADAgECAgRVYr6gMAsGCSqGSIb3DQEBCzAuMSwwKgYDVQQDEyNZdWJpY28gVTJGIFJvb3QgQ0EgU2VyaWFsIDQ1NzIwMDYzMTAgFw0xNDA4MDEwMDAwMDBaGA8yMDUwMDkwNDAwMDAwMFowKjEoMCYGA1UEAwwfWXViaWNvIFUyRiBFRSBTZXJpYWwgMTQzMjUzNDY4ODBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABEszH3c9gUS5mVy-RYVRfhdYOqR2I2lcvoWsSCyAGfLJuUZ64EWw5m8TGy6jJDyR_aYC4xjz_F2NKnq65yvRQwmjOzA5MCIGCSsGAQQBgsQKAgQVMS4zLjYuMS40LjEuNDE0ODIuMS41MBMGCysGAQQBguUcAgEBBAQDAgUgMAsGCSqGSIb3DQEBCwOCAQEArBbZs262s6m3bXWUs09Z9Pc-28n96yk162tFHKv0HSXT5xYU10cmBMpypXjjI-23YARoXwXn0bm-BdtulED6xc_JMqbK-uhSmXcu2wJ4ICA81BQdPutvaizpnjlXgDJjq6uNbsSAp98IStLLp7fW13yUw-vAsWb5YFfK9f46Yx6iakM3YqNvvs9M9EUJYl_VrxBJqnyLx2iaZlnpr13o8NcsKIJRdMUOBqt_ageQg3ttsyq_3LyoNcu7CQ7x8NmeCGm_6eVnZMQjDmwFdymwEN4OxfnM5MkcKCYhjqgIGruWkVHsFnJa8qjZXneVvKoiepuUQyDEJ2GcqvhU2YKY1zBFAiEA4ZkIXXyjEPExcMGtW6kJXqYv7UHgjxJR5h3H9w9FV7gCIFGdhxZDqwCQKplDi-LU4WJ45OyCpNK6lGa72eZqUR_k"
        # Authentication data
        transaction_id = "05871369157706202013"
        challenge = "1616515928c389ba9e028d83eb5f63782cbf351ca6abbc81aeb0dddd4895b609"
        # challenge = "FhZRWSjDibqeAo2D619jeCy_NRymq7yBrrDd3UiVtgk"
        key_handle = "X_EUn8sCwqQ9PMojBSU8iMZkOwua_R6fYjJrXtjPxfw5Lz1-7HBk68SiT41A4pRMk_dq239FV7d0QBur-I63IA"
        client_data_auth = "eyJ0eXAiOiJuYXZpZ2F0b3IuaWQuZ2V0QXNzZXJ0aW9uIiwiY2hhbGxlbmdlIjoiRmhaUldTakRpYnFlQW8yRDYxOWplQ3lfTlJ5bXE3eUJyckRkM1VpVnRnayIsIm9yaWdpbiI6Imh0dHBzOi8vcHVjay5hei5pbnRlcm4iLCJjaWRfcHVia2V5IjoidW51c2VkIn0"
        signature_data = "AQAAAAMwRQIgU8d6waOIRVVydg_AXxediEZGkfFioUjd6FG3OxH2wUMCIQDpxzavJyxRlMwgNmD1Kw-iw_oP2egdshU9hrpxFHTRzQ"

        # step 1
        with self.app.test_request_context('/token/init',
                                           method='POST',
                                           data={"type": "u2f",
                                                 "user": "******",
                                                 "realm": self.realm1,
                                                 "serial": serial},
                                           headers={'Authorization': self.at}):
            res = self.app.full_dispatch_request()
            self.assertEqual(res.status_code, 200)
            result = json.loads(res.data).get("result")
            detail = json.loads(res.data).get("detail")
            self.assertEqual(result.get("status"), True)
            self.assertEqual(result.get("value"), True)

        set_policy(name="u2f01", scope=SCOPE.ENROLL,
                   action="{0!s}=issuer/.*Plugup.*/".format(U2FACTION.REQ))

        # Init step 2
        with self.app.test_request_context('/token/init',
                                           method='POST',
                                           data={"type": "u2f",
                                                 "serial": serial,
                                                 "regdata": reg_data,
                                                 "clientdata": client_data},
                                           headers={'Authorization': self.at}):
            res = self.app.full_dispatch_request()
            self.assertEqual(res.status_code, 403)
            result = json.loads(res.data).get("result")
            detail = json.loads(res.data).get("detail")
            self.assertEqual(result.get("status"), False)
            self.assertEqual(result.get("error").get("message"),
                             u'The U2F device is not allowed to be registered '
                             u'due to policy restriction.')

        delete_policy("u2f01")
        remove_token(serial)
    def test_04_check_otp_success_with_post_request(self):
        set_privacyidea_config("yubico.do_post", True)
        responses.add(responses.POST, YUBICO_URL,
                      body=self.success_body)

        db_token = Token.query.filter(Token.serial == self.serial1).first()
        token = YubicoTokenClass(db_token)
        otpcount = token.check_otp("vvbgidlghkhgndujklhhudbcuttkcklhvjktrjrt")
        # Nonce and hash do not match
        self.assertTrue(otpcount == -2, otpcount)
        set_privacyidea_config("yubico.do_post", False)
示例#11
0
    def test_15_validate_at_sign(self):
        self.setUp_user_realm2()
        serial1 = "Split001"
        serial2 = "Split002"
        init_token({"serial": serial1,
                    "type": "spass",
                    "pin": serial1}, user=User("cornelius", self.realm1))

        init_token({"serial": serial2,
                    "type": "spass",
                    "pin": serial2}, user=User("cornelius", self.realm2))

        with self.app.test_request_context('/validate/check',
                                           method='POST',
                                           data={"user": "******",
                                                 "pass": serial1}):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 200, res)
            result = json.loads(res.data).get("result")
            self.assertTrue(result.get("value"))

        set_privacyidea_config("splitAtSign", "0")
        with self.app.test_request_context('/validate/check',
                                           method='POST',
                                           data={"user":
                                                    "******"+self.realm2,
                                                 "pass": serial2}):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 400, res)

        set_privacyidea_config("splitAtSign", "1")
        with self.app.test_request_context('/validate/check',
                                           method='POST',
                                           data={"user":
                                                    "******"+self.realm2,
                                                 "pass": serial2}):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 200, res)
            result = json.loads(res.data).get("result")
            self.assertTrue(result.get("value"))

        # The default behaviour - if the config entry does not exist,
        # is to split the @Sign
        delete_privacyidea_config("splitAtSign")
        with self.app.test_request_context('/validate/check',
                                           method='POST',
                                           data={"user":
                                                    "******"+self.realm2,
                                                 "pass": serial2}):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 200, res)
            result = json.loads(res.data).get("result")
            self.assertTrue(result.get("value"))
    def test_06_do_request_success_remote_user(self):
        # verify SSL
        set_privacyidea_config("remote.verify_ssl_certificate", True)
        responses.add(responses.POST,
                      "http://my.privacyidea.server/validate/check",
                      body=json.dumps(self.success_body),
                      content_type="application/json")

        db_token = Token.query.filter(Token.serial == self.serial2).first()
        token = RemoteTokenClass(db_token)
        otpcount = token.check_otp("123456")
        self.assertTrue(otpcount > 0, otpcount)
示例#13
0
 def test_02_reset_password(self):
     smtpmock.setdata(response={"*****@*****.**": (200, "OK")})
     set_privacyidea_config("recovery.identifier", "myserver")
     with self.app.test_request_context(
         "/recover",
         method="POST",
         data={"user": "******", "realm": "register", "email": "*****@*****.**"},
     ):
         res = self.app.full_dispatch_request()
         self.assertTrue(res.status_code == 200, res.data)
         data = json.loads(res.data)
         self.assertEqual(data.get("result").get("value"), True)
    def test_06_do_request_success_remote_user(self):
        # verify SSL
        set_privacyidea_config("remote.verify_ssl_certificate", True)
        responses.add(responses.POST,
                      "http://my.privacyidea.server/mypi/validate/check",
                      body=json.dumps(self.success_body),
                      content_type="application/json")

        db_token = Token.query.filter(Token.serial == self.serial2).first()
        token = RemoteTokenClass(db_token)
        otpcount = token.check_otp("123456")
        self.assertTrue(otpcount > 0, otpcount)
示例#15
0
 def test_10_authenticate_system_radius_settings(self):
     set_privacyidea_config("radius.server", "my.other.radiusserver:1812")
     set_privacyidea_config("radius.secret", "testing123")
     radiusmock.setdata(success=True)
     token = init_token({"type": "radius",
                         "radius.system_settings": True,
                         "radius.user": "******",
                         "radius.server": "",
                         "radius.secret": ""})
     r = token.authenticate("radiuspassword")
     self.assertEqual(r[0], True)
     self.assertEqual(r[1], 0)
     self.assertEqual(r[2].get("message"), "matching 1 tokens")
 def test_04_dumb_question(self):
     set_privacyidea_config("question.num_answers", 1)
     token = init_token({
         "type": "question",
         "pin": self.pin,
         "serial": "2ndtoken",
         "user": "******",
         "realm": self.realm1,
         "questions": self.j_dumb_questions
     })
     _r, question, _transaction, _none = token.create_challenge()
     self.assertEqual("dumb questiontype", question)
     token.delete_token()
示例#17
0
    def test_01_create_recovery(self):
        smtpmock.setdata(response={"*****@*****.**": (200, "OK")})

        # missing configuration
        self.assertRaises(privacyIDEAError, create_recoverycode,
                          user=User("cornelius", self.realm1))

        # recover password with "recovery.identifier"
        r = add_smtpserver(identifier="myserver", server="1.2.3.4")
        self.assertTrue(r > 0)
        set_privacyidea_config("recovery.identifier", "myserver")
        r = create_recoverycode(User("cornelius", self.realm1))
        self.assertEqual(r, True)
 def test_10_authenticate_system_radius_settings(self):
     set_privacyidea_config("radius.server", "my.other.radiusserver:1812")
     set_privacyidea_config("radius.secret", "testing123")
     radiusmock.setdata(success=True)
     token = init_token({"type": "radius",
                         "radius.system_settings": True,
                         "radius.user": "******",
                         "radius.server": "",
                         "radius.secret": ""})
     r = token.authenticate("radiuspassword")
     self.assertEqual(r[0], True)
     self.assertEqual(r[1], 0)
     self.assertEqual(r[2].get("message"), "matching 1 tokens")
 def test_11_RADIUS_request(self):
     set_privacyidea_config("radius.dictfile", DICT_FILE)
     radiusmock.setdata(success=True)
     r = add_radius(identifier="myserver", server="1.2.3.4",
                    secret="testing123", dictionary=DICT_FILE)
     self.assertTrue(r > 0)
     token = init_token({"type": "radius",
                         "radius.identifier": "myserver",
                         "radius.user": "******"})
     r = token.authenticate("radiuspassword")
     self.assertEqual(r[0], True)
     self.assertEqual(r[1], 0)
     self.assertEqual(r[2].get("message"), "matching 1 tokens")
示例#20
0
 def test_02_reset_password(self):
     smtpmock.setdata(response={"*****@*****.**": (200, "OK")})
     set_privacyidea_config("recovery.identifier", "myserver")
     with self.app.test_request_context('/recover',
                                        method='POST',
                                        data={"user": "******",
                                              "realm": "register",
                                              "email":
                                                  "*****@*****.**"}):
         res = self.app.full_dispatch_request()
         self.assertTrue(res.status_code == 200, res.data)
         data = json.loads(res.data)
         self.assertEqual(data.get("result").get("value"), True)
示例#21
0
 def test_11_RADIUS_request(self):
     set_privacyidea_config("radius.dictfile", DICT_FILE)
     radiusmock.setdata(success=True)
     r = add_radius(identifier="myserver", server="1.2.3.4",
                    secret="testing123", dictionary=DICT_FILE)
     self.assertTrue(r > 0)
     token = init_token({"type": "radius",
                         "radius.identifier": "myserver",
                         "radius.user": "******"})
     r = token.authenticate("radiuspassword")
     self.assertEqual(r[0], True)
     self.assertEqual(r[1], 0)
     self.assertEqual(r[2].get("message"), "matching 1 tokens")
    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)
示例#23
0
    def test_06_u2f_enrollment_fails_wrong_issuer(self):
        # test data taken from
        # https://fidoalliance.org/specs/fido-u2f-v1.0-ps-20141009/fido-u2f-raw-message-formats-ps-20141009.html#examples
        serial = "U2F0010BF6F"
        set_privacyidea_config("u2f.appId", "https://puck.az.intern")
        # Registration data
        client_data = "eyJ0eXAiOiJuYXZpZ2F0b3IuaWQuZmluaXNoRW5yb2xsbWVudCIsImNoYWxsZW5nZSI6ImpIakIxaEM2VjA3dDl4ZnNNaDRfOEQ3U1JuSHRFY1BqUTdsaVl3cWxkX009Iiwib3JpZ2luIjoiaHR0cHM6Ly9wdWNrLmF6LmludGVybiIsImNpZF9wdWJrZXkiOiJ1bnVzZWQifQ"
        reg_data = "BQRHjwxEYFCkLHz3xdrmifKOHl2h17BmRJQ_S1Y9PRAhS2R186T391YE-ryqWis9HSmdp0XpRqUaKk9L8lxJTPpTQF_xFJ_LAsKkPTzKIwUlPIjGZDsLmv0en2Iya17Yz8X8OS89fuxwZOvEok-NQOKUTJP3att_RVe3dEAbq_iOtyAwggJEMIIBLqADAgECAgRVYr6gMAsGCSqGSIb3DQEBCzAuMSwwKgYDVQQDEyNZdWJpY28gVTJGIFJvb3QgQ0EgU2VyaWFsIDQ1NzIwMDYzMTAgFw0xNDA4MDEwMDAwMDBaGA8yMDUwMDkwNDAwMDAwMFowKjEoMCYGA1UEAwwfWXViaWNvIFUyRiBFRSBTZXJpYWwgMTQzMjUzNDY4ODBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABEszH3c9gUS5mVy-RYVRfhdYOqR2I2lcvoWsSCyAGfLJuUZ64EWw5m8TGy6jJDyR_aYC4xjz_F2NKnq65yvRQwmjOzA5MCIGCSsGAQQBgsQKAgQVMS4zLjYuMS40LjEuNDE0ODIuMS41MBMGCysGAQQBguUcAgEBBAQDAgUgMAsGCSqGSIb3DQEBCwOCAQEArBbZs262s6m3bXWUs09Z9Pc-28n96yk162tFHKv0HSXT5xYU10cmBMpypXjjI-23YARoXwXn0bm-BdtulED6xc_JMqbK-uhSmXcu2wJ4ICA81BQdPutvaizpnjlXgDJjq6uNbsSAp98IStLLp7fW13yUw-vAsWb5YFfK9f46Yx6iakM3YqNvvs9M9EUJYl_VrxBJqnyLx2iaZlnpr13o8NcsKIJRdMUOBqt_ageQg3ttsyq_3LyoNcu7CQ7x8NmeCGm_6eVnZMQjDmwFdymwEN4OxfnM5MkcKCYhjqgIGruWkVHsFnJa8qjZXneVvKoiepuUQyDEJ2GcqvhU2YKY1zBFAiEA4ZkIXXyjEPExcMGtW6kJXqYv7UHgjxJR5h3H9w9FV7gCIFGdhxZDqwCQKplDi-LU4WJ45OyCpNK6lGa72eZqUR_k"

        # step 1
        with self.app.test_request_context('/token/init',
                                           method='POST',
                                           data={
                                               "type": "u2f",
                                               "user": "******",
                                               "realm": self.realm1,
                                               "serial": serial
                                           },
                                           headers={'Authorization': self.at}):
            res = self.app.full_dispatch_request()
            self.assertEqual(res.status_code, 200)
            result = res.json.get("result")
            detail = res.json.get("detail")
            self.assertEqual(result.get("status"), True)
            self.assertEqual(result.get("value"), True)

        set_policy(name="u2f01",
                   scope=SCOPE.ENROLL,
                   action="{0!s}=issuer/.*Plugup.*/".format(U2FACTION.REQ))

        # Init step 2
        with self.app.test_request_context('/token/init',
                                           method='POST',
                                           data={
                                               "type": "u2f",
                                               "serial": serial,
                                               "regdata": reg_data,
                                               "clientdata": client_data
                                           },
                                           headers={'Authorization': self.at}):
            res = self.app.full_dispatch_request()
            self.assertEqual(res.status_code, 403)
            result = res.json.get("result")
            self.assertEqual(result.get("status"), False)
            self.assertEqual(
                result.get("error").get("message"),
                u'The U2F device is not allowed to be registered '
                u'due to policy restriction.')

        delete_policy("u2f01")
        remove_token(serial)
示例#24
0
 def test_10_authenticate_system_radius_settings(self):
     set_privacyidea_config("radius.server", "my.other.radiusserver:1812")
     set_privacyidea_config("radius.secret", "testing123")
     radiusmock.setdata(response=radiusmock.AccessAccept)
     token = init_token({
         "type": "radius",
         "radius.system_settings": True,
         "radius.user": "******",
         "radius.server": "",
         "radius.secret": ""
     })
     r = token.authenticate("radiuspassword")
     self.assertEqual(r[0], True)
     self.assertEqual(r[1], 1)
 def test_08_config_object(self):
     obj1 = get_config_object()
     # Another call to ``get_config_object`` returns the identical config object
     self.assertIs(obj1, get_config_object())
     set_privacyidea_config(key="k1", value="v1")
     # ``set_privacyidea_config`` invalidates the config object, so we get a different one
     obj2 = get_config_object()
     self.assertIsNot(obj1, obj2)
     self.assertEqual(get_config_object().get_config("k1"), "v1")
     # ``set_privacyidea_config`` again invalidates the config object
     set_privacyidea_config(key="k1", value="v2")
     obj3 = get_config_object()
     self.assertIsNot(obj2, obj3)
     self.assertEqual(get_config_object().get_config("k1"), "v2")
示例#26
0
    def test_18_challenge_request(self):
        responses.add(responses.POST, self.SMSHttpUrl, body=self.success_body)
        transactionid = "123456098712"
        set_privacyidea_config("sms.providerConfig", self.SMSProviderConfig)
        db_token = Token.query.filter_by(serial=self.serial1).first()
        token = SmsTokenClass(db_token)
        self.assertTrue(token.check_otp("123456", 1, 10) == -1)
        c = token.create_challenge(transactionid)
        self.assertTrue(c[0], c)
        otp = c[1]
        self.assertTrue(c[3].get("state"), transactionid)

        # check for the challenges response
        r = token.check_challenge_response(passw=otp)
        self.assertTrue(r, r)
示例#27
0
    def test_99_unset_config(self):
        # Test early exit!
        # Assert that the function `retrieve_latest_entry` is called if the cache is enabled
        with patch('privacyidea.lib.usercache.retrieve_latest_entry') as mock_retrieve:
            mock_retrieve.return_value = None
            get_username('some-userid', 'resolver1')
            self.assertEqual(mock_retrieve.call_count, 1)
        set_privacyidea_config(EXPIRATION_SECONDS, 0)

        self.assertFalse(is_cache_enabled())
        # Assert that the function `retrieve_latest_entry` is not called anymore
        with patch('privacyidea.lib.usercache.retrieve_latest_entry') as mock_retrieve:
            mock_retrieve.return_value = None
            get_username('some-userid', 'resolver1')
            self.assertEqual(mock_retrieve.call_count, 0)
示例#28
0
    def test_99_unset_config(self):
        # Test early exit!
        # Assert that the function `retrieve_latest_entry` is called if the cache is enabled
        with patch('privacyidea.lib.usercache.retrieve_latest_entry') as mock_retrieve:
            mock_retrieve.return_value = None
            get_username('some-userid', 'resolver1')
            self.assertEqual(mock_retrieve.call_count, 1)
        set_privacyidea_config(EXPIRATION_SECONDS, 0)

        self.assertFalse(is_cache_enabled())
        # Assert that the function `retrieve_latest_entry` is not called anymore
        with patch('privacyidea.lib.usercache.retrieve_latest_entry') as mock_retrieve:
            mock_retrieve.return_value = None
            get_username('some-userid', 'resolver1')
            self.assertEqual(mock_retrieve.call_count, 0)
示例#29
0
 def test_12_non_ascii(self):
     set_privacyidea_config("radius.dictfile", DICT_FILE)
     radiusmock.setdata(response=radiusmock.AccessAccept)
     r = add_radius(identifier="myserver",
                    server="1.2.3.4",
                    secret="testing123",
                    dictionary=DICT_FILE)
     self.assertTrue(r > 0)
     token = init_token({
         "type": "radius",
         "radius.identifier": "myserver",
         "radius.user": u"nönäscii"
     })
     r = token.authenticate(u"passwörd")
     self.assertEqual(r[0], True)
     self.assertEqual(r[1], 1)
示例#30
0
    def test_06_u2f_enrollment_fails_wrong_issuer(self):
        # test data taken from
        # https://fidoalliance.org/specs/fido-u2f-v1.0-ps-20141009/fido-u2f-raw-message-formats-ps-20141009.html#examples
        serial = "U2F0010BF6F"
        set_privacyidea_config("u2f.appId",
                               "https://puck.az.intern")
        # Registration data
        client_data = "eyJ0eXAiOiJuYXZpZ2F0b3IuaWQuZmluaXNoRW5yb2xsbWVudCIsImNoYWxsZW5nZSI6ImpIakIxaEM2VjA3dDl4ZnNNaDRfOEQ3U1JuSHRFY1BqUTdsaVl3cWxkX009Iiwib3JpZ2luIjoiaHR0cHM6Ly9wdWNrLmF6LmludGVybiIsImNpZF9wdWJrZXkiOiJ1bnVzZWQifQ"
        reg_data = "BQRHjwxEYFCkLHz3xdrmifKOHl2h17BmRJQ_S1Y9PRAhS2R186T391YE-ryqWis9HSmdp0XpRqUaKk9L8lxJTPpTQF_xFJ_LAsKkPTzKIwUlPIjGZDsLmv0en2Iya17Yz8X8OS89fuxwZOvEok-NQOKUTJP3att_RVe3dEAbq_iOtyAwggJEMIIBLqADAgECAgRVYr6gMAsGCSqGSIb3DQEBCzAuMSwwKgYDVQQDEyNZdWJpY28gVTJGIFJvb3QgQ0EgU2VyaWFsIDQ1NzIwMDYzMTAgFw0xNDA4MDEwMDAwMDBaGA8yMDUwMDkwNDAwMDAwMFowKjEoMCYGA1UEAwwfWXViaWNvIFUyRiBFRSBTZXJpYWwgMTQzMjUzNDY4ODBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABEszH3c9gUS5mVy-RYVRfhdYOqR2I2lcvoWsSCyAGfLJuUZ64EWw5m8TGy6jJDyR_aYC4xjz_F2NKnq65yvRQwmjOzA5MCIGCSsGAQQBgsQKAgQVMS4zLjYuMS40LjEuNDE0ODIuMS41MBMGCysGAQQBguUcAgEBBAQDAgUgMAsGCSqGSIb3DQEBCwOCAQEArBbZs262s6m3bXWUs09Z9Pc-28n96yk162tFHKv0HSXT5xYU10cmBMpypXjjI-23YARoXwXn0bm-BdtulED6xc_JMqbK-uhSmXcu2wJ4ICA81BQdPutvaizpnjlXgDJjq6uNbsSAp98IStLLp7fW13yUw-vAsWb5YFfK9f46Yx6iakM3YqNvvs9M9EUJYl_VrxBJqnyLx2iaZlnpr13o8NcsKIJRdMUOBqt_ageQg3ttsyq_3LyoNcu7CQ7x8NmeCGm_6eVnZMQjDmwFdymwEN4OxfnM5MkcKCYhjqgIGruWkVHsFnJa8qjZXneVvKoiepuUQyDEJ2GcqvhU2YKY1zBFAiEA4ZkIXXyjEPExcMGtW6kJXqYv7UHgjxJR5h3H9w9FV7gCIFGdhxZDqwCQKplDi-LU4WJ45OyCpNK6lGa72eZqUR_k"

        # step 1
        with self.app.test_request_context('/token/init',
                                           method='POST',
                                           data={"type": "u2f",
                                                 "user": "******",
                                                 "realm": self.realm1,
                                                 "serial": serial},
                                           headers={'Authorization': self.at}):
            res = self.app.full_dispatch_request()
            self.assertEqual(res.status_code, 200)
            result = json.loads(res.data.decode('utf8')).get("result")
            detail = json.loads(res.data.decode('utf8')).get("detail")
            self.assertEqual(result.get("status"), True)
            self.assertEqual(result.get("value"), True)

        set_policy(name="u2f01", scope=SCOPE.ENROLL,
                   action="{0!s}=issuer/.*Plugup.*/".format(U2FACTION.REQ))

        # Init step 2
        with self.app.test_request_context('/token/init',
                                           method='POST',
                                           data={"type": "u2f",
                                                 "serial": serial,
                                                 "regdata": reg_data,
                                                 "clientdata": client_data},
                                           headers={'Authorization': self.at}):
            res = self.app.full_dispatch_request()
            self.assertEqual(res.status_code, 403)
            result = json.loads(res.data.decode('utf8')).get("result")
            self.assertEqual(result.get("status"), False)
            self.assertEqual(result.get("error").get("message"),
                             u'The U2F device is not allowed to be registered '
                             u'due to policy restriction.')

        delete_policy("u2f01")
        remove_token(serial)
示例#31
0
    def test_18_challenge_request(self):
        responses.add(responses.POST,
                      self.SMSHttpUrl,
                      body=self.success_body)
        transactionid = "123456098712"
        set_privacyidea_config("sms.providerConfig", self.SMSProviderConfig)
        db_token = Token.query.filter_by(serial=self.serial1).first()
        token = SmsTokenClass(db_token)
        self.assertTrue(token.check_otp("123456", 1, 10) == -1)
        c = token.create_challenge(transactionid)
        self.assertTrue(c[0], c)
        otp = c[1]
        self.assertTrue(c[3].get("state"), transactionid)

        # check for the challenges response
        r = token.check_challenge_response(passw=otp)
        self.assertTrue(r, r)
示例#32
0
    def test_18a_challenge_request_dynamic(self):
        # Send a challenge request for an SMS token with a dynamic phone number
        responses.add(responses.POST, self.SMSHttpUrl, body=self.success_body)
        transactionid = "123456098712"
        set_privacyidea_config("sms.providerConfig", self.SMSProviderConfig)
        db_token = Token.query.filter_by(serial=self.serial2).first()
        token = SmsTokenClass(db_token)
        self.assertTrue(token.check_otp("123456", 1, 10) == -1)
        c = token.create_challenge(transactionid)
        self.assertTrue(c[0], c)
        otp = c[1]
        self.assertTrue(c[3].get("state"), transactionid)

        # check for the challenges response
        r = token.check_challenge_response(
            passw=otp, options={"transaction_id": transactionid})
        self.assertTrue(r, r)
 def test_18b_challenge_request_dynamic_multivalue(self):
     responses.add(responses.POST,
                   self.SMSHttpUrl,
                   body=self.success_body)
     transactionid = "123456098712"
     set_privacyidea_config("sms.providerConfig", self.SMSProviderConfig)
     db_token = Token.query.filter_by(serial=self.serial2).first()
     token = SmsTokenClass(db_token)
     # if the email is a multi-value attribute, the first address should be chosen
     new_user_info = token.user.info.copy()
     new_user_info['mobile'] = ['1234', '5678']
     with mock.patch('privacyidea.lib.resolvers.PasswdIdResolver.IdResolver.getUserInfo') as mock_user_info:
         mock_user_info.return_value = new_user_info
         c = token.create_challenge(transactionid)
         self.assertTrue(c[0], c)
         self.assertIn('destination=1234', responses.calls[0].request.body)
         self.assertNotIn('destination=5678', responses.calls[0].request.body)
示例#34
0
 def test_18b_challenge_request_dynamic_multivalue(self):
     responses.add(responses.POST,
                   self.SMSHttpUrl,
                   body=self.success_body)
     transactionid = "123456098712"
     set_privacyidea_config("sms.providerConfig", self.SMSProviderConfig)
     db_token = Token.query.filter_by(serial=self.serial2).first()
     token = SmsTokenClass(db_token)
     # if the email is a multi-value attribute, the first address should be chosen
     new_user_info = token.user.info.copy()
     new_user_info['mobile'] = ['1234', '5678']
     with mock.patch('privacyidea.lib.resolvers.PasswdIdResolver.IdResolver.getUserInfo') as mock_user_info:
         mock_user_info.return_value = new_user_info
         c = token.create_challenge(transactionid)
         self.assertTrue(c[0], c)
         self.assertIn('destination=1234', responses.calls[0].request.body)
         self.assertNotIn('destination=5678', responses.calls[0].request.body)
    def test_02_send_test_email(self):
        set_privacyidea_config("radius.dictfile", DICT_FILE)
        radiusmock.setdata(success=True)

        with self.app.test_request_context('/radiusserver/test_request',
                                           method='POST',
                                           data={"identifier": "someServer",
                                                 "secret": "secret",
                                                 "port": "1812",
                                                 "server": "1.2.3.4",
                                                 "dictionary": DICT_FILE,
                                                 "username": "******",
                                                 "password": "******"},
                                           headers={'Authorization': self.at}):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 200, res)
            data = json.loads(res.data)
            self.assertEqual(data.get("result").get("value"), True)
示例#36
0
    def test_02_send_test_email(self):
        set_privacyidea_config("radius.dictfile", DICT_FILE)
        radiusmock.setdata(response=radiusmock.AccessAccept)

        with self.app.test_request_context('/radiusserver/test_request',
                                           method='POST',
                                           data={"identifier": "someServer",
                                                 "secret": "secret",
                                                 "port": "1812",
                                                 "server": "1.2.3.4",
                                                 "dictionary": DICT_FILE,
                                                 "username": "******",
                                                 "password": "******"},
                                           headers={'Authorization': self.at}):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 200, res)
            data = res.json
            self.assertEqual(data.get("result").get("value"), True)
    def test_19_smstext(self):
        # create a SMSTEXT policy:
        p = set_policy(name="smstext",
                       action="{0!s}={1!s}".format(SMSACTION.SMSTEXT, "'Your <otp>'"),
                       scope=SCOPE.AUTH)
        self.assertTrue(p > 0)

        g = FakeFlaskG()
        P = PolicyClass()
        g.audit_object = FakeAudit()
        g.policy_object = P
        options = {"g": g}

        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)

        # check for the challenges response
        # r = token.check_challenge_response(passw="287922")
        # self.assertTrue(r, r)

        # 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("287922", options=options)
        self.assertTrue(r > 0, r)
示例#38
0
    def test_40_failcounter_exceeded(self):
        from privacyidea.lib.tokenclass import (FAILCOUNTER_EXCEEDED,
                                                FAILCOUNTER_CLEAR_TIMEOUT)
        db_token = Token("failcounter", tokentype="spass")
        db_token.save()
        token_obj = TokenClass(db_token)
        for i in range(0, 11):
            token_obj.inc_failcount()
        now = datetime.datetime.now(tzlocal()).strftime(DATE_FORMAT)
        # Now the FAILCOUNTER_EXCEEDED is set
        ti = token_obj.get_tokeninfo(FAILCOUNTER_EXCEEDED)
        # We only compare the date
        self.assertEqual(ti[:10], now[:10])
        # and the timezone
        self.assertEqual(ti[-5:], now[-5:])
        # reset the failcounter
        token_obj.reset()
        ti = token_obj.get_tokeninfo(FAILCOUNTER_EXCEEDED)
        self.assertEqual(ti, None)

        # Now check with failcounter clear, with timeout 5 minutes
        set_privacyidea_config(FAILCOUNTER_CLEAR_TIMEOUT, 5)
        token_obj.set_failcount(10)
        failed_recently = (datetime.datetime.now(tzlocal()) -
                           datetime.timedelta(minutes=3)).strftime(DATE_FORMAT)
        token_obj.add_tokeninfo(FAILCOUNTER_EXCEEDED, failed_recently)

        r = token_obj.check_failcount()
        # the fail is only 3 minutes ago, so we will not reset and check will
        #  be false
        self.assertFalse(r)

        # Set the timeout to a shorter value
        set_privacyidea_config(FAILCOUNTER_CLEAR_TIMEOUT, 2)
        r = token_obj.check_failcount()
        # The fail is longer ago.
        self.assertTrue(r)

        # The tokeninfo of this token is deleted and the failcounter is 0
        self.assertEqual(token_obj.get_tokeninfo(FAILCOUNTER_EXCEEDED), None)
        self.assertEqual(token_obj.get_failcount(), 0)

        token_obj.delete_token()
示例#39
0
    def test_19_smstext(self):
        # create a SMSTEXT policy:
        p = set_policy(name="smstext",
                       action="{0!s}={1!s}".format(SMSACTION.SMSTEXT, "'Your <otp>'"),
                       scope=SCOPE.AUTH)
        self.assertTrue(p > 0)

        g = FakeFlaskG()
        P = PolicyClass()
        g.audit_object = FakeAudit()
        g.policy_object = P
        options = {"g": g}

        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)

        # check for the challenges response
        # r = token.check_challenge_response(passw="287922")
        # self.assertTrue(r, r)

        # 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("287922", options=options)
        self.assertTrue(r > 0, r)
    def test_22_new_email_config(self):
        smtpmock.setdata(response={"*****@*****.**": (200, 'OK')})
        transactionid = "123456098717"
        # send the email with the new configuration
        r = add_smtpserver(identifier="myServer", server="1.2.3.4")
        set_privacyidea_config("email.identifier", "myServer")
        db_token = Token.query.filter_by(serial=self.serial1).first()
        token = EmailTokenClass(db_token)
        self.assertTrue(token.check_otp("123456", 1, 10) == -1)
        c = token.create_challenge(transactionid)
        self.assertTrue(c[0], c)
        otp = c[1]
        self.assertTrue(c[3].get("state"), transactionid)

        # check for the challenges response
        r = token.check_challenge_response(passw=otp)
        self.assertTrue(r, r)
        delete_smtpserver("myServer")
        delete_privacyidea_config("email.identifier")
示例#41
0
    def test_40_failcounter_exceeded(self):
        from privacyidea.lib.tokenclass import (FAILCOUNTER_EXCEEDED,
                                                FAILCOUNTER_CLEAR_TIMEOUT)
        db_token = Token("failcounter", tokentype="spass")
        db_token.save()
        token_obj = TokenClass(db_token)
        for i in range(0, 11):
            token_obj.inc_failcount()
        now = datetime.datetime.now(tzlocal()).strftime(DATE_FORMAT)
        # Now the FAILCOUNTER_EXCEEDED is set
        ti = token_obj.get_tokeninfo(FAILCOUNTER_EXCEEDED)
        # We only compare the date
        self.assertEqual(ti[:10], now[:10])
        # and the timezone
        self.assertEqual(ti[-5:], now[-5:])
        # reset the failcounter
        token_obj.reset()
        ti = token_obj.get_tokeninfo(FAILCOUNTER_EXCEEDED)
        self.assertEqual(ti, None)

        # Now check with failcounter clear, with timeout 5 minutes
        set_privacyidea_config(FAILCOUNTER_CLEAR_TIMEOUT, 5)
        token_obj.set_failcount(10)
        failed_recently = (datetime.datetime.now(tzlocal()) -
                           datetime.timedelta(minutes=3)).strftime(DATE_FORMAT)
        token_obj.add_tokeninfo(FAILCOUNTER_EXCEEDED, failed_recently)

        r = token_obj.check_failcount()
        # the fail is only 3 minutes ago, so we will not reset and check will
        #  be false
        self.assertFalse(r)

        # Set the timeout to a shorter value
        set_privacyidea_config(FAILCOUNTER_CLEAR_TIMEOUT, 2)
        r = token_obj.check_failcount()
        # The fail is longer ago.
        self.assertTrue(r)

        # The tokeninfo of this token is deleted and the failcounter is 0
        self.assertEqual(token_obj.get_tokeninfo(FAILCOUNTER_EXCEEDED), None)
        self.assertEqual(token_obj.get_failcount(), 0)

        token_obj.delete_token()
    def test_22_new_email_config(self):
        smtpmock.setdata(response={"*****@*****.**": (200, 'OK')})
        transactionid = "123456098717"
        # send the email with the new configuration
        r = add_smtpserver(identifier="myServer", server="1.2.3.4")
        set_privacyidea_config("email.identifier", "myServer")
        db_token = Token.query.filter_by(serial=self.serial1).first()
        token = EmailTokenClass(db_token)
        self.assertTrue(token.check_otp("123456", 1, 10) == -1)
        c = token.create_challenge(transactionid)
        self.assertTrue(c[0], c)
        otp = c[1]
        self.assertTrue(c[3].get("state"), transactionid)

        # check for the challenges response
        r = token.check_challenge_response(passw=otp)
        self.assertTrue(r, r)
        delete_smtpserver("myServer")
        delete_privacyidea_config("email.identifier")
    def test_01_create_token(self):
        set_privacyidea_config("question.num_answers", 3)
        token = init_token({"type": "question",
                            "pin": self.pin,
                            "serial": self.serial1,
                            "user": "******",
                            "realm": self.realm1,
                            "questions": self.j_questions
                            })
        self.assertEqual(token.type, "question")

        prefix = QuestionnaireTokenClass.get_class_prefix()
        self.assertEqual(prefix, "QUST")

        info = QuestionnaireTokenClass.get_class_info()
        self.assertEqual(info.get("type"), "question")

        info = QuestionnaireTokenClass.get_class_info("type")
        self.assertEqual(info, "question")
    def test_04_store_encrypted_values(self):
        r = set_privacyidea_config("mySecretData", "soho",
                                   typ="password", desc="Very important")
        self.assertTrue(r == "insert", r)

        r = get_from_config("mySecretData")
        self.assertTrue(r == "soho", r)

        r = get_from_config()
        self.assertTrue(r.get("mySecretData") == "soho",
                        r.get("mySecretData"))
    def test_18a_challenge_request_dynamic(self):
        # Send a challenge request for an SMS token with a dynamic phone number
        responses.add(responses.POST,
                      self.SMSHttpUrl,
                      body=self.success_body)
        transactionid = "123456098712"
        set_privacyidea_config("sms.providerConfig", self.SMSProviderConfig)
        db_token = Token.query.filter_by(serial=self.serial2).first()
        token = SmsTokenClass(db_token)
        self.assertTrue(token.check_otp("123456", 1, 10) == -1)
        c = token.create_challenge(transactionid)
        self.assertTrue(c[0], c)
        otp = c[1]
        self.assertTrue(c[3].get("state"), transactionid)

        # check for the challenges response
        r = token.check_challenge_response(passw=otp,
                                           options={"transaction_id":
                                                        transactionid})
        self.assertTrue(r, r)
示例#46
0
    def test_23_specific_email_config(self):
        smtpmock.setdata(response={"*****@*****.**": (200, 'OK')})
        transactionid = "123456098723"
        # create new configuration
        r = add_smtpserver(identifier="myServer", server="1.2.3.4")
        set_privacyidea_config("email.identifier", "myServer")
        # set it to the token instead of changing the global config
        db_token = Token.query.filter_by(serial=self.serial1).first()
        token = EmailTokenClass(db_token)
        token.add_tokeninfo("email.identifier", "myServer")
        self.assertTrue(token.check_otp("123456", 1, 10) == -1)
        c = token.create_challenge(transactionid)
        self.assertTrue(c[0], c)
        otp = c[1]
        self.assertTrue(c[3]["attributes"]["state"], transactionid)

        # check for the challenges response
        r = token.check_challenge_response(passw=otp)
        self.assertTrue(r, r)
        delete_smtpserver("myServer")
示例#47
0
    def test_04_store_encrypted_values(self):
        r = set_privacyidea_config("mySecretData", "soho",
                                   typ="password", desc="Very important")
        self.assertTrue(r == "insert", r)

        r = get_from_config("mySecretData")
        self.assertTrue(r == "soho", r)

        r = get_from_config()
        self.assertTrue(r.get("mySecretData") == "soho",
                        r.get("mySecretData"))
示例#48
0
    def test_02_get_resolvers(self):
        # enable user cache
        set_privacyidea_config(EXPIRATION_SECONDS, 600)
        # create realm
        self._create_realm()
        # delete user_cache
        r = delete_user_cache()
        self.assertTrue(r >= 0)

        # The username is not in the cache. It is fetched from the resolver
        # At the same time the cache is filled.
        user = User(self.username, self.realm1)
        self.assertEqual(user.login, self.username)
        # The user ID is fetched from the resolver
        self.assertEqual(user.uid, self.uid)

        # Now, the cache should have exactly one entry
        entry = UserCache.query.one()
        self.assertEqual(entry.user_id, self.uid)
        self.assertEqual(entry.username, self.username)
        self.assertEqual(entry.resolver, self.resolvername1)
        ts = entry.timestamp

        # delete the resolver, which also purges the cache
        self._delete_realm()

        # manually re-add the entry from above
        UserCache(self.username, self.username, self.resolvername1, self.uid,
                  ts).save()

        # the username is fetched from the cache
        u_name = get_username(self.uid, self.resolvername1)
        self.assertEqual(u_name, self.username)

        # delete the cache
        r = delete_user_cache()

        # try to fetch the username. It is not in the cache and the
        # resolver does not exist anymore.
        u_name = get_username(self.uid, self.resolvername1)
        self.assertEqual(u_name, "")
示例#49
0
    def test_22_autosync(self):
        db_token = Token.query.filter_by(serial=self.serial1).first()
        token = HotpTokenClass(db_token)
        set_privacyidea_config("AutoResync", True)
        token.update({"otpkey": self.otpkey,
                      "otplen": 6})
        token.token.count = 0
        token.set_sync_window(10)
        token.set_count_window(5)
        # counter = 8, is out of sync
        r = token.check_otp(anOtpVal="399871")
        self.assertTrue(r == -1, r)
        # counter = 9, will be autosynced.
        r = token.check_otp(anOtpVal="520489")
        self.assertTrue(r == 9, r)
        # counter = 10, has also to authenticate! The counter of the token is
        #  set.
        r = token.check_otp(anOtpVal="403154")
        self.assertTrue(r == 10, r)
        self.assertEqual(token.token.count, 11)

        # Autosync with a gap in the next otp value will fail
        token.token.count = 0
        # Just try some bullshit config value
        set_privacyidea_config("AutoResyncTimeout", "totally not a number")
        # counter = 7, is out of sync
        r = token.check_otp(anOtpVal="162583")
        self.assertTrue(r == -1, r)
        # counter = 9, will NOT _autosync
        r = token.check_otp(anOtpVal="520489")
        self.assertTrue(r == -1, r)

        # Autosync fails, if dueDate is over
        token.token.count = 0
        set_privacyidea_config("AutoResyncTimeout", 0)
        # counter = 8, is out of sync
        r = token.check_otp(anOtpVal="399871")
        self.assertTrue(r == -1, r)
        # counter = 9, is the next value, but duedate is over.
        r = token.check_otp(anOtpVal="520489")
        self.assertTrue(r == -1, r)

        # No _autosync
        set_privacyidea_config("AutoResync", False)
        token.token.count = 0
        # counter = 8, is out of sync
        r = token.check_otp(anOtpVal="399871")
        self.assertTrue(r == -1, r)
        # counter = 9, will not be autosynced
        r = token.check_otp(anOtpVal="520489")
        self.assertTrue(r == -1, r)
示例#50
0
    def test_10_saml_check(self):
        # test successful authentication
        set_privacyidea_config("ReturnSamlAttributes", "0")
        with self.app.test_request_context('/validate/samlcheck',
                                           method='POST',
                                           data={
                                               "user": "******",
                                               "pass": "******"
                                           }):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 200, res)
            result = json.loads(res.data).get("result")
            detail = json.loads(res.data).get("detail")
            value = result.get("value")
            attributes = value.get("attributes")
            self.assertEqual(value.get("auth"), True)
            # No SAML return attributes
            self.assertEqual(attributes.get("email"), None)

        set_privacyidea_config("ReturnSamlAttributes", "1")

        with self.app.test_request_context('/validate/samlcheck',
                                           method='POST',
                                           data={
                                               "user": "******",
                                               "pass": "******"
                                           }):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 200, res)
            result = json.loads(res.data).get("result")
            detail = json.loads(res.data).get("detail")
            value = result.get("value")
            attributes = value.get("attributes")
            self.assertEqual(value.get("auth"), True)
            self.assertEqual(attributes.get("email"),
                             "*****@*****.**")
            self.assertEqual(attributes.get("givenname"), "Cornelius")
            self.assertEqual(attributes.get("mobile"), "+491111111")
            self.assertEqual(attributes.get("phone"), "+491234566")
            self.assertEqual(attributes.get("realm"), "realm1")
            self.assertEqual(attributes.get("username"), "cornelius")
    def test_22_autosync(self):
        db_token = Token.query.filter_by(serial=self.serial1).first()
        token = HotpTokenClass(db_token)
        set_privacyidea_config("AutoResync", True)
        token.update({"otpkey": self.otpkey,
                      "otplen": 6})
        token.token.count = 0
        token.set_sync_window(10)
        token.set_count_window(5)
        # counter = 8, is out of sync
        r = token.check_otp(anOtpVal="399871")
        self.assertTrue(r == -1, r)
        # counter = 9, will be autosynced.
        r = token.check_otp(anOtpVal="520489")
        self.assertTrue(r == 9, r)
        # counter = 10, has also to authenticate! The counter of the token is
        #  set.
        r = token.check_otp(anOtpVal="403154")
        self.assertTrue(r == 10, r)
        self.assertEqual(token.token.count, 11)

        # Autosync with a gap in the next otp value will fail
        token.token.count = 0
        # Just try some bullshit config value
        set_privacyidea_config("AutoResyncTimeout", "totally not a number")
        # counter = 7, is out of sync
        r = token.check_otp(anOtpVal="162583")
        self.assertTrue(r == -1, r)
        # counter = 9, will NOT _autosync
        r = token.check_otp(anOtpVal="520489")
        self.assertTrue(r == -1, r)

        # Autosync fails, if dueDate is over
        token.token.count = 0
        set_privacyidea_config("AutoResyncTimeout", 0)
        # counter = 8, is out of sync
        r = token.check_otp(anOtpVal="399871")
        self.assertTrue(r == -1, r)
        # counter = 9, is the next value, but duedate is over.
        r = token.check_otp(anOtpVal="520489")
        self.assertTrue(r == -1, r)

        # No _autosync
        set_privacyidea_config("AutoResync", False)
        token.token.count = 0
        # counter = 8, is out of sync
        r = token.check_otp(anOtpVal="399871")
        self.assertTrue(r == -1, r)
        # counter = 9, will not be autosynced
        r = token.check_otp(anOtpVal="520489")
        self.assertTrue(r == -1, r)
示例#52
0
    def test_02_u2f(self):
        set_privacyidea_config("u2f.appId", "https://puck.az.intern")
        with self.app.test_request_context('/ttype/u2f',
                                           method='GET'):
            res = self.app.full_dispatch_request()
            self.assertEqual(res.status_code, 200)
            self.assertEqual(res.mimetype, u'application/fido.trusted-apps+json')
            data = json.loads(res.data.decode('utf8'))
            self.assertTrue("trustedFacets" in data)

        # Check the audit log.
        with self.app.test_request_context('/audit/?action=*GET /ttype/*',
                                           method='GET',
                                           headers={'Authorization': self.at}):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 200, res)
            json_response = json.loads(res.data.decode('utf8'))
            result = json_response.get("result")
            auditdata = result.get("value").get("auditdata")
            self.assertTrue(len(auditdata) > 0)
            self.assertEqual(auditdata[0].get("token_type"), "u2f")
示例#53
0
    def test_02_u2f(self):
        set_privacyidea_config("u2f.appId", "https://puck.az.intern")
        with self.app.test_request_context('/ttype/u2f',
                                           method='GET'):
            res = self.app.full_dispatch_request()
            self.assertEqual(res.status_code, 200)
            self.assertEqual(res.mimetype, u'application/fido.trusted-apps+json')
            data = json.loads(res.data.decode('utf8'))
            self.assertTrue("trustedFacets" in data)

        # Check the audit log.
        with self.app.test_request_context('/audit/?action=*GET /ttype/*',
                                           method='GET',
                                           headers={'Authorization': self.at}):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 200, res)
            json_response = json.loads(res.data.decode('utf8'))
            result = json_response.get("result")
            auditdata = result.get("value").get("auditdata")
            self.assertTrue(len(auditdata) > 0)
            self.assertEqual(auditdata[0].get("token_type"), "u2f")
    def test_06_public_and_admin(self):
        # This tests the new public available config
        set_privacyidea_config("publicInfo1", "info1", typ="public")
        set_privacyidea_config("publicInfo2", "info2", typ="public")
        set_privacyidea_config("secretInfo1", "info1")

        # Get administrators info
        a = get_from_config()
        self.assertTrue("secretInfo1" in a)
        self.assertTrue("publicInfo1" in a)
        a = get_from_config("publicInfo1")
        self.assertEqual(a, "info1")
        a = get_from_config("secretInfo1")
        self.assertEqual(a, "info1")

        # Get public info as user
        a = get_from_config()
        self.assertTrue("publicInfo1" in a)
        a = get_from_config("publicInfo1")
        self.assertEqual(a, "info1")

        # Not able to get private info as user
        a = get_from_config(role="public")
        self.assertTrue("secretInfo1" not in a)
        a = get_from_config("secretInfo1", role="public")
        self.assertEqual(a, None)
示例#55
0
    def test_06_public_and_admin(self):
        # This tests the new public available config
        set_privacyidea_config("publicInfo1", "info1", typ="public")
        set_privacyidea_config("publicInfo2", "info2", typ="public")
        set_privacyidea_config("secretInfo1", "info1")

        # Get administrators info
        a = get_from_config()
        self.assertTrue("secretInfo1" in a)
        self.assertTrue("publicInfo1" in a)
        a = get_from_config("publicInfo1")
        self.assertEqual(a, "info1")
        a = get_from_config("secretInfo1")
        self.assertEqual(a, "info1")

        # Get public info as user
        a = get_from_config()
        self.assertTrue("publicInfo1" in a)
        a = get_from_config("publicInfo1")
        self.assertEqual(a, "info1")

        # Not able to get private info as user
        a = get_from_config(role="public")
        self.assertTrue("secretInfo1" not in a)
        a = get_from_config("secretInfo1", role="public")
        self.assertEqual(a, None)
示例#56
0
    def test_03_admin_auth(self):
        set_privacyidea_config(SYSCONF.SPLITATSIGN, True)
        # check that the default admin works
        with self.app.test_request_context('/auth',
                                           method='POST',
                                           data={"username": "******",
                                                 "password": "******"}):
            res = self.app.full_dispatch_request()
            self.assertEqual(200, res.status_code, res)
            result = res.json.get("result")
            self.assertTrue(result.get("status"), result)
            self.assertIn('token', result.get("value"), result)
            # role should be 'admin'
            self.assertEqual('admin', result['value']['role'], result)

        # add an admin with an '@' in the login name
        create_db_admin(self.app, 'super@intern', password='******')
        # as long as the part after the '@' does not resemble an existing realm,
        # this should work with 'spltAtSign' set to True
        with self.app.test_request_context('/auth',
                                           method='POST',
                                           data={"username": "******",
                                                 "password": "******"}):
            res = self.app.full_dispatch_request()
            self.assertEqual(200, res.status_code, res)
            result = res.json.get("result")
            self.assertTrue(result.get("status"), result)
            self.assertIn('token', result.get("value"), result)
            # role should be 'admin'
            self.assertEqual('admin', result['value']['role'], result)

        # both admin logins should also work with 'splitAtSign' set to False
        set_privacyidea_config(SYSCONF.SPLITATSIGN, False)
        with self.app.test_request_context('/auth',
                                           method='POST',
                                           data={"username": "******",
                                                 "password": "******"}):
            res = self.app.full_dispatch_request()
            self.assertEqual(200, res.status_code, res)
            result = res.json.get("result")
            self.assertTrue(result.get("status"), result)
            self.assertIn('token', result.get("value"), result)
            # role should be 'admin'
            self.assertEqual('admin', result['value']['role'], result)

        with self.app.test_request_context('/auth',
                                           method='POST',
                                           data={"username": "******",
                                                 "password": "******"}):
            res = self.app.full_dispatch_request()
            self.assertEqual(200, res.status_code, res)
            result = res.json.get("result")
            self.assertTrue(result.get("status"), result)
            self.assertIn('token', result.get("value"), result)
            # role should be 'admin'
            self.assertEqual('admin', result['value']['role'], result)

        # reset 'splitAtSign' to default value
        set_privacyidea_config(SYSCONF.SPLITATSIGN, True)
示例#57
0
    def test_16_autoresync_hotp(self):
        serial = "autosync1"
        token = init_token(
            {
                "serial": serial,
                "otpkey": self.otpkey,
                "pin": "async"
            }, User("cornelius", self.realm2))
        set_privacyidea_config("AutoResync", True)
        token.set_sync_window(10)
        token.set_count_window(5)
        # counter = 8, is out of sync
        with self.app.test_request_context('/validate/check',
                                           method='POST',
                                           data={
                                               "user":
                                               "******" + self.realm2,
                                               "pass": "******"
                                           }):
            res = self.app.full_dispatch_request()
            self.assertEqual(res.status_code, 200)
            result = json.loads(res.data).get("result")
            self.assertEqual(result.get("value"), False)

        # counter = 9, will be autosynced.
        # Authentication is successful
        with self.app.test_request_context('/validate/check',
                                           method='POST',
                                           data={
                                               "user":
                                               "******" + self.realm2,
                                               "pass": "******"
                                           }):
            res = self.app.full_dispatch_request()
            self.assertEqual(res.status_code, 200)
            result = json.loads(res.data).get("result")
            self.assertEqual(result.get("value"), True)

        delete_privacyidea_config("AutoResync")
    def test_05_unicode_question(self):
        questions = {u'cité': u'Nîmes', u'城市': u'北京', 'ciudad': u'Almería'}
        set_privacyidea_config("question.num_answers", 2)
        token = init_token({
            "type": "question",
            "pin": self.pin,
            "user": "******",
            "realm": self.realm1,
            "questions": json.dumps(questions)
        })
        self.assertEqual(token.type, "question")
        r = token.create_challenge()
        self.assertEqual(r[0], True)
        question = r[1]
        transactionid = r[2]
        self.assertTrue(question in questions)

        # Now that we have the question, we can give the answer
        r = token.check_challenge_response(
            passw=questions[question],
            options={"transaction_id": transactionid})
        self.assertEqual(r, 1)
        token.delete_token()