Ejemplo n.º 1
0
    def setUp(self):
        kwargs = {
            "chall": acme_util.HTTP01,
            "uri": "uri",
            "status": messages.STATUS_INVALID,
            "error": messages.Error(typ="tls", detail="detail"),
        }

        self.http01 = achallenges.KeyAuthorizationAnnotatedChallenge(
            # pylint: disable=star-args
            challb=messages.ChallengeBody(**kwargs),
            domain="example.com",
            account_key="key")

        kwargs["chall"] = acme_util.DVSNI
        self.dvsni_same = achallenges.DVSNI(
            # pylint: disable=star-args
            challb=messages.ChallengeBody(**kwargs),
            domain="example.com",
            account_key="key")

        kwargs["error"] = messages.Error(typ="dnssec", detail="detail")
        self.dvsni_diff = achallenges.DVSNI(
            # pylint: disable=star-args
            challb=messages.ChallengeBody(**kwargs),
            domain="foo.bar",
            account_key="key")
Ejemplo n.º 2
0
    def setUp(self):
        from letsencrypt import achallenges

        kwargs = {
            "chall" : acme_util.SIMPLE_HTTP,
            "uri": "uri",
            "status": messages.STATUS_INVALID,
            "error": messages.Error(typ="tls", detail="detail"),
        }

        self.simple_http = achallenges.SimpleHTTP(
            challb=messages.ChallengeBody(**kwargs),# pylint: disable=star-args
            domain="example.com",
            account_key="key")

        kwargs["chall"] = acme_util.DVSNI
        self.dvsni_same = achallenges.DVSNI(
            challb=messages.ChallengeBody(**kwargs),# pylint: disable=star-args
            domain="example.com",
            account_key="key")

        kwargs["error"] = messages.Error(typ="dnssec", detail="detail")
        self.dvsni_diff = achallenges.DVSNI(
            challb=messages.ChallengeBody(**kwargs),# pylint: disable=star-args
            domain="foo.bar",
            account_key="key")
    def test_perform(self, mock_restart, mock_dvsni_perform):
        # Only tests functionality specific to configurator.perform
        # Note: As more challenges are offered this will have to be expanded
        auth_key = le_util.Key(self.rsa256_file, self.rsa256_pem)
        achall1 = achallenges.DVSNI(challb=messages.ChallengeBody(
            chall=challenges.DVSNI(r="foo", nonce="bar"),
            uri="https://ca.org/chall0_uri",
            status=messages.Status("pending"),
        ),
                                    domain="localhost",
                                    key=auth_key)
        achall2 = achallenges.DVSNI(challb=messages.ChallengeBody(
            chall=challenges.DVSNI(r="abc", nonce="def"),
            uri="https://ca.org/chall1_uri",
            status=messages.Status("pending"),
        ),
                                    domain="example.com",
                                    key=auth_key)

        dvsni_ret_val = [
            challenges.DVSNIResponse(s="irrelevant"),
            challenges.DVSNIResponse(s="arbitrary"),
        ]

        mock_dvsni_perform.return_value = dvsni_ret_val
        responses = self.config.perform([achall1, achall2])

        self.assertEqual(mock_dvsni_perform.call_count, 1)
        self.assertEqual(responses, dvsni_ret_val)
        self.assertEqual(mock_restart.call_count, 1)
