We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
KeyError when using --manual-cleanup-hook with wildcard certificate
## My operating system is (include version):
Ubuntu 16.04

## I installed Certbot with (certbot-auto, OS package manager, pip, etc):
Git - commit `31805c5`

## I ran this command and it produced this output:
```bash
$ certbot --noninteractive --manual --manual-public-ip-logging-ok --preferred-challenges dns --manual-auth-hook "/srv/letsencrypt-lexicon.sh auth" --manual-cleanup-hook "/srv/letsencrypt-lexicon.sh cleanup" --server https://acme-staging-v02.api.letsencrypt.org/directory --cert-name xenial.alberon.co.uk -d xenial.alberon.co.uk,*.xenial.alberon.co.uk -m dave@davejamesmiller.com --agree-tos
...
Traceback (most recent call last):
  File "/srv/certbot/venv/bin/certbot", line 11, in <module>
    load_entry_point('certbot', 'console_scripts', 'certbot')()
  File "/srv/certbot/certbot/main.py", line 1266, in main
    return config.func(config, plugins)
  File "/srv/certbot/certbot/main.py", line 1157, in certonly
    lineage = _get_and_save_cert(le_client, config, domains, certname, lineage)
  File "/srv/certbot/certbot/main.py", line 118, in _get_and_save_cert
    lineage = le_client.obtain_and_enroll_certificate(domains, certname)
  File "/srv/certbot/certbot/client.py", line 349, in obtain_and_enroll_certificate
    cert, chain, key, _ = self.obtain_certificate(domains)
  File "/srv/certbot/certbot/client.py", line 293, in obtain_certificate
    orderr = self._get_order_and_authorizations(csr.data, self.config.allow_subset_of_names)
  File "/srv/certbot/certbot/client.py", line 329, in _get_order_and_authorizations
    authzr = self.auth_handler.handle_authorizations(orderr, best_effort)
  File "/srv/certbot/certbot/auth_handler.py", line 82, in handle_authorizations
    self._respond(resp, best_effort)
  File "/srv/certbot/certbot/auth_handler.py", line 159, in _respond
    self._cleanup_challenges(active_achalls)
  File "/srv/certbot/certbot/auth_handler.py", line 304, in _cleanup_challenges
    self.auth.cleanup(achalls)
  File "/srv/certbot/certbot/plugins/manual.py", line 218, in cleanup
    env = self.env.pop(achall.domain)
KeyError: u'xenial.alberon.co.uk'
```

## Certbot's behavior differed from what I expected because:
It crashed.

This only seems to happen when using `--manual-cleanup-hook` *and* including both `xenial.alberon.co.uk` and `*.xenial.alberon.co.uk`.

I think `self.env.pop(achall.domain)` gets called twice, both times with `achall.domain = 'xenial.alberon.co.uk'`, and the second time it's already been removed. I would guess the key needs to be changed to something else now that one domain may require two separate challenges.

## Here is a Certbot log showing the issue (if available):
https://gist.github.com/davejamesmiller/2a8c2f7a03cac9edd573c767a8fbedec