Ejemplo n.º 4
0
    def test_perform(self, mock_restart, mock_dvsni_perform):
        # Only tests functionality specific to configurator.perform
        # Note: As more challenges are offered this will have to be expanded
        achall1 = achallenges.DVSNI(
            challb=messages.ChallengeBody(
                chall=challenges.DVSNI(token="kNdwjwOeX0I_A8DXt9Msmg"),
                uri="https://ca.org/chall0_uri",
                status=messages.Status("pending"),
            ), domain="localhost", account_key=self.rsa512jwk)
        achall2 = achallenges.DVSNI(
            challb=messages.ChallengeBody(
                chall=challenges.DVSNI(token="m8TdO1qik4JVFtgPPurJmg"),
                uri="https://ca.org/chall1_uri",
                status=messages.Status("pending"),
            ), domain="example.com", account_key=self.rsa512jwk)

        dvsni_ret_val = [
            achall1.gen_response(self.rsa512jwk),
            achall2.gen_response(self.rsa512jwk),
        ]

        mock_dvsni_perform.return_value = dvsni_ret_val
        responses = self.config.perform([achall1, achall2])

        self.assertEqual(mock_dvsni_perform.call_count, 1)
        self.assertEqual(responses, dvsni_ret_val)
        self.assertEqual(mock_restart.call_count, 1)
    def test_perform(self, mock_restart, mock_dvsni_perform):
        # Only tests functionality specific to configurator.perform
        # Note: As more challenges are offered this will have to be expanded
        auth_key = le_util.Key(self.rsa256_file, self.rsa256_pem)
        achall1 = achallenges.DVSNI(
            challb=acme_util.chall_to_challb(
                challenges.DVSNI(
                    r="jIq_Xy1mXGN37tb4L6Xj_es58fW571ZNyXekdZzhh7Q",
                    nonce="37bc5eb75d3e00a19b4f6355845e5a18"),
                "pending"),
            domain="encryption-example.demo", key=auth_key)
        achall2 = achallenges.DVSNI(
            challb=acme_util.chall_to_challb(
                challenges.DVSNI(
                    r="uqnaPzxtrndteOqtrXb0Asl5gOJfWAnnx6QJyvcmlDU",
                    nonce="59ed014cac95f77057b1d7a1b2c596ba"),
                "pending"),
            domain="letsencrypt.demo", key=auth_key)

        dvsni_ret_val = [
            challenges.DVSNIResponse(s="randomS1"),
            challenges.DVSNIResponse(s="randomS2"),
        ]

        mock_dvsni_perform.return_value = dvsni_ret_val
        responses = self.config.perform([achall1, achall2])

        self.assertEqual(mock_dvsni_perform.call_count, 1)
        self.assertEqual(responses, dvsni_ret_val)

        self.assertEqual(mock_restart.call_count, 1)
Ejemplo n.º 6
0
class DvsniTest(unittest.TestCase):
    """Tests for letsencrypt.plugins.common.DvsniTest."""

    auth_key = jose.JWKRSA.load(test_util.load_vector("rsa512_key.pem"))
    achalls = [
        achallenges.DVSNI(challb=acme_util.chall_to_challb(
            challenges.DVSNI(token=b'dvsni1'), "pending"),
                          domain="encryption-example.demo",
                          account_key=auth_key),
        achallenges.DVSNI(challb=acme_util.chall_to_challb(
            challenges.DVSNI(token=b'dvsni2'), "pending"),
                          domain="letsencrypt.demo",
                          account_key=auth_key),
    ]

    def setUp(self):
        from letsencrypt.plugins.common import Dvsni
        self.sni = Dvsni(configurator=mock.MagicMock())

    def test_add_chall(self):
        self.sni.add_chall(self.achalls[0], 0)
        self.assertEqual(1, len(self.sni.achalls))
        self.assertEqual([0], self.sni.indices)

    def test_setup_challenge_cert(self):
        # This is a helper function that can be used for handling
        # open context managers more elegantly. It avoids dealing with
        # __enter__ and __exit__ calls.
        # http://www.voidspace.org.uk/python/mock/helpers.html#mock.mock_open
        mock_open, mock_safe_open = mock.mock_open(), mock.mock_open()

        response = challenges.DVSNIResponse(validation=mock.Mock())
        achall = mock.MagicMock()
        key = test_util.load_pyopenssl_private_key("rsa512_key.pem")
        achall.gen_cert_and_response.return_value = (
            response, test_util.load_cert("cert.pem"), key)

        with mock.patch("letsencrypt.plugins.common.open",
                        mock_open,
                        create=True):
            with mock.patch("letsencrypt.plugins.common.le_util.safe_open",
                            mock_safe_open):
                # pylint: disable=protected-access
                self.assertEqual(
                    response,
                    self.sni._setup_challenge_cert(achall, "randomS1"))

        # pylint: disable=no-member
        mock_open.assert_called_once_with(self.sni.get_cert_path(achall), "wb")
        mock_open.return_value.write.assert_called_once_with(
            test_util.load_vector("cert.pem"))
        mock_safe_open.assert_called_once_with(self.sni.get_key_path(achall),
                                               "wb",
                                               chmod=0o400)
        mock_safe_open.return_value.write.assert_called_once_with(
            OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key))
Ejemplo n.º 7
0
class DvsniTest(unittest.TestCase):
    """Tests for letsencrypt.plugins.common.DvsniTest."""

    rsa256_file = pkg_resources.resource_filename(
        "acme.jose", "testdata/rsa256_key.pem")
    rsa256_pem = pkg_resources.resource_string(
        "acme.jose", "testdata/rsa256_key.pem")

    auth_key = le_util.Key(rsa256_file, rsa256_pem)
    achalls = [
        achallenges.DVSNI(
            challb=acme_util.chall_to_challb(
                challenges.DVSNI(
                    r="\x8c\x8a\xbf_-f\\cw\xee\xd6\xf8/\xa5\xe3\xfd\xeb9"
                      "\xf1\xf5\xb9\xefVM\xc9w\xa4u\x9c\xe1\x87\xb4",
                    nonce="7\xbc^\xb7]>\x00\xa1\x9bOcU\x84^Z\x18",
                ), "pending"),
            domain="encryption-example.demo", key=auth_key),
        achallenges.DVSNI(
            challb=acme_util.chall_to_challb(
                challenges.DVSNI(
                    r="\xba\xa9\xda?<m\xaewmx\xea\xad\xadv\xf4\x02\xc9y\x80"
                    "\xe2_X\t\xe7\xc7\xa4\t\xca\xf7&\x945",
                    nonce="Y\xed\x01L\xac\x95\xf7pW\xb1\xd7\xa1\xb2\xc5"
                          "\x96\xba",
                ), "pending"),
            domain="letsencrypt.demo", key=auth_key),
    ]

    def setUp(self):
        from letsencrypt.plugins.common import Dvsni
        self.sni = Dvsni(configurator=mock.MagicMock())

    def test_setup_challenge_cert(self):
        # This is a helper function that can be used for handling
        # open context managers more elegantly. It avoids dealing with
        # __enter__ and __exit__ calls.
        # http://www.voidspace.org.uk/python/mock/helpers.html#mock.mock_open
        m_open = mock.mock_open()

        response = challenges.DVSNIResponse(s="randomS1")
        achall = mock.MagicMock(nonce=self.achalls[0].nonce,
                                nonce_domain=self.achalls[0].nonce_domain)
        achall.gen_cert_and_response.return_value = ("pem", response)

        with mock.patch("letsencrypt.plugins.common.open", m_open, create=True):
            # pylint: disable=protected-access
            self.assertEqual(response, self.sni._setup_challenge_cert(
                achall, "randomS1"))

            self.assertTrue(m_open.called)
            self.assertEqual(
                m_open.call_args[0], (self.sni.get_cert_file(achall), "w"))
            self.assertEqual(m_open().write.call_args[0][0], "pem")
Ejemplo n.º 8
0
    def setUp(self):
        from letsencrypt.plugins.standalone.authenticator import \
            StandaloneAuthenticator
        self.authenticator = StandaloneAuthenticator(config=CONFIG, name=None)

        self.achall1 = achallenges.DVSNI(
            challb=acme_util.chall_to_challb(
                challenges.DVSNI(r="whee", nonce="foo"), "pending"),
            domain="foo.example.com", key=KEY)
        self.achall2 = achallenges.DVSNI(
            challb=acme_util.chall_to_challb(
                challenges.DVSNI(r="whee", nonce="bar"), "pending"),
            domain="bar.example.com", key=KEY)
        bad_achall = ("This", "Represents", "A Non-DVSNI", "Challenge")
        self.achalls = [self.achall1, self.achall2, bad_achall]
Ejemplo n.º 9
0
 def test_bad_cleanup(self):
     self.assertRaises(ValueError, self.authenticator.cleanup, [
         achallenges.DVSNI(challb=acme_util.chall_to_challb(
             challenges.DVSNI(r="whee", nonce="badnonce"), "pending"),
                           domain="bad.example.com",
                           key="key")
     ])
Ejemplo n.º 10
0
    def test_perform2(self):
        domain = b'localhost'
        key = jose.JWK.load(test_util.load_vector('rsa512_key.pem'))
        simple_http = achallenges.SimpleHTTP(
            challb=acme_util.SIMPLE_HTTP_P, domain=domain, account_key=key)
        dvsni = achallenges.DVSNI(
            challb=acme_util.DVSNI_P, domain=domain, account_key=key)

        self.auth.servers = mock.MagicMock()

        def _run(port, tls):  # pylint: disable=unused-argument
            return "server{0}".format(port)

        self.auth.servers.run.side_effect = _run
        responses = self.auth.perform2([simple_http, dvsni])

        self.assertTrue(isinstance(responses, list))
        self.assertEqual(2, len(responses))
        self.assertTrue(isinstance(responses[0], challenges.SimpleHTTPResponse))
        self.assertTrue(isinstance(responses[1], challenges.DVSNIResponse))

        self.assertEqual(self.auth.servers.run.mock_calls, [
            mock.call(4321, challenges.SimpleHTTP),
            mock.call(1234, challenges.DVSNI),
        ])
        self.assertEqual(self.auth.served, {
            "server1234": set([dvsni]),
            "server4321": set([simple_http]),
        })
        self.assertEqual(1, len(self.auth.simple_http_resources))
        self.assertEqual(2, len(self.auth.certs))
        self.assertEqual(list(self.auth.simple_http_resources), [
            acme_standalone.SimpleHTTPRequestHandler.SimpleHTTPResource(
                acme_util.SIMPLE_HTTP, responses[0], mock.ANY)])