## Here is the relevant nginx server block or Apache virtualhost for the domain I am configuring:
N/A

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `certbot/plugins/manual.py`
Content:
```
1 """Manual authenticator plugin"""
2 import os
3 
4 import zope.component
5 import zope.interface
6 
7 from acme import challenges
8 
9 from certbot import interfaces
10 from certbot import errors
11 from certbot import hooks
12 from certbot import reverter
13 from certbot.plugins import common
14 
15 
16 class ManualTlsSni01(common.TLSSNI01):
17     """TLS-SNI-01 authenticator for the Manual plugin
18 
19     :ivar configurator: Authenticator object
20     :type configurator: :class:`~certbot.plugins.manual.Authenticator`
21 
22     :ivar list achalls: Annotated
23         class:`~certbot.achallenges.KeyAuthorizationAnnotatedChallenge`
24         challenges
25 
26     :param list indices: Meant to hold indices of challenges in a
27         larger array. NginxTlsSni01 is capable of solving many challenges
28         at once which causes an indexing issue within NginxConfigurator
29         who must return all responses in order.  Imagine NginxConfigurator
30         maintaining state about where all of the http-01 Challenges,
31         TLS-SNI-01 Challenges belong in the response array.  This is an
32         optional utility.
33 
34     :param str challenge_conf: location of the challenge config file
35     """
36 
37     def perform(self):
38         """Create the SSL certificates and private keys"""
39 
40         for achall in self.achalls:
41             self._setup_challenge_cert(achall)
42 
43 
44 @zope.interface.implementer(interfaces.IAuthenticator)
45 @zope.interface.provider(interfaces.IPluginFactory)
46 class Authenticator(common.Plugin):
47     """Manual authenticator
48 
49     This plugin allows the user to perform the domain validation
50     challenge(s) themselves. This either be done manually by the user or
51     through shell scripts provided to Certbot.
52 
53     """
54 
55     description = 'Manual configuration or run your own shell scripts'
56     hidden = True
57     long_description = (
58         'Authenticate through manual configuration or custom shell scripts. '
59         'When using shell scripts, an authenticator script must be provided. '
60         'The environment variables available to this script depend on the '
61         'type of challenge. $CERTBOT_DOMAIN will always contain the domain '
62         'being authenticated. For HTTP-01 and DNS-01, $CERTBOT_VALIDATION '
63         'is the validation string, and $CERTBOT_TOKEN is the filename of the '
64         'resource requested when performing an HTTP-01 challenge. When '
65         'performing a TLS-SNI-01 challenge, $CERTBOT_SNI_DOMAIN will contain '
66         'the SNI name for which the ACME server expects to be presented with '
67         'the self-signed certificate located at $CERTBOT_CERT_PATH. The '
68         'secret key needed to complete the TLS handshake is located at '
69         '$CERTBOT_KEY_PATH. An additional cleanup script can also be '
70         'provided and can use the additional variable $CERTBOT_AUTH_OUTPUT '
71         'which contains the stdout output from the auth script.')
72     _DNS_INSTRUCTIONS = """\
73 Please deploy a DNS TXT record under the name
74 {domain} with the following value:
75 
76 {validation}
77 
78 Before continuing, verify the record is deployed."""
79     _HTTP_INSTRUCTIONS = """\
80 Create a file containing just this data:
81 
82 {validation}
83 
84 And make it available on your web server at this URL:
85 
86 {uri}
87 """
88     _TLSSNI_INSTRUCTIONS = """\
89 Configure the service listening on port {port} to present the certificate
90 {cert}
91 using the secret key
92 {key}
93 when it receives a TLS ClientHello with the SNI extension set to
94 {sni_domain}
95 """
96 
97     def __init__(self, *args, **kwargs):
98         super(Authenticator, self).__init__(*args, **kwargs)
99         self.reverter = reverter.Reverter(self.config)
100         self.reverter.recovery_routine()
101         self.env = dict()
102         self.tls_sni_01 = None
103 
104     @classmethod
105     def add_parser_arguments(cls, add):
106         add('auth-hook',
107             help='Path or command to execute for the authentication script')
108         add('cleanup-hook',
109             help='Path or command to execute for the cleanup script')
110         add('public-ip-logging-ok', action='store_true',
111             help='Automatically allows public IP logging (default: Ask)')
112 
113     def prepare(self):  # pylint: disable=missing-docstring
114         if self.config.noninteractive_mode and not self.conf('auth-hook'):
115             raise errors.PluginError(
116                 'An authentication script must be provided with --{0} when '
117                 'using the manual plugin non-interactively.'.format(
118                     self.option_name('auth-hook')))
119         self._validate_hooks()
120 
121     def _validate_hooks(self):
122         if self.config.validate_hooks:
123             for name in ('auth-hook', 'cleanup-hook'):
124                 hook = self.conf(name)
125                 if hook is not None:
126                     hook_prefix = self.option_name(name)[:-len('-hook')]
127                     hooks.validate_hook(hook, hook_prefix)
128 
129     def more_info(self):  # pylint: disable=missing-docstring,no-self-use
130         return (
131             'This plugin allows the user to customize setup for domain '
132             'validation challenges either through shell scripts provided by '
133             'the user or by performing the setup manually.')
134 
135     def get_chall_pref(self, domain):
136         # pylint: disable=missing-docstring,no-self-use,unused-argument
137         return [challenges.HTTP01, challenges.DNS01, challenges.TLSSNI01]
138 
139     def perform(self, achalls):  # pylint: disable=missing-docstring
140         self._verify_ip_logging_ok()
141         if self.conf('auth-hook'):
142             perform_achall = self._perform_achall_with_script
143         else:
144             perform_achall = self._perform_achall_manually
145 
146         responses = []
147         for achall in achalls:
148             if isinstance(achall.chall, challenges.TLSSNI01):
149                 # Make a new ManualTlsSni01 instance for each challenge
150                 # because the manual plugin deals with one challenge at a time.
151                 self.tls_sni_01 = ManualTlsSni01(self)
152                 self.tls_sni_01.add_chall(achall)
153                 self.tls_sni_01.perform()
154             perform_achall(achall)
155             responses.append(achall.response(achall.account_key))
156         return responses
157 
158     def _verify_ip_logging_ok(self):
159         if not self.conf('public-ip-logging-ok'):
160             cli_flag = '--{0}'.format(self.option_name('public-ip-logging-ok'))
161             msg = ('NOTE: The IP of this machine will be publicly logged as '
162                    "having requested this certificate. If you're running "
163                    'certbot in manual mode on a machine that is not your '
164                    "server, please ensure you're okay with that.\n\n"
165                    'Are you OK with your IP being logged?')
166             display = zope.component.getUtility(interfaces.IDisplay)
167             if display.yesno(msg, cli_flag=cli_flag, force_interactive=True):
168                 setattr(self.config, self.dest('public-ip-logging-ok'), True)
169             else:
170                 raise errors.PluginError('Must agree to IP logging to proceed')
171 
172     def _perform_achall_with_script(self, achall):
173         env = dict(CERTBOT_DOMAIN=achall.domain,
174                    CERTBOT_VALIDATION=achall.validation(achall.account_key))
175         if isinstance(achall.chall, challenges.HTTP01):
176             env['CERTBOT_TOKEN'] = achall.chall.encode('token')
177         else:
178             os.environ.pop('CERTBOT_TOKEN', None)
179         if isinstance(achall.chall, challenges.TLSSNI01):
180             env['CERTBOT_CERT_PATH'] = self.tls_sni_01.get_cert_path(achall)
181             env['CERTBOT_KEY_PATH'] = self.tls_sni_01.get_key_path(achall)
182             env['CERTBOT_SNI_DOMAIN'] = self.tls_sni_01.get_z_domain(achall)
183             os.environ.pop('CERTBOT_VALIDATION', None)
184             env.pop('CERTBOT_VALIDATION')
185         else:
186             os.environ.pop('CERTBOT_CERT_PATH', None)
187             os.environ.pop('CERTBOT_KEY_PATH', None)
188             os.environ.pop('CERTBOT_SNI_DOMAIN', None)
189         os.environ.update(env)
190         _, out = hooks.execute(self.conf('auth-hook'))
191         env['CERTBOT_AUTH_OUTPUT'] = out.strip()
192         self.env[achall.domain] = env
193 
194     def _perform_achall_manually(self, achall):
195         validation = achall.validation(achall.account_key)
196         if isinstance(achall.chall, challenges.HTTP01):
197             msg = self._HTTP_INSTRUCTIONS.format(
198                 achall=achall, encoded_token=achall.chall.encode('token'),
199                 port=self.config.http01_port,
200                 uri=achall.chall.uri(achall.domain), validation=validation)
201         elif isinstance(achall.chall, challenges.DNS01):
202             msg = self._DNS_INSTRUCTIONS.format(
203                 domain=achall.validation_domain_name(achall.domain),
204                 validation=validation)
205         else:
206             assert isinstance(achall.chall, challenges.TLSSNI01)
207             msg = self._TLSSNI_INSTRUCTIONS.format(
208                 cert=self.tls_sni_01.get_cert_path(achall),
209                 key=self.tls_sni_01.get_key_path(achall),
210                 port=self.config.tls_sni_01_port,
211                 sni_domain=self.tls_sni_01.get_z_domain(achall))
212         display = zope.component.getUtility(interfaces.IDisplay)
213         display.notification(msg, wrap=False, force_interactive=True)
214 
215     def cleanup(self, achalls):  # pylint: disable=missing-docstring
216         if self.conf('cleanup-hook'):
217             for achall in achalls:
218                 env = self.env.pop(achall.domain)
219                 if 'CERTBOT_TOKEN' not in env:
220                     os.environ.pop('CERTBOT_TOKEN', None)
221                 os.environ.update(env)
222                 hooks.execute(self.conf('cleanup-hook'))
223         self.reverter.recovery_routine()
224
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/certbot/plugins/manual.py b/certbot/plugins/manual.py
--- a/certbot/plugins/manual.py
+++ b/certbot/plugins/manual.py
@@ -189,7 +189,7 @@
         os.environ.update(env)
         _, out = hooks.execute(self.conf('auth-hook'))
         env['CERTBOT_AUTH_OUTPUT'] = out.strip()
-        self.env[achall.domain] = env
+        self.env[achall] = env
 
     def _perform_achall_manually(self, achall):
         validation = achall.validation(achall.account_key)
@@ -215,7 +215,7 @@
     def cleanup(self, achalls):  # pylint: disable=missing-docstring
         if self.conf('cleanup-hook'):
             for achall in achalls:
-                env = self.env.pop(achall.domain)
+                env = self.env.pop(achall)
                 if 'CERTBOT_TOKEN' not in env:
                     os.environ.pop('CERTBOT_TOKEN', None)
                 os.environ.update(env)

{"golden_diff": "diff --git a/certbot/plugins/manual.py b/certbot/plugins/manual.py\n--- a/certbot/plugins/manual.py\n+++ b/certbot/plugins/manual.py\n@@ -189,7 +189,7 @@\n         os.environ.update(env)\n         _, out = hooks.execute(self.conf('auth-hook'))\n         env['CERTBOT_AUTH_OUTPUT'] = out.strip()\n-        self.env[achall.domain] = env\n+        self.env[achall] = env\n \n     def _perform_achall_manually(self, achall):\n         validation = achall.validation(achall.account_key)\n@@ -215,7 +215,7 @@\n     def cleanup(self, achalls):  # pylint: disable=missing-docstring\n         if self.conf('cleanup-hook'):\n             for achall in achalls:\n-                env = self.env.pop(achall.domain)\n+                env = self.env.pop(achall)\n                 if 'CERTBOT_TOKEN' not in env:\n                     os.environ.pop('CERTBOT_TOKEN', None)\n                 os.environ.update(env)\n", "issue": "KeyError when using --manual-cleanup-hook with wildcard certificate\n## My operating system is (include version):\r\nUbuntu 16.04\r\n\r\n## I installed Certbot with (certbot-auto, OS package manager, pip, etc):\r\nGit - commit `31805c5`\r\n\r\n## I ran this command and it produced this output:\r\n```bash\r\n$ certbot --noninteractive --manual --manual-public-ip-logging-ok --preferred-challenges dns --manual-auth-hook \"/srv/letsencrypt-lexicon.sh auth\" --manual-cleanup-hook \"/srv/letsencrypt-lexicon.sh cleanup\" --server https://acme-staging-v02.api.letsencrypt.org/directory --cert-name xenial.alberon.co.uk -d xenial.alberon.co.uk,*.xenial.alberon.co.uk -m dave@davejamesmiller.com --agree-tos\r\n...\r\nTraceback (most recent call last):\r\n  File \"/srv/certbot/venv/bin/certbot\", line 11, in <module>\r\n    load_entry_point('certbot', 'console_scripts', 'certbot')()\r\n  File \"/srv/certbot/certbot/main.py\", line 1266, in main\r\n    return config.func(config, plugins)\r\n  File \"/srv/certbot/certbot/main.py\", line 1157, in certonly\r\n    lineage = _get_and_save_cert(le_client, config, domains, certname, lineage)\r\n  File \"/srv/certbot/certbot/main.py\", line 118, in _get_and_save_cert\r\n    lineage = le_client.obtain_and_enroll_certificate(domains, certname)\r\n  File \"/srv/certbot/certbot/client.py\", line 349, in obtain_and_enroll_certificate\r\n    cert, chain, key, _ = self.obtain_certificate(domains)\r\n  File \"/srv/certbot/certbot/client.py\", line 293, in obtain_certificate\r\n    orderr = self._get_order_and_authorizations(csr.data, self.config.allow_subset_of_names)\r\n  File \"/srv/certbot/certbot/client.py\", line 329, in _get_order_and_authorizations\r\n    authzr = self.auth_handler.handle_authorizations(orderr, best_effort)\r\n  File \"/srv/certbot/certbot/auth_handler.py\", line 82, in handle_authorizations\r\n    self._respond(resp, best_effort)\r\n  File \"/srv/certbot/certbot/auth_handler.py\", line 159, in _respond\r\n    self._cleanup_challenges(active_achalls)\r\n  File \"/srv/certbot/certbot/auth_handler.py\", line 304, in _cleanup_challenges\r\n    self.auth.cleanup(achalls)\r\n  File \"/srv/certbot/certbot/plugins/manual.py\", line 218, in cleanup\r\n    env = self.env.pop(achall.domain)\r\nKeyError: u'xenial.alberon.co.uk'\r\n```\r\n\r\n## Certbot's behavior differed from what I expected because:\r\nIt crashed.\r\n\r\nThis only seems to happen when using `--manual-cleanup-hook` *and* including both `xenial.alberon.co.uk` and `*.xenial.alberon.co.uk`.\r\n\r\nI think `self.env.pop(achall.domain)` gets called twice, both times with `achall.domain = 'xenial.alberon.co.uk'`, and the second time it's already been removed. I would guess the key needs to be changed to something else now that one domain may require two separate challenges.\r\n\r\n## Here is a Certbot log showing the issue (if available):\r\nhttps://gist.github.com/davejamesmiller/2a8c2f7a03cac9edd573c767a8fbedec\r\n\r\n## Here is the relevant nginx server block or Apache virtualhost for the domain I am configuring:\r\nN/A\n", "before_files": [{"content": "\"\"\"Manual authenticator plugin\"\"\"\nimport os\n\nimport zope.component\nimport zope.interface\n\nfrom acme import challenges\n\nfrom certbot import interfaces\nfrom certbot import errors\nfrom certbot import hooks\nfrom certbot import reverter\nfrom certbot.plugins import common\n\n\nclass ManualTlsSni01(common.TLSSNI01):\n    \"\"\"TLS-SNI-01 authenticator for the Manual plugin\n\n    :ivar configurator: Authenticator object\n    :type configurator: :class:`~certbot.plugins.manual.Authenticator`\n\n    :ivar list achalls: Annotated\n        class:`~certbot.achallenges.KeyAuthorizationAnnotatedChallenge`\n        challenges\n\n    :param list indices: Meant to hold indices of challenges in a\n        larger array. NginxTlsSni01 is capable of solving many challenges\n        at once which causes an indexing issue within NginxConfigurator\n        who must return all responses in order.  Imagine NginxConfigurator\n        maintaining state about where all of the http-01 Challenges,\n        TLS-SNI-01 Challenges belong in the response array.  This is an\n        optional utility.\n\n    :param str challenge_conf: location of the challenge config file\n    \"\"\"\n\n    def perform(self):\n        \"\"\"Create the SSL certificates and private keys\"\"\"\n\n        for achall in self.achalls:\n            self._setup_challenge_cert(achall)\n\n\n@zope.interface.implementer(interfaces.IAuthenticator)\n@zope.interface.provider(interfaces.IPluginFactory)\nclass Authenticator(common.Plugin):\n    \"\"\"Manual authenticator\n\n    This plugin allows the user to perform the domain validation\n    challenge(s) themselves. This either be done manually by the user or\n    through shell scripts provided to Certbot.\n\n    \"\"\"\n\n    description = 'Manual configuration or run your own shell scripts'\n    hidden = True\n    long_description = (\n        'Authenticate through manual configuration or custom shell scripts. '\n        'When using shell scripts, an authenticator script must be provided. '\n        'The environment variables available to this script depend on the '\n        'type of challenge. $CERTBOT_DOMAIN will always contain the domain '\n        'being authenticated. For HTTP-01 and DNS-01, $CERTBOT_VALIDATION '\n        'is the validation string, and $CERTBOT_TOKEN is the filename of the '\n        'resource requested when performing an HTTP-01 challenge. When '\n        'performing a TLS-SNI-01 challenge, $CERTBOT_SNI_DOMAIN will contain '\n        'the SNI name for which the ACME server expects to be presented with '\n        'the self-signed certificate located at $CERTBOT_CERT_PATH. The '\n        'secret key needed to complete the TLS handshake is located at '\n        '$CERTBOT_KEY_PATH. An additional cleanup script can also be '\n        'provided and can use the additional variable $CERTBOT_AUTH_OUTPUT '\n        'which contains the stdout output from the auth script.')\n    _DNS_INSTRUCTIONS = \"\"\"\\\nPlease deploy a DNS TXT record under the name\n{domain} with the following value:\n\n{validation}\n\nBefore continuing, verify the record is deployed.\"\"\"\n    _HTTP_INSTRUCTIONS = \"\"\"\\\nCreate a file containing just this data:\n\n{validation}\n\nAnd make it available on your web server at this URL:\n\n{uri}\n\"\"\"\n    _TLSSNI_INSTRUCTIONS = \"\"\"\\\nConfigure the service listening on port {port} to present the certificate\n{cert}\nusing the secret key\n{key}\nwhen it receives a TLS ClientHello with the SNI extension set to\n{sni_domain}\n\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        super(Authenticator, self).__init__(*args, **kwargs)\n        self.reverter = reverter.Reverter(self.config)\n        self.reverter.recovery_routine()\n        self.env = dict()\n        self.tls_sni_01 = None\n\n    @classmethod\n    def add_parser_arguments(cls, add):\n        add('auth-hook',\n            help='Path or command to execute for the authentication script')\n        add('cleanup-hook',\n            help='Path or command to execute for the cleanup script')\n        add('public-ip-logging-ok', action='store_true',\n            help='Automatically allows public IP logging (default: Ask)')\n\n    def prepare(self):  # pylint: disable=missing-docstring\n        if self.config.noninteractive_mode and not self.conf('auth-hook'):\n            raise errors.PluginError(\n                'An authentication script must be provided with --{0} when '\n                'using the manual plugin non-interactively.'.format(\n                    self.option_name('auth-hook')))\n        self._validate_hooks()\n\n    def _validate_hooks(self):\n        if self.config.validate_hooks:\n            for name in ('auth-hook', 'cleanup-hook'):\n                hook = self.conf(name)\n                if hook is not None:\n                    hook_prefix = self.option_name(name)[:-len('-hook')]\n                    hooks.validate_hook(hook, hook_prefix)\n\n    def more_info(self):  # pylint: disable=missing-docstring,no-self-use\n        return (\n            'This plugin allows the user to customize setup for domain '\n            'validation challenges either through shell scripts provided by '\n            'the user or by performing the setup manually.')\n\n    def get_chall_pref(self, domain):\n        # pylint: disable=missing-docstring,no-self-use,unused-argument\n        return [challenges.HTTP01, challenges.DNS01, challenges.TLSSNI01]\n\n    def perform(self, achalls):  # pylint: disable=missing-docstring\n        self._verify_ip_logging_ok()\n        if self.conf('auth-hook'):\n            perform_achall = self._perform_achall_with_script\n        else:\n            perform_achall = self._perform_achall_manually\n\n        responses = []\n        for achall in achalls:\n            if isinstance(achall.chall, challenges.TLSSNI01):\n                # Make a new ManualTlsSni01 instance for each challenge\n                # because the manual plugin deals with one challenge at a time.\n                self.tls_sni_01 = ManualTlsSni01(self)\n                self.tls_sni_01.add_chall(achall)\n                self.tls_sni_01.perform()\n            perform_achall(achall)\n            responses.append(achall.response(achall.account_key))\n        return responses\n\n    def _verify_ip_logging_ok(self):\n        if not self.conf('public-ip-logging-ok'):\n            cli_flag = '--{0}'.format(self.option_name('public-ip-logging-ok'))\n            msg = ('NOTE: The IP of this machine will be publicly logged as '\n                   \"having requested this certificate. If you're running \"\n                   'certbot in manual mode on a machine that is not your '\n                   \"server, please ensure you're okay with that.\\n\\n\"\n                   'Are you OK with your IP being logged?')\n            display = zope.component.getUtility(interfaces.IDisplay)\n            if display.yesno(msg, cli_flag=cli_flag, force_interactive=True):\n                setattr(self.config, self.dest('public-ip-logging-ok'), True)\n            else:\n                raise errors.PluginError('Must agree to IP logging to proceed')\n\n    def _perform_achall_with_script(self, achall):\n        env = dict(CERTBOT_DOMAIN=achall.domain,\n                   CERTBOT_VALIDATION=achall.validation(achall.account_key))\n        if isinstance(achall.chall, challenges.HTTP01):\n            env['CERTBOT_TOKEN'] = achall.chall.encode('token')\n        else:\n            os.environ.pop('CERTBOT_TOKEN', None)\n        if isinstance(achall.chall, challenges.TLSSNI01):\n            env['CERTBOT_CERT_PATH'] = self.tls_sni_01.get_cert_path(achall)\n            env['CERTBOT_KEY_PATH'] = self.tls_sni_01.get_key_path(achall)\n            env['CERTBOT_SNI_DOMAIN'] = self.tls_sni_01.get_z_domain(achall)\n            os.environ.pop('CERTBOT_VALIDATION', None)\n            env.pop('CERTBOT_VALIDATION')\n        else:\n            os.environ.pop('CERTBOT_CERT_PATH', None)\n            os.environ.pop('CERTBOT_KEY_PATH', None)\n            os.environ.pop('CERTBOT_SNI_DOMAIN', None)\n        os.environ.update(env)\n        _, out = hooks.execute(self.conf('auth-hook'))\n        env['CERTBOT_AUTH_OUTPUT'] = out.strip()\n        self.env[achall.domain] = env\n\n    def _perform_achall_manually(self, achall):\n        validation = achall.validation(achall.account_key)\n        if isinstance(achall.chall, challenges.HTTP01):\n            msg = self._HTTP_INSTRUCTIONS.format(\n                achall=achall, encoded_token=achall.chall.encode('token'),\n                port=self.config.http01_port,\n                uri=achall.chall.uri(achall.domain), validation=validation)\n        elif isinstance(achall.chall, challenges.DNS01):\n            msg = self._DNS_INSTRUCTIONS.format(\n                domain=achall.validation_domain_name(achall.domain),\n                validation=validation)\n        else:\n            assert isinstance(achall.chall, challenges.TLSSNI01)\n            msg = self._TLSSNI_INSTRUCTIONS.format(\n                cert=self.tls_sni_01.get_cert_path(achall),\n                key=self.tls_sni_01.get_key_path(achall),\n                port=self.config.tls_sni_01_port,\n                sni_domain=self.tls_sni_01.get_z_domain(achall))\n        display = zope.component.getUtility(interfaces.IDisplay)\n        display.notification(msg, wrap=False, force_interactive=True)\n\n    def cleanup(self, achalls):  # pylint: disable=missing-docstring\n        if self.conf('cleanup-hook'):\n            for achall in achalls:\n                env = self.env.pop(achall.domain)\n                if 'CERTBOT_TOKEN' not in env:\n                    os.environ.pop('CERTBOT_TOKEN', None)\n                os.environ.update(env)\n                hooks.execute(self.conf('cleanup-hook'))\n        self.reverter.recovery_routine()\n", "path": "certbot/plugins/manual.py"}], "after_files": [{"content": "\"\"\"Manual authenticator plugin\"\"\"\nimport os\n\nimport zope.component\nimport zope.interface\n\nfrom acme import challenges\n\nfrom certbot import interfaces\nfrom certbot import errors\nfrom certbot import hooks\nfrom certbot import reverter\nfrom certbot.plugins import common\n\n\nclass ManualTlsSni01(common.TLSSNI01):\n    \"\"\"TLS-SNI-01 authenticator for the Manual plugin\n\n    :ivar configurator: Authenticator object\n    :type configurator: :class:`~certbot.plugins.manual.Authenticator`\n\n    :ivar list achalls: Annotated\n        class:`~certbot.achallenges.KeyAuthorizationAnnotatedChallenge`\n        challenges\n\n    :param list indices: Meant to hold indices of challenges in a\n        larger array. NginxTlsSni01 is capable of solving many challenges\n        at once which causes an indexing issue within NginxConfigurator\n        who must return all responses in order.  Imagine NginxConfigurator\n        maintaining state about where all of the http-01 Challenges,\n        TLS-SNI-01 Challenges belong in the response array.  This is an\n        optional utility.\n\n    :param str challenge_conf: location of the challenge config file\n    \"\"\"\n\n    def perform(self):\n        \"\"\"Create the SSL certificates and private keys\"\"\"\n\n        for achall in self.achalls:\n            self._setup_challenge_cert(achall)\n\n\n@zope.interface.implementer(interfaces.IAuthenticator)\n@zope.interface.provider(interfaces.IPluginFactory)\nclass Authenticator(common.Plugin):\n    \"\"\"Manual authenticator\n\n    This plugin allows the user to perform the domain validation\n    challenge(s) themselves. This either be done manually by the user or\n    through shell scripts provided to Certbot.\n\n    \"\"\"\n\n    description = 'Manual configuration or run your own shell scripts'\n    hidden = True\n    long_description = (\n        'Authenticate through manual configuration or custom shell scripts. '\n        'When using shell scripts, an authenticator script must be provided. '\n        'The environment variables available to this script depend on the '\n        'type of challenge. $CERTBOT_DOMAIN will always contain the domain '\n        'being authenticated. For HTTP-01 and DNS-01, $CERTBOT_VALIDATION '\n        'is the validation string, and $CERTBOT_TOKEN is the filename of the '\n        'resource requested when performing an HTTP-01 challenge. When '\n        'performing a TLS-SNI-01 challenge, $CERTBOT_SNI_DOMAIN will contain '\n        'the SNI name for which the ACME server expects to be presented with '\n        'the self-signed certificate located at $CERTBOT_CERT_PATH. The '\n        'secret key needed to complete the TLS handshake is located at '\n        '$CERTBOT_KEY_PATH. An additional cleanup script can also be '\n        'provided and can use the additional variable $CERTBOT_AUTH_OUTPUT '\n        'which contains the stdout output from the auth script.')\n    _DNS_INSTRUCTIONS = \"\"\"\\\nPlease deploy a DNS TXT record under the name\n{domain} with the following value:\n\n{validation}\n\nBefore continuing, verify the record is deployed.\"\"\"\n    _HTTP_INSTRUCTIONS = \"\"\"\\\nCreate a file containing just this data:\n\n{validation}\n\nAnd make it available on your web server at this URL:\n\n{uri}\n\"\"\"\n    _TLSSNI_INSTRUCTIONS = \"\"\"\\\nConfigure the service listening on port {port} to present the certificate\n{cert}\nusing the secret key\n{key}\nwhen it receives a TLS ClientHello with the SNI extension set to\n{sni_domain}\n\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        super(Authenticator, self).__init__(*args, **kwargs)\n        self.reverter = reverter.Reverter(self.config)\n        self.reverter.recovery_routine()\n        self.env = dict()\n        self.tls_sni_01 = None\n\n    @classmethod\n    def add_parser_arguments(cls, add):\n        add('auth-hook',\n            help='Path or command to execute for the authentication script')\n        add('cleanup-hook',\n            help='Path or command to execute for the cleanup script')\n        add('public-ip-logging-ok', action='store_true',\n            help='Automatically allows public IP logging (default: Ask)')\n\n    def prepare(self):  # pylint: disable=missing-docstring\n        if self.config.noninteractive_mode and not self.conf('auth-hook'):\n            raise errors.PluginError(\n                'An authentication script must be provided with --{0} when '\n                'using the manual plugin non-interactively.'.format(\n                    self.option_name('auth-hook')))\n        self._validate_hooks()\n\n    def _validate_hooks(self):\n        if self.config.validate_hooks:\n            for name in ('auth-hook', 'cleanup-hook'):\n                hook = self.conf(name)\n                if hook is not None:\n                    hook_prefix = self.option_name(name)[:-len('-hook')]\n                    hooks.validate_hook(hook, hook_prefix)\n\n    def more_info(self):  # pylint: disable=missing-docstring,no-self-use\n        return (\n            'This plugin allows the user to customize setup for domain '\n            'validation challenges either through shell scripts provided by '\n            'the user or by performing the setup manually.')\n\n    def get_chall_pref(self, domain):\n        # pylint: disable=missing-docstring,no-self-use,unused-argument\n        return [challenges.HTTP01, challenges.DNS01, challenges.TLSSNI01]\n\n    def perform(self, achalls):  # pylint: disable=missing-docstring\n        self._verify_ip_logging_ok()\n        if self.conf('auth-hook'):\n            perform_achall = self._perform_achall_with_script\n        else:\n            perform_achall = self._perform_achall_manually\n\n        responses = []\n        for achall in achalls:\n            if isinstance(achall.chall, challenges.TLSSNI01):\n                # Make a new ManualTlsSni01 instance for each challenge\n                # because the manual plugin deals with one challenge at a time.\n                self.tls_sni_01 = ManualTlsSni01(self)\n                self.tls_sni_01.add_chall(achall)\n                self.tls_sni_01.perform()\n            perform_achall(achall)\n            responses.append(achall.response(achall.account_key))\n        return responses\n\n    def _verify_ip_logging_ok(self):\n        if not self.conf('public-ip-logging-ok'):\n            cli_flag = '--{0}'.format(self.option_name('public-ip-logging-ok'))\n            msg = ('NOTE: The IP of this machine will be publicly logged as '\n                   \"having requested this certificate. If you're running \"\n                   'certbot in manual mode on a machine that is not your '\n                   \"server, please ensure you're okay with that.\\n\\n\"\n                   'Are you OK with your IP being logged?')\n            display = zope.component.getUtility(interfaces.IDisplay)\n            if display.yesno(msg, cli_flag=cli_flag, force_interactive=True):\n                setattr(self.config, self.dest('public-ip-logging-ok'), True)\n            else:\n                raise errors.PluginError('Must agree to IP logging to proceed')\n\n    def _perform_achall_with_script(self, achall):\n        env = dict(CERTBOT_DOMAIN=achall.domain,\n                   CERTBOT_VALIDATION=achall.validation(achall.account_key))\n        if isinstance(achall.chall, challenges.HTTP01):\n            env['CERTBOT_TOKEN'] = achall.chall.encode('token')\n        else:\n            os.environ.pop('CERTBOT_TOKEN', None)\n        if isinstance(achall.chall, challenges.TLSSNI01):\n            env['CERTBOT_CERT_PATH'] = self.tls_sni_01.get_cert_path(achall)\n            env['CERTBOT_KEY_PATH'] = self.tls_sni_01.get_key_path(achall)\n            env['CERTBOT_SNI_DOMAIN'] = self.tls_sni_01.get_z_domain(achall)\n            os.environ.pop('CERTBOT_VALIDATION', None)\n            env.pop('CERTBOT_VALIDATION')\n        else:\n            os.environ.pop('CERTBOT_CERT_PATH', None)\n            os.environ.pop('CERTBOT_KEY_PATH', None)\n            os.environ.pop('CERTBOT_SNI_DOMAIN', None)\n        os.environ.update(env)\n        _, out = hooks.execute(self.conf('auth-hook'))\n        env['CERTBOT_AUTH_OUTPUT'] = out.strip()\n        self.env[achall] = env\n\n    def _perform_achall_manually(self, achall):\n        validation = achall.validation(achall.account_key)\n        if isinstance(achall.chall, challenges.HTTP01):\n            msg = self._HTTP_INSTRUCTIONS.format(\n                achall=achall, encoded_token=achall.chall.encode('token'),\n                port=self.config.http01_port,\n                uri=achall.chall.uri(achall.domain), validation=validation)\n        elif isinstance(achall.chall, challenges.DNS01):\n            msg = self._DNS_INSTRUCTIONS.format(\n                domain=achall.validation_domain_name(achall.domain),\n                validation=validation)\n        else:\n            assert isinstance(achall.chall, challenges.TLSSNI01)\n            msg = self._TLSSNI_INSTRUCTIONS.format(\n                cert=self.tls_sni_01.get_cert_path(achall),\n                key=self.tls_sni_01.get_key_path(achall),\n                port=self.config.tls_sni_01_port,\n                sni_domain=self.tls_sni_01.get_z_domain(achall))\n        display = zope.component.getUtility(interfaces.IDisplay)\n        display.notification(msg, wrap=False, force_interactive=True)\n\n    def cleanup(self, achalls):  # pylint: disable=missing-docstring\n        if self.conf('cleanup-hook'):\n            for achall in achalls:\n                env = self.env.pop(achall)\n                if 'CERTBOT_TOKEN' not in env:\n                    os.environ.pop('CERTBOT_TOKEN', None)\n                os.environ.update(env)\n                hooks.execute(self.conf('cleanup-hook'))\n        self.reverter.recovery_routine()\n", "path": "certbot/plugins/manual.py"}]}