Ejemplo n.º 11
0
def challb_to_achall(challb, key, domain):
    """Converts a ChallengeBody object to an AnnotatedChallenge.

    :param challb: ChallengeBody
    :type challb: :class:`acme.messages.ChallengeBody`

    :param key: Key
    :type key: :class:`letsencrypt.le_util.Key`

    :param str domain: Domain of the challb

    :returns: Appropriate AnnotatedChallenge
    :rtype: :class:`letsencrypt.achallenges.AnnotatedChallenge`

    """
    chall = challb.chall
    logger.info("%s challenge for %s", chall.typ, domain)

    if isinstance(chall, challenges.DVSNI):
        return achallenges.DVSNI(challb=challb, domain=domain, key=key)
    elif isinstance(chall, challenges.SimpleHTTP):
        return achallenges.SimpleHTTP(challb=challb, domain=domain, key=key)
    elif isinstance(chall, challenges.DNS):
        return achallenges.DNS(challb=challb, domain=domain)
    elif isinstance(chall, challenges.RecoveryToken):
        return achallenges.RecoveryToken(challb=challb, domain=domain)
    elif isinstance(chall, challenges.RecoveryContact):
        return achallenges.RecoveryContact(challb=challb, domain=domain)
    elif isinstance(chall, challenges.ProofOfPossession):
        return achallenges.ProofOfPossession(challb=challb, domain=domain)

    else:
        raise errors.Error("Received unsupported challenge of type: %s",
                           chall.typ)
Ejemplo n.º 12
0
 def test_bad_cleanup(self):
     self.assertRaises(ValueError, self.authenticator.cleanup, [
         achallenges.DVSNI(challb=acme_util.chall_to_challb(
             challenges.DVSNI(token=b"badtoken"), "pending"),
                           domain="bad.example.com",
                           account_key="key")
     ])
Ejemplo n.º 13
0
def challb_to_achall(challb, account_key, domain):
    """Converts a ChallengeBody object to an AnnotatedChallenge.

    :param .ChallengeBody challb: ChallengeBody
    :param .JWK account_key: Authorized Account Key
    :param str domain: Domain of the challb

    :returns: Appropriate AnnotatedChallenge
    :rtype: :class:`letsencrypt.achallenges.AnnotatedChallenge`

    """
    chall = challb.chall
    logger.info("%s challenge for %s", chall.typ, domain)

    if isinstance(chall, challenges.DVSNI):
        return achallenges.DVSNI(challb=challb,
                                 domain=domain,
                                 account_key=account_key)
    elif isinstance(chall, challenges.SimpleHTTP):
        return achallenges.SimpleHTTP(challb=challb,
                                      domain=domain,
                                      account_key=account_key)
    elif isinstance(chall, challenges.DNS):
        return achallenges.DNS(challb=challb, domain=domain)
    elif isinstance(chall, challenges.RecoveryContact):
        return achallenges.RecoveryContact(challb=challb, domain=domain)
    elif isinstance(chall, challenges.ProofOfPossession):
        return achallenges.ProofOfPossession(challb=challb, domain=domain)

    else:
        raise errors.Error("Received unsupported challenge of type: %s",
                           chall.typ)
Ejemplo n.º 14
0
    def test_unexpected(self):
        token = achallenges.RecoveryToken(challb=None, domain="0")
        unexpected = achallenges.DVSNI(challb=None,
                                       domain="0",
                                       key="dummy_key")

        self.assertRaises(errors.LetsEncryptContAuthError, self.auth.cleanup,
                          [token, unexpected])
Ejemplo n.º 15
0
    def get_achalls(self):
        """Return testing achallenges."""
        account_key = self.rsa512jwk
        achall1 = achallenges.DVSNI(challb=acme_util.chall_to_challb(
            challenges.DVSNI(
                token="jIq_Xy1mXGN37tb4L6Xj_es58fW571ZNyXekdZzhh7Q"),
            "pending"),
                                    domain="encryption-example.demo",
                                    account_key=account_key)
        achall2 = achallenges.DVSNI(challb=acme_util.chall_to_challb(
            challenges.DVSNI(
                token="uqnaPzxtrndteOqtrXb0Asl5gOJfWAnnx6QJyvcmlDU"),
            "pending"),
                                    domain="letsencrypt.demo",
                                    account_key=account_key)

        return account_key, achall1, achall2
Ejemplo n.º 16
0
 def setUp(self):
     from letsencrypt.plugins.standalone.authenticator import \
         StandaloneAuthenticator
     self.authenticator = StandaloneAuthenticator(config=CONFIG, name=None)
     self.achall = achallenges.DVSNI(
         challb=acme_util.chall_to_challb(
             challenges.DVSNI(r="whee", nonce="foononce"), "pending"),
         domain="foo.example.com", key="key")
     self.authenticator.tasks = {self.achall.nonce_domain: "stuff"}
     self.authenticator.child_pid = 12345
Ejemplo n.º 17
0
 def setUp(self):
     from letsencrypt.plugins.standalone.authenticator import \
         StandaloneAuthenticator
     self.authenticator = StandaloneAuthenticator(config=CONFIG, name=None)
     self.cert = achallenges.DVSNI(
         challb=acme_util.DVSNI_P,
         domain="example.com", key=KEY).gen_cert_and_response()[0]
     self.authenticator.private_key = PRIVATE_KEY
     self.authenticator.tasks = {"abcdef.acme.invalid": self.cert}
     self.authenticator.child_pid = 12345
Ejemplo n.º 18
0
 def setUp(self):
     from letsencrypt.plugins.standalone.authenticator import \
         StandaloneAuthenticator
     self.authenticator = StandaloneAuthenticator(config=CONFIG, name=None)
     self.cert = achallenges.DVSNI(
         challb=acme_util.DVSNI_P,
         domain="example.com",
         account_key=ACCOUNT_KEY
     ).gen_cert_and_response(key_pem=CHALL_KEY_PEM)[1]
     self.authenticator.private_key = CHALL_KEY
     self.authenticator.sni_names = {"abcdef.acme.invalid": self.cert}
     self.authenticator.child_pid = 12345
Ejemplo n.º 19
0
    def setUp(self):
        super(DvsniPerformTest, self).setUp()

        with mock.patch("letsencrypt_apache.configurator."
                        "mod_loaded") as mock_load:
            mock_load.return_value = True
            config = util.get_apache_configurator(
                self.config_path, self.config_dir, self.work_dir,
                self.ssl_options)

        from letsencrypt_apache import dvsni
        self.sni = dvsni.ApacheDvsni(config)

        rsa256_file = pkg_resources.resource_filename(
            "acme.jose", "testdata/rsa256_key.pem")
        rsa256_pem = pkg_resources.resource_string(
            "acme.jose", "testdata/rsa256_key.pem")

        auth_key = le_util.Key(rsa256_file, rsa256_pem)
        self.achalls = [
            achallenges.DVSNI(
                challb=acme_util.chall_to_challb(
                    challenges.DVSNI(
                        r="\x8c\x8a\xbf_-f\\cw\xee\xd6\xf8/\xa5\xe3\xfd\xeb9"
                          "\xf1\xf5\xb9\xefVM\xc9w\xa4u\x9c\xe1\x87\xb4",
                        nonce="7\xbc^\xb7]>\x00\xa1\x9bOcU\x84^Z\x18",
                    ), "pending"),
                domain="encryption-example.demo", key=auth_key),
            achallenges.DVSNI(
                challb=acme_util.chall_to_challb(
                    challenges.DVSNI(
                        r="\xba\xa9\xda?<m\xaewmx\xea\xad\xadv\xf4\x02\xc9y\x80"
                        "\xe2_X\t\xe7\xc7\xa4\t\xca\xf7&\x945",
                        nonce="Y\xed\x01L\xac\x95\xf7pW\xb1\xd7\xa1\xb2\xc5"
                              "\x96\xba",
                    ), "pending"),
                domain="letsencrypt.demo", key=auth_key),
        ]
    def setUp(self):
        super(DvsniPerformTest, self).setUp()

        config = util.get_nginx_configurator(self.config_path, self.config_dir,
                                             self.work_dir, self.ssl_options)

        rsa256_file = pkg_resources.resource_filename(
            "acme.jose", "testdata/rsa256_key.pem")
        rsa256_pem = pkg_resources.resource_string("acme.jose",
                                                   "testdata/rsa256_key.pem")

        auth_key = le_util.Key(rsa256_file, rsa256_pem)

        from letsencrypt_nginx import dvsni
        self.sni = dvsni.NginxDvsni(config)

        self.achalls = [
            achallenges.DVSNI(challb=acme_util.chall_to_challb(
                challenges.DVSNI(r="foo", nonce="bar"), "pending"),
                              domain="www.example.com",
                              key=auth_key),
            achallenges.DVSNI(challb=acme_util.chall_to_challb(
                challenges.DVSNI(
                    r="\xba\xa9\xda?<m\xaewmx\xea\xad\xadv\xf4\x02\xc9y\x80"
                    "\xe2_X\t\xe7\xc7\xa4\t\xca\xf7&\x945",
                    nonce="Y\xed\x01L\xac\x95\xf7pW\xb1\xd7"
                    "\xa1\xb2\xc5\x96\xba"), "pending"),
                              domain="blah",
                              key=auth_key),
            achallenges.DVSNI(challb=acme_util.chall_to_challb(
                challenges.DVSNI(
                    r="\x8c\x8a\xbf_-f\\cw\xee\xd6\xf8/\xa5\xe3\xfd\xeb9"
                    "\xf1\xf5\xb9\xefVM\xc9w\xa4u\x9c\xe1\x87\xb4",
                    nonce="7\xbc^\xb7]>\x00\xa1\x9bOcU\x84^Z\x18"), "pending"),
                              domain="www.example.org",
                              key=auth_key)
        ]
Ejemplo n.º 21
0
def _create_achalls(plugin):
    """Returns a list of annotated challenges to test on plugin"""
    achalls = list()
    names = plugin.get_testable_domain_names()
    for domain in names:
        prefs = plugin.get_chall_pref(domain)
        for chall_type in prefs:
            if chall_type == challenges.DVSNI:
                chall = challenges.DVSNI(
                    token=os.urandom(challenges.DVSNI.TOKEN_SIZE))
                challb = acme_util.chall_to_challb(
                    chall, messages.STATUS_PENDING)
                achall = achallenges.DVSNI(
                    challb=challb, domain=domain, account_key=util.JWK)
                achalls.append(achall)

    return achalls
Ejemplo n.º 22
0
class DvsniPerformTest(util.NginxTest):
    """Test the NginxDVSNI challenge."""

    account_key = common_test.DvsniTest.auth_key
    achalls = [
        achallenges.DVSNI(challb=acme_util.chall_to_challb(
            challenges.DVSNI(token="kNdwjwOeX0I_A8DXt9Msmg"), "pending"),
                          domain="www.example.com",
                          account_key=account_key),
        achallenges.DVSNI(challb=acme_util.chall_to_challb(
            challenges.DVSNI(
                token="\xba\xa9\xda?<m\xaewmx\xea\xad\xadv\xf4\x02\xc9y"
                "\x80\xe2_X\t\xe7\xc7\xa4\t\xca\xf7&\x945"), "pending"),
                          domain="blah",
                          account_key=account_key),
        achallenges.DVSNI(challb=acme_util.chall_to_challb(
            challenges.DVSNI(
                token="\x8c\x8a\xbf_-f\\cw\xee\xd6\xf8/\xa5\xe3\xfd"
                "\xeb9\xf1\xf5\xb9\xefVM\xc9w\xa4u\x9c\xe1\x87\xb4"),
            "pending"),
                          domain="www.example.org",
                          account_key=account_key),
    ]

    def setUp(self):
        super(DvsniPerformTest, self).setUp()

        config = util.get_nginx_configurator(self.config_path, self.config_dir,
                                             self.work_dir)

        from letsencrypt_nginx import dvsni
        self.sni = dvsni.NginxDvsni(config)

    def tearDown(self):
        shutil.rmtree(self.temp_dir)
        shutil.rmtree(self.config_dir)
        shutil.rmtree(self.work_dir)

    @mock.patch("letsencrypt_nginx.configurator"
                ".NginxConfigurator.choose_vhost")
    def test_perform(self, mock_choose):
        self.sni.add_chall(self.achalls[1])
        mock_choose.return_value = None
        result = self.sni.perform()
        self.assertTrue(result is None)

    def test_perform0(self):
        responses = self.sni.perform()
        self.assertEqual([], responses)

    @mock.patch("letsencrypt_nginx.configurator.NginxConfigurator.save")
    def test_perform1(self, mock_save):
        self.sni.add_chall(self.achalls[0])
        response = self.achalls[0].gen_response(self.account_key)
        mock_setup_cert = mock.MagicMock(return_value=response)

        # pylint: disable=protected-access
        self.sni._setup_challenge_cert = mock_setup_cert

        responses = self.sni.perform()

        mock_setup_cert.assert_called_once_with(self.achalls[0])
        self.assertEqual([response], responses)
        self.assertEqual(mock_save.call_count, 2)

        # Make sure challenge config is included in main config
        http = self.sni.configurator.parser.parsed[
            self.sni.configurator.parser.loc["root"]][-1]
        self.assertTrue(
            util.contains_at_depth(http, ['include', self.sni.challenge_conf],
                                   1))

    def test_perform2(self):
        acme_responses = []
        for achall in self.achalls:
            self.sni.add_chall(achall)
            acme_responses.append(achall.gen_response(self.account_key))

        mock_setup_cert = mock.MagicMock(side_effect=acme_responses)
        # pylint: disable=protected-access
        self.sni._setup_challenge_cert = mock_setup_cert

        sni_responses = self.sni.perform()

        self.assertEqual(mock_setup_cert.call_count, 3)

        for index, achall in enumerate(self.achalls):
            self.assertEqual(mock_setup_cert.call_args_list[index],
                             mock.call(achall))

        http = self.sni.configurator.parser.parsed[
            self.sni.configurator.parser.loc["root"]][-1]
        self.assertTrue(['include', self.sni.challenge_conf] in http[1])
        self.assertTrue(
            util.contains_at_depth(http, ['server_name', 'blah'], 3))

        self.assertEqual(len(sni_responses), 3)
        for i in xrange(3):
            self.assertEqual(sni_responses[i], acme_responses[i])

    def test_mod_config(self):
        self.sni.add_chall(self.achalls[0])
        self.sni.add_chall(self.achalls[2])

        v_addr1 = [
            obj.Addr("69.50.225.155", "9000", True, False),
            obj.Addr("127.0.0.1", "", False, False)
        ]
        v_addr2 = [obj.Addr("myhost", "", False, True)]
        ll_addr = [v_addr1, v_addr2]
        self.sni._mod_config(ll_addr)  # pylint: disable=protected-access

        self.sni.configurator.save()

        self.sni.configurator.parser.load()

        http = self.sni.configurator.parser.parsed[
            self.sni.configurator.parser.loc["root"]][-1]
        self.assertTrue(['include', self.sni.challenge_conf] in http[1])

        vhosts = self.sni.configurator.parser.get_vhosts()
        vhs = [vh for vh in vhosts if vh.filep == self.sni.challenge_conf]

        for vhost in vhs:
            if vhost.addrs == set(v_addr1):
                response = self.achalls[0].gen_response(self.account_key)
            else:
                response = self.achalls[2].gen_response(self.account_key)
                self.assertEqual(vhost.addrs, set(v_addr2))
            self.assertEqual(vhost.names, set([response.z_domain]))

        self.assertEqual(len(vhs), 2)

    def test_mod_config_fail(self):
        root = self.sni.configurator.parser.loc["root"]
        self.sni.configurator.parser.parsed[root] = [['include', 'foo.conf']]
        # pylint: disable=protected-access
        self.assertRaises(errors.MisconfigurationError, self.sni._mod_config,
                          [])
Ejemplo n.º 23
0
 def test_unexpected(self):
     unexpected = achallenges.DVSNI(challb=None,
                                    domain="0",
                                    account_key="dummy_key")
     self.assertRaises(errors.ContAuthError, self.auth.cleanup,
                       [unexpected])
 def test_unexpected(self):
     self.assertRaises(
         errors.ContAuthError, self.auth.perform, [
             achallenges.DVSNI(challb=None, domain="0", key="invalid_key")])
Ejemplo n.º 25
0
class DvsniPerformTest(util.NginxTest):
    """Test the NginxDVSNI challenge."""

    achalls = [
        achallenges.DVSNI(challb=acme_util.chall_to_challb(
            challenges.DVSNI(r="foo", nonce="bar"), "pending"),
                          domain="www.example.com",
                          key=common_test.DvsniTest.auth_key),
        achallenges.DVSNI(challb=acme_util.chall_to_challb(
            challenges.DVSNI(
                r="\xba\xa9\xda?<m\xaewmx\xea\xad\xadv\xf4\x02\xc9y\x80"
                "\xe2_X\t\xe7\xc7\xa4\t\xca\xf7&\x945",
                nonce="Y\xed\x01L\xac\x95\xf7pW\xb1\xd7"
                "\xa1\xb2\xc5\x96\xba"), "pending"),
                          domain="blah",
                          key=common_test.DvsniTest.auth_key),
        achallenges.DVSNI(challb=acme_util.chall_to_challb(
            challenges.DVSNI(
                r="\x8c\x8a\xbf_-f\\cw\xee\xd6\xf8/\xa5\xe3\xfd\xeb9"
                "\xf1\xf5\xb9\xefVM\xc9w\xa4u\x9c\xe1\x87\xb4",
                nonce="7\xbc^\xb7]>\x00\xa1\x9bOcU\x84^Z\x18"), "pending"),
                          domain="www.example.org",
                          key=common_test.DvsniTest.auth_key)
    ]

    def setUp(self):
        super(DvsniPerformTest, self).setUp()

        config = util.get_nginx_configurator(self.config_path, self.config_dir,
                                             self.work_dir)

        from letsencrypt_nginx import dvsni
        self.sni = dvsni.NginxDvsni(config)

    def tearDown(self):
        shutil.rmtree(self.temp_dir)
        shutil.rmtree(self.config_dir)
        shutil.rmtree(self.work_dir)

    def test_add_chall(self):
        self.sni.add_chall(self.achalls[0], 0)
        self.assertEqual(1, len(self.sni.achalls))
        self.assertEqual([0], self.sni.indices)

    @mock.patch("letsencrypt_nginx.configurator"
                ".NginxConfigurator.choose_vhost")
    def test_perform(self, mock_choose):
        self.sni.add_chall(self.achalls[1])
        mock_choose.return_value = None
        result = self.sni.perform()
        self.assertTrue(result is None)

    def test_perform0(self):
        responses = self.sni.perform()
        self.assertEqual([], responses)

    @mock.patch("letsencrypt_nginx.configurator.NginxConfigurator.save")
    def test_perform1(self, mock_save):
        self.sni.add_chall(self.achalls[0])
        mock_setup_cert = mock.MagicMock(return_value=challenges.DVSNIResponse(
            s="nginxS1"))

        # pylint: disable=protected-access
        self.sni._setup_challenge_cert = mock_setup_cert

        responses = self.sni.perform()

        mock_setup_cert.assert_called_once_with(self.achalls[0])
        self.assertEqual([challenges.DVSNIResponse(s="nginxS1")], responses)
        self.assertEqual(mock_save.call_count, 2)

        # Make sure challenge config is included in main config
        http = self.sni.configurator.parser.parsed[
            self.sni.configurator.parser.loc["root"]][-1]
        self.assertTrue(['include', self.sni.challenge_conf] in http[1])

    def test_perform2(self):
        for achall in self.achalls:
            self.sni.add_chall(achall)

        mock_setup_cert = mock.MagicMock(side_effect=[
            challenges.DVSNIResponse(s="nginxS0"),
            challenges.DVSNIResponse(s="nginxS1"),
            challenges.DVSNIResponse(s="nginxS2")
        ])
        # pylint: disable=protected-access
        self.sni._setup_challenge_cert = mock_setup_cert

        responses = self.sni.perform()

        self.assertEqual(mock_setup_cert.call_count, 3)

        for index, achall in enumerate(self.achalls):
            self.assertEqual(mock_setup_cert.call_args_list[index],
                             mock.call(achall))

        http = self.sni.configurator.parser.parsed[
            self.sni.configurator.parser.loc["root"]][-1]
        self.assertTrue(['include', self.sni.challenge_conf] in http[1])
        self.assertTrue(['server_name', 'blah'] in http[1][-2][1])

        self.assertEqual(len(responses), 3)
        for i in xrange(3):
            self.assertEqual(responses[i].s, "nginxS%d" % i)

    def test_mod_config(self):
        self.sni.add_chall(self.achalls[0])
        self.sni.add_chall(self.achalls[2])

        v_addr1 = [
            obj.Addr("69.50.225.155", "9000", True, False),
            obj.Addr("127.0.0.1", "", False, False)
        ]
        v_addr2 = [obj.Addr("myhost", "", False, True)]
        ll_addr = [v_addr1, v_addr2]
        self.sni._mod_config(ll_addr)  # pylint: disable=protected-access

        self.sni.configurator.save()

        self.sni.configurator.parser.load()

        http = self.sni.configurator.parser.parsed[
            self.sni.configurator.parser.loc["root"]][-1]
        self.assertTrue(['include', self.sni.challenge_conf] in http[1])

        vhosts = self.sni.configurator.parser.get_vhosts()
        vhs = [vh for vh in vhosts if vh.filep == self.sni.challenge_conf]

        for vhost in vhs:
            if vhost.addrs == set(v_addr1):
                self.assertEqual(vhost.names,
                                 set([self.achalls[0].nonce_domain]))
            else:
                self.assertEqual(vhost.addrs, set(v_addr2))
                self.assertEqual(vhost.names,
                                 set([self.achalls[2].nonce_domain]))

        self.assertEqual(len(vhs), 2)

    def test_mod_config_fail(self):
        root = self.sni.configurator.parser.loc["root"]
        self.sni.configurator.parser.parsed[root] = [['include', 'foo.conf']]
        # pylint: disable=protected-access
        self.assertRaises(errors.MisconfigurationError, self.sni._mod_config,
                          [])