We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Allow the certbot_dns_rfc2136 algorithm specified in it's config file to be case insensitive.
## My operating system is (include version):

```
[root@host ~]# head -n4 /etc/os-release
NAME=Fedora
VERSION="29 (Server Edition)"
ID=fedora
VERSION_ID=29
```

## I installed Certbot with (certbot-auto, OS package manager, pip, etc):
OS Package Manager

## I ran this command and it produced this output:
RFC-2136 configuration file contents(Secret is random data and not valid):
```
dns_rfc2136_server = 1.2.3.4
dns_rfc2136_name = certbot
dns_rfc2136_secret = 
Mjk0MjQzZTg1ODk5MTUyMWMyNjZkMjBhYWY1N2UzOGVkMGU1MmM1NDg1OTJiODVmYWY4M2M2N2Uy==
dns_rfc2136_algorithm = hmac-sha512
```

```
[root@host ~]# certbot certonly --dns-rfc2136 --dns-rfc2136-credentials /etc/letsencrypt/rfc2136.ini --server https://acme-v02.api.letsencrypt.org/directory --email email.address@domain.tld --agree-tos --no-eff-email -d 'domain.tld' -d '*.domain.tld'
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator dns-rfc2136, Installer None
Obtaining a new certificate
Performing the following challenges:
dns-01 challenge for domain.tld
dns-01 challenge for domain.tld
Cleaning up challenges
Unknown algorithm: hmac-sha512.
```

## Certbot's behavior differed from what I expected because:
The plugins documentation does not specify that the algorithm name is expected to be all uppercase letters. This causes the command to fail when the plugins configuration file specifies the algorithm with the name provided in lowercase letters.

This is due to the algorithm validation function checking if the specified algorithm name is found in the algorithm dictionary which has the keys named with all uppercase letters.

```
 30     ALGORITHMS = {
 31       'HMAC-MD5': dns.tsig.HMAC_MD5,
 32       'HMAC-SHA1': dns.tsig.HMAC_SHA1,
 33       'HMAC-SHA224': dns.tsig.HMAC_SHA224,
 34       'HMAC-SHA256': dns.tsig.HMAC_SHA256,
 35       'HMAC-SHA384': dns.tsig.HMAC_SHA384,
 36       'HMAC-SHA512': dns.tsig.HMAC_SHA512
 37     }

[...TRUNCATED...]

 57     def _validate_algorithm(self, credentials):
 58         algorithm = credentials.conf('algorithm')
 59         if algorithm:
 60             if not self.ALGORITHMS.get(algorithm):
 61                 raise errors.PluginError("Unknown algorithm: {0}.".format(algorithm))
```

This issue occurred for me due to copying and pasting the results of the `pdnsutil` output when generating the key and after looking at other utilities I couldn't find an example that only worked with the algorithm name being in all caps.

I'm proposing allowing the configuration option to be valid regardless of the case of the letters provided in the value which can easily be done with the patch below.

```
diff --git a/certbot-dns-rfc2136/certbot_dns_rfc2136/dns_rfc2136.py b/certbot-dns-rfc2136/certbot_dns_rfc2136/dns_rfc2136.py
index f985c9bf..2061374e 100644
--- a/certbot-dns-rfc2136/certbot_dns_rfc2136/dns_rfc2136.py
+++ b/certbot-dns-rfc2136/certbot_dns_rfc2136/dns_rfc2136.py
@@ -57,7 +57,7 @@ class Authenticator(dns_common.DNSAuthenticator):
     def _validate_algorithm(self, credentials):
         algorithm = credentials.conf('algorithm')
         if algorithm:
-            if not self.ALGORITHMS.get(algorithm):
+            if not self.ALGORITHMS.get(algorithm.upper()):
                 raise errors.PluginError("Unknown algorithm: {0}.".format(algorithm))

     def _setup_credentials(self):
```

The change made wouldn't have any effect on existing users and would simply remove the strict casing requirement currently in place.

I have a fork with this as well as an update to the unit test for this that I can submit a pull request for should there be any interest in the change.


--- 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-dns-rfc2136/certbot_dns_rfc2136/dns_rfc2136.py`
Content:
```
1 """DNS Authenticator using RFC 2136 Dynamic Updates."""
2 import logging
3 
4 import dns.flags
5 import dns.message
6 import dns.name
7 import dns.query
8 import dns.rdataclass
9 import dns.rdatatype
10 import dns.tsig
11 import dns.tsigkeyring
12 import dns.update
13 import zope.interface
14 
15 from certbot import errors
16 from certbot import interfaces
17 from certbot.plugins import dns_common
18 
19 logger = logging.getLogger(__name__)
20 
21 
22 @zope.interface.implementer(interfaces.IAuthenticator)
23 @zope.interface.provider(interfaces.IPluginFactory)
24 class Authenticator(dns_common.DNSAuthenticator):
25     """DNS Authenticator using RFC 2136 Dynamic Updates
26 
27     This Authenticator uses RFC 2136 Dynamic Updates to fulfull a dns-01 challenge.
28     """
29 
30     ALGORITHMS = {
31       'HMAC-MD5': dns.tsig.HMAC_MD5,
32       'HMAC-SHA1': dns.tsig.HMAC_SHA1,
33       'HMAC-SHA224': dns.tsig.HMAC_SHA224,
34       'HMAC-SHA256': dns.tsig.HMAC_SHA256,
35       'HMAC-SHA384': dns.tsig.HMAC_SHA384,
36       'HMAC-SHA512': dns.tsig.HMAC_SHA512
37     }
38 
39     PORT = 53
40 
41     description = 'Obtain certificates using a DNS TXT record (if you are using BIND for DNS).'
42     ttl = 120
43 
44     def __init__(self, *args, **kwargs):
45         super(Authenticator, self).__init__(*args, **kwargs)
46         self.credentials = None
47 
48     @classmethod
49     def add_parser_arguments(cls, add):  # pylint: disable=arguments-differ
50         super(Authenticator, cls).add_parser_arguments(add, default_propagation_seconds=60)
51         add('credentials', help='RFC 2136 credentials INI file.')
52 
53     def more_info(self):  # pylint: disable=missing-docstring,no-self-use
54         return 'This plugin configures a DNS TXT record to respond to a dns-01 challenge using ' + \
55                'RFC 2136 Dynamic Updates.'
56 
57     def _validate_algorithm(self, credentials):
58         algorithm = credentials.conf('algorithm')
59         if algorithm:
60             if not self.ALGORITHMS.get(algorithm):
61                 raise errors.PluginError("Unknown algorithm: {0}.".format(algorithm))
62 
63     def _setup_credentials(self):
64         self.credentials = self._configure_credentials(
65             'credentials',
66             'RFC 2136 credentials INI file',
67             {
68                 'name': 'TSIG key name',
69                 'secret': 'TSIG key secret',
70                 'server': 'The target DNS server'
71             },
72             self._validate_algorithm
73         )
74 
75     def _perform(self, _domain, validation_name, validation):
76         self._get_rfc2136_client().add_txt_record(validation_name, validation, self.ttl)
77 
78     def _cleanup(self, _domain, validation_name, validation):
79         self._get_rfc2136_client().del_txt_record(validation_name, validation)
80 
81     def _get_rfc2136_client(self):
82         return _RFC2136Client(self.credentials.conf('server'),
83                               int(self.credentials.conf('port') or self.PORT),
84                               self.credentials.conf('name'),
85                               self.credentials.conf('secret'),
86                               self.ALGORITHMS.get(self.credentials.conf('algorithm'),
87                                                   dns.tsig.HMAC_MD5))
88 
89 
90 class _RFC2136Client(object):
91     """
92     Encapsulates all communication with the target DNS server.
93     """
94     def __init__(self, server, port, key_name, key_secret, key_algorithm):
95         self.server = server
96         self.port = port
97         self.keyring = dns.tsigkeyring.from_text({
98             key_name: key_secret
99         })
100         self.algorithm = key_algorithm
101 
102     def add_txt_record(self, record_name, record_content, record_ttl):
103         """
104         Add a TXT record using the supplied information.
105 
106         :param str record_name: The record name (typically beginning with '_acme-challenge.').
107         :param str record_content: The record content (typically the challenge validation).
108         :param int record_ttl: The record TTL (number of seconds that the record may be cached).
109         :raises certbot.errors.PluginError: if an error occurs communicating with the DNS server
110         """
111 
112         domain = self._find_domain(record_name)
113 
114         n = dns.name.from_text(record_name)
115         o = dns.name.from_text(domain)
116         rel = n.relativize(o)
117 
118         update = dns.update.Update(
119             domain,
120             keyring=self.keyring,
121             keyalgorithm=self.algorithm)
122         update.add(rel, record_ttl, dns.rdatatype.TXT, record_content)
123 
124         try:
125             response = dns.query.tcp(update, self.server, port=self.port)
126         except Exception as e:
127             raise errors.PluginError('Encountered error adding TXT record: {0}'
128                                      .format(e))
129         rcode = response.rcode()
130 
131         if rcode == dns.rcode.NOERROR:
132             logger.debug('Successfully added TXT record')
133         else:
134             raise errors.PluginError('Received response from server: {0}'
135                                      .format(dns.rcode.to_text(rcode)))
136 
137     def del_txt_record(self, record_name, record_content):
138         """
139         Delete a TXT record using the supplied information.
140 
141         :param str record_name: The record name (typically beginning with '_acme-challenge.').
142         :param str record_content: The record content (typically the challenge validation).
143         :param int record_ttl: The record TTL (number of seconds that the record may be cached).
144         :raises certbot.errors.PluginError: if an error occurs communicating with the DNS server
145         """
146 
147         domain = self._find_domain(record_name)
148 
149         n = dns.name.from_text(record_name)
150         o = dns.name.from_text(domain)
151         rel = n.relativize(o)
152 
153         update = dns.update.Update(
154             domain,
155             keyring=self.keyring,
156             keyalgorithm=self.algorithm)
157         update.delete(rel, dns.rdatatype.TXT, record_content)
158 
159         try:
160             response = dns.query.tcp(update, self.server, port=self.port)
161         except Exception as e:
162             raise errors.PluginError('Encountered error deleting TXT record: {0}'
163                                      .format(e))
164         rcode = response.rcode()
165 
166         if rcode == dns.rcode.NOERROR:
167             logger.debug('Successfully deleted TXT record')
168         else:
169             raise errors.PluginError('Received response from server: {0}'
170                                      .format(dns.rcode.to_text(rcode)))
171 
172     def _find_domain(self, record_name):
173         """
174         Find the closest domain with an SOA record for a given domain name.
175 
176         :param str record_name: The record name for which to find the closest SOA record.
177         :returns: The domain, if found.
178         :rtype: str
179         :raises certbot.errors.PluginError: if no SOA record can be found.
180         """
181 
182         domain_name_guesses = dns_common.base_domain_name_guesses(record_name)
183 
184         # Loop through until we find an authoritative SOA record
185         for guess in domain_name_guesses:
186             if self._query_soa(guess):
187                 return guess
188 
189         raise errors.PluginError('Unable to determine base domain for {0} using names: {1}.'
190                                  .format(record_name, domain_name_guesses))
191 
192     def _query_soa(self, domain_name):
193         """
194         Query a domain name for an authoritative SOA record.
195 
196         :param str domain_name: The domain name to query for an SOA record.
197         :returns: True if found, False otherwise.
198         :rtype: bool
199         :raises certbot.errors.PluginError: if no response is received.
200         """
201 
202         domain = dns.name.from_text(domain_name)
203 
204         request = dns.message.make_query(domain, dns.rdatatype.SOA, dns.rdataclass.IN)
205         # Turn off Recursion Desired bit in query
206         request.flags ^= dns.flags.RD
207 
208         try:
209             response = dns.query.udp(request, self.server, port=self.port)
210             rcode = response.rcode()
211 
212             # Authoritative Answer bit should be set
213             if (rcode == dns.rcode.NOERROR and response.get_rrset(response.answer,
214                 domain, dns.rdataclass.IN, dns.rdatatype.SOA) and response.flags & dns.flags.AA):
215                 logger.debug('Received authoritative SOA response for %s', domain_name)
216                 return True
217 
218             logger.debug('No authoritative SOA record found for %s', domain_name)
219             return False
220         except Exception as e:
221             raise errors.PluginError('Encountered error when making query: {0}'
222                                      .format(e))
223
```
--- 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-dns-rfc2136/certbot_dns_rfc2136/dns_rfc2136.py b/certbot-dns-rfc2136/certbot_dns_rfc2136/dns_rfc2136.py
--- a/certbot-dns-rfc2136/certbot_dns_rfc2136/dns_rfc2136.py
+++ b/certbot-dns-rfc2136/certbot_dns_rfc2136/dns_rfc2136.py
@@ -57,7 +57,7 @@
     def _validate_algorithm(self, credentials):
         algorithm = credentials.conf('algorithm')
         if algorithm:
-            if not self.ALGORITHMS.get(algorithm):
+            if not self.ALGORITHMS.get(algorithm.upper()):
                 raise errors.PluginError("Unknown algorithm: {0}.".format(algorithm))
 
     def _setup_credentials(self):

{"golden_diff": "diff --git a/certbot-dns-rfc2136/certbot_dns_rfc2136/dns_rfc2136.py b/certbot-dns-rfc2136/certbot_dns_rfc2136/dns_rfc2136.py\n--- a/certbot-dns-rfc2136/certbot_dns_rfc2136/dns_rfc2136.py\n+++ b/certbot-dns-rfc2136/certbot_dns_rfc2136/dns_rfc2136.py\n@@ -57,7 +57,7 @@\n     def _validate_algorithm(self, credentials):\n         algorithm = credentials.conf('algorithm')\n         if algorithm:\n-            if not self.ALGORITHMS.get(algorithm):\n+            if not self.ALGORITHMS.get(algorithm.upper()):\n                 raise errors.PluginError(\"Unknown algorithm: {0}.\".format(algorithm))\n \n     def _setup_credentials(self):\n", "issue": "Allow the certbot_dns_rfc2136 algorithm specified in it's config file to be case insensitive.\n## My operating system is (include version):\r\n\r\n```\r\n[root@host ~]# head -n4 /etc/os-release\r\nNAME=Fedora\r\nVERSION=\"29 (Server Edition)\"\r\nID=fedora\r\nVERSION_ID=29\r\n```\r\n\r\n## I installed Certbot with (certbot-auto, OS package manager, pip, etc):\r\nOS Package Manager\r\n\r\n## I ran this command and it produced this output:\r\nRFC-2136 configuration file contents(Secret is random data and not valid):\r\n```\r\ndns_rfc2136_server = 1.2.3.4\r\ndns_rfc2136_name = certbot\r\ndns_rfc2136_secret = \r\nMjk0MjQzZTg1ODk5MTUyMWMyNjZkMjBhYWY1N2UzOGVkMGU1MmM1NDg1OTJiODVmYWY4M2M2N2Uy==\r\ndns_rfc2136_algorithm = hmac-sha512\r\n```\r\n\r\n```\r\n[root@host ~]# certbot certonly --dns-rfc2136 --dns-rfc2136-credentials /etc/letsencrypt/rfc2136.ini --server https://acme-v02.api.letsencrypt.org/directory --email email.address@domain.tld --agree-tos --no-eff-email -d 'domain.tld' -d '*.domain.tld'\r\nSaving debug log to /var/log/letsencrypt/letsencrypt.log\r\nPlugins selected: Authenticator dns-rfc2136, Installer None\r\nObtaining a new certificate\r\nPerforming the following challenges:\r\ndns-01 challenge for domain.tld\r\ndns-01 challenge for domain.tld\r\nCleaning up challenges\r\nUnknown algorithm: hmac-sha512.\r\n```\r\n\r\n## Certbot's behavior differed from what I expected because:\r\nThe plugins documentation does not specify that the algorithm name is expected to be all uppercase letters. This causes the command to fail when the plugins configuration file specifies the algorithm with the name provided in lowercase letters.\r\n\r\nThis is due to the algorithm validation function checking if the specified algorithm name is found in the algorithm dictionary which has the keys named with all uppercase letters.\r\n\r\n```\r\n 30     ALGORITHMS = {\r\n 31       'HMAC-MD5': dns.tsig.HMAC_MD5,\r\n 32       'HMAC-SHA1': dns.tsig.HMAC_SHA1,\r\n 33       'HMAC-SHA224': dns.tsig.HMAC_SHA224,\r\n 34       'HMAC-SHA256': dns.tsig.HMAC_SHA256,\r\n 35       'HMAC-SHA384': dns.tsig.HMAC_SHA384,\r\n 36       'HMAC-SHA512': dns.tsig.HMAC_SHA512\r\n 37     }\r\n\r\n[...TRUNCATED...]\r\n\r\n 57     def _validate_algorithm(self, credentials):\r\n 58         algorithm = credentials.conf('algorithm')\r\n 59         if algorithm:\r\n 60             if not self.ALGORITHMS.get(algorithm):\r\n 61                 raise errors.PluginError(\"Unknown algorithm: {0}.\".format(algorithm))\r\n```\r\n\r\nThis issue occurred for me due to copying and pasting the results of the `pdnsutil` output when generating the key and after looking at other utilities I couldn't find an example that only worked with the algorithm name being in all caps.\r\n\r\nI'm proposing allowing the configuration option to be valid regardless of the case of the letters provided in the value which can easily be done with the patch below.\r\n\r\n```\r\ndiff --git a/certbot-dns-rfc2136/certbot_dns_rfc2136/dns_rfc2136.py b/certbot-dns-rfc2136/certbot_dns_rfc2136/dns_rfc2136.py\r\nindex f985c9bf..2061374e 100644\r\n--- a/certbot-dns-rfc2136/certbot_dns_rfc2136/dns_rfc2136.py\r\n+++ b/certbot-dns-rfc2136/certbot_dns_rfc2136/dns_rfc2136.py\r\n@@ -57,7 +57,7 @@ class Authenticator(dns_common.DNSAuthenticator):\r\n     def _validate_algorithm(self, credentials):\r\n         algorithm = credentials.conf('algorithm')\r\n         if algorithm:\r\n-            if not self.ALGORITHMS.get(algorithm):\r\n+            if not self.ALGORITHMS.get(algorithm.upper()):\r\n                 raise errors.PluginError(\"Unknown algorithm: {0}.\".format(algorithm))\r\n\r\n     def _setup_credentials(self):\r\n```\r\n\r\nThe change made wouldn't have any effect on existing users and would simply remove the strict casing requirement currently in place.\r\n\r\nI have a fork with this as well as an update to the unit test for this that I can submit a pull request for should there be any interest in the change.\r\n\n", "before_files": [{"content": "\"\"\"DNS Authenticator using RFC 2136 Dynamic Updates.\"\"\"\nimport logging\n\nimport dns.flags\nimport dns.message\nimport dns.name\nimport dns.query\nimport dns.rdataclass\nimport dns.rdatatype\nimport dns.tsig\nimport dns.tsigkeyring\nimport dns.update\nimport zope.interface\n\nfrom certbot import errors\nfrom certbot import interfaces\nfrom certbot.plugins import dns_common\n\nlogger = logging.getLogger(__name__)\n\n\n@zope.interface.implementer(interfaces.IAuthenticator)\n@zope.interface.provider(interfaces.IPluginFactory)\nclass Authenticator(dns_common.DNSAuthenticator):\n    \"\"\"DNS Authenticator using RFC 2136 Dynamic Updates\n\n    This Authenticator uses RFC 2136 Dynamic Updates to fulfull a dns-01 challenge.\n    \"\"\"\n\n    ALGORITHMS = {\n      'HMAC-MD5': dns.tsig.HMAC_MD5,\n      'HMAC-SHA1': dns.tsig.HMAC_SHA1,\n      'HMAC-SHA224': dns.tsig.HMAC_SHA224,\n      'HMAC-SHA256': dns.tsig.HMAC_SHA256,\n      'HMAC-SHA384': dns.tsig.HMAC_SHA384,\n      'HMAC-SHA512': dns.tsig.HMAC_SHA512\n    }\n\n    PORT = 53\n\n    description = 'Obtain certificates using a DNS TXT record (if you are using BIND for DNS).'\n    ttl = 120\n\n    def __init__(self, *args, **kwargs):\n        super(Authenticator, self).__init__(*args, **kwargs)\n        self.credentials = None\n\n    @classmethod\n    def add_parser_arguments(cls, add):  # pylint: disable=arguments-differ\n        super(Authenticator, cls).add_parser_arguments(add, default_propagation_seconds=60)\n        add('credentials', help='RFC 2136 credentials INI file.')\n\n    def more_info(self):  # pylint: disable=missing-docstring,no-self-use\n        return 'This plugin configures a DNS TXT record to respond to a dns-01 challenge using ' + \\\n               'RFC 2136 Dynamic Updates.'\n\n    def _validate_algorithm(self, credentials):\n        algorithm = credentials.conf('algorithm')\n        if algorithm:\n            if not self.ALGORITHMS.get(algorithm):\n                raise errors.PluginError(\"Unknown algorithm: {0}.\".format(algorithm))\n\n    def _setup_credentials(self):\n        self.credentials = self._configure_credentials(\n            'credentials',\n            'RFC 2136 credentials INI file',\n            {\n                'name': 'TSIG key name',\n                'secret': 'TSIG key secret',\n                'server': 'The target DNS server'\n            },\n            self._validate_algorithm\n        )\n\n    def _perform(self, _domain, validation_name, validation):\n        self._get_rfc2136_client().add_txt_record(validation_name, validation, self.ttl)\n\n    def _cleanup(self, _domain, validation_name, validation):\n        self._get_rfc2136_client().del_txt_record(validation_name, validation)\n\n    def _get_rfc2136_client(self):\n        return _RFC2136Client(self.credentials.conf('server'),\n                              int(self.credentials.conf('port') or self.PORT),\n                              self.credentials.conf('name'),\n                              self.credentials.conf('secret'),\n                              self.ALGORITHMS.get(self.credentials.conf('algorithm'),\n                                                  dns.tsig.HMAC_MD5))\n\n\nclass _RFC2136Client(object):\n    \"\"\"\n    Encapsulates all communication with the target DNS server.\n    \"\"\"\n    def __init__(self, server, port, key_name, key_secret, key_algorithm):\n        self.server = server\n        self.port = port\n        self.keyring = dns.tsigkeyring.from_text({\n            key_name: key_secret\n        })\n        self.algorithm = key_algorithm\n\n    def add_txt_record(self, record_name, record_content, record_ttl):\n        \"\"\"\n        Add a TXT record using the supplied information.\n\n        :param str record_name: The record name (typically beginning with '_acme-challenge.').\n        :param str record_content: The record content (typically the challenge validation).\n        :param int record_ttl: The record TTL (number of seconds that the record may be cached).\n        :raises certbot.errors.PluginError: if an error occurs communicating with the DNS server\n        \"\"\"\n\n        domain = self._find_domain(record_name)\n\n        n = dns.name.from_text(record_name)\n        o = dns.name.from_text(domain)\n        rel = n.relativize(o)\n\n        update = dns.update.Update(\n            domain,\n            keyring=self.keyring,\n            keyalgorithm=self.algorithm)\n        update.add(rel, record_ttl, dns.rdatatype.TXT, record_content)\n\n        try:\n            response = dns.query.tcp(update, self.server, port=self.port)\n        except Exception as e:\n            raise errors.PluginError('Encountered error adding TXT record: {0}'\n                                     .format(e))\n        rcode = response.rcode()\n\n        if rcode == dns.rcode.NOERROR:\n            logger.debug('Successfully added TXT record')\n        else:\n            raise errors.PluginError('Received response from server: {0}'\n                                     .format(dns.rcode.to_text(rcode)))\n\n    def del_txt_record(self, record_name, record_content):\n        \"\"\"\n        Delete a TXT record using the supplied information.\n\n        :param str record_name: The record name (typically beginning with '_acme-challenge.').\n        :param str record_content: The record content (typically the challenge validation).\n        :param int record_ttl: The record TTL (number of seconds that the record may be cached).\n        :raises certbot.errors.PluginError: if an error occurs communicating with the DNS server\n        \"\"\"\n\n        domain = self._find_domain(record_name)\n\n        n = dns.name.from_text(record_name)\n        o = dns.name.from_text(domain)\n        rel = n.relativize(o)\n\n        update = dns.update.Update(\n            domain,\n            keyring=self.keyring,\n            keyalgorithm=self.algorithm)\n        update.delete(rel, dns.rdatatype.TXT, record_content)\n\n        try:\n            response = dns.query.tcp(update, self.server, port=self.port)\n        except Exception as e:\n            raise errors.PluginError('Encountered error deleting TXT record: {0}'\n                                     .format(e))\n        rcode = response.rcode()\n\n        if rcode == dns.rcode.NOERROR:\n            logger.debug('Successfully deleted TXT record')\n        else:\n            raise errors.PluginError('Received response from server: {0}'\n                                     .format(dns.rcode.to_text(rcode)))\n\n    def _find_domain(self, record_name):\n        \"\"\"\n        Find the closest domain with an SOA record for a given domain name.\n\n        :param str record_name: The record name for which to find the closest SOA record.\n        :returns: The domain, if found.\n        :rtype: str\n        :raises certbot.errors.PluginError: if no SOA record can be found.\n        \"\"\"\n\n        domain_name_guesses = dns_common.base_domain_name_guesses(record_name)\n\n        # Loop through until we find an authoritative SOA record\n        for guess in domain_name_guesses:\n            if self._query_soa(guess):\n                return guess\n\n        raise errors.PluginError('Unable to determine base domain for {0} using names: {1}.'\n                                 .format(record_name, domain_name_guesses))\n\n    def _query_soa(self, domain_name):\n        \"\"\"\n        Query a domain name for an authoritative SOA record.\n\n        :param str domain_name: The domain name to query for an SOA record.\n        :returns: True if found, False otherwise.\n        :rtype: bool\n        :raises certbot.errors.PluginError: if no response is received.\n        \"\"\"\n\n        domain = dns.name.from_text(domain_name)\n\n        request = dns.message.make_query(domain, dns.rdatatype.SOA, dns.rdataclass.IN)\n        # Turn off Recursion Desired bit in query\n        request.flags ^= dns.flags.RD\n\n        try:\n            response = dns.query.udp(request, self.server, port=self.port)\n            rcode = response.rcode()\n\n            # Authoritative Answer bit should be set\n            if (rcode == dns.rcode.NOERROR and response.get_rrset(response.answer,\n                domain, dns.rdataclass.IN, dns.rdatatype.SOA) and response.flags & dns.flags.AA):\n                logger.debug('Received authoritative SOA response for %s', domain_name)\n                return True\n\n            logger.debug('No authoritative SOA record found for %s', domain_name)\n            return False\n        except Exception as e:\n            raise errors.PluginError('Encountered error when making query: {0}'\n                                     .format(e))\n", "path": "certbot-dns-rfc2136/certbot_dns_rfc2136/dns_rfc2136.py"}], "after_files": [{"content": "\"\"\"DNS Authenticator using RFC 2136 Dynamic Updates.\"\"\"\nimport logging\n\nimport dns.flags\nimport dns.message\nimport dns.name\nimport dns.query\nimport dns.rdataclass\nimport dns.rdatatype\nimport dns.tsig\nimport dns.tsigkeyring\nimport dns.update\nimport zope.interface\n\nfrom certbot import errors\nfrom certbot import interfaces\nfrom certbot.plugins import dns_common\n\nlogger = logging.getLogger(__name__)\n\n\n@zope.interface.implementer(interfaces.IAuthenticator)\n@zope.interface.provider(interfaces.IPluginFactory)\nclass Authenticator(dns_common.DNSAuthenticator):\n    \"\"\"DNS Authenticator using RFC 2136 Dynamic Updates\n\n    This Authenticator uses RFC 2136 Dynamic Updates to fulfull a dns-01 challenge.\n    \"\"\"\n\n    ALGORITHMS = {\n      'HMAC-MD5': dns.tsig.HMAC_MD5,\n      'HMAC-SHA1': dns.tsig.HMAC_SHA1,\n      'HMAC-SHA224': dns.tsig.HMAC_SHA224,\n      'HMAC-SHA256': dns.tsig.HMAC_SHA256,\n      'HMAC-SHA384': dns.tsig.HMAC_SHA384,\n      'HMAC-SHA512': dns.tsig.HMAC_SHA512\n    }\n\n    PORT = 53\n\n    description = 'Obtain certificates using a DNS TXT record (if you are using BIND for DNS).'\n    ttl = 120\n\n    def __init__(self, *args, **kwargs):\n        super(Authenticator, self).__init__(*args, **kwargs)\n        self.credentials = None\n\n    @classmethod\n    def add_parser_arguments(cls, add):  # pylint: disable=arguments-differ\n        super(Authenticator, cls).add_parser_arguments(add, default_propagation_seconds=60)\n        add('credentials', help='RFC 2136 credentials INI file.')\n\n    def more_info(self):  # pylint: disable=missing-docstring,no-self-use\n        return 'This plugin configures a DNS TXT record to respond to a dns-01 challenge using ' + \\\n               'RFC 2136 Dynamic Updates.'\n\n    def _validate_algorithm(self, credentials):\n        algorithm = credentials.conf('algorithm')\n        if algorithm:\n            if not self.ALGORITHMS.get(algorithm.upper()):\n                raise errors.PluginError(\"Unknown algorithm: {0}.\".format(algorithm))\n\n    def _setup_credentials(self):\n        self.credentials = self._configure_credentials(\n            'credentials',\n            'RFC 2136 credentials INI file',\n            {\n                'name': 'TSIG key name',\n                'secret': 'TSIG key secret',\n                'server': 'The target DNS server'\n            },\n            self._validate_algorithm\n        )\n\n    def _perform(self, _domain, validation_name, validation):\n        self._get_rfc2136_client().add_txt_record(validation_name, validation, self.ttl)\n\n    def _cleanup(self, _domain, validation_name, validation):\n        self._get_rfc2136_client().del_txt_record(validation_name, validation)\n\n    def _get_rfc2136_client(self):\n        return _RFC2136Client(self.credentials.conf('server'),\n                              int(self.credentials.conf('port') or self.PORT),\n                              self.credentials.conf('name'),\n                              self.credentials.conf('secret'),\n                              self.ALGORITHMS.get(self.credentials.conf('algorithm'),\n                                                  dns.tsig.HMAC_MD5))\n\n\nclass _RFC2136Client(object):\n    \"\"\"\n    Encapsulates all communication with the target DNS server.\n    \"\"\"\n    def __init__(self, server, port, key_name, key_secret, key_algorithm):\n        self.server = server\n        self.port = port\n        self.keyring = dns.tsigkeyring.from_text({\n            key_name: key_secret\n        })\n        self.algorithm = key_algorithm\n\n    def add_txt_record(self, record_name, record_content, record_ttl):\n        \"\"\"\n        Add a TXT record using the supplied information.\n\n        :param str record_name: The record name (typically beginning with '_acme-challenge.').\n        :param str record_content: The record content (typically the challenge validation).\n        :param int record_ttl: The record TTL (number of seconds that the record may be cached).\n        :raises certbot.errors.PluginError: if an error occurs communicating with the DNS server\n        \"\"\"\n\n        domain = self._find_domain(record_name)\n\n        n = dns.name.from_text(record_name)\n        o = dns.name.from_text(domain)\n        rel = n.relativize(o)\n\n        update = dns.update.Update(\n            domain,\n            keyring=self.keyring,\n            keyalgorithm=self.algorithm)\n        update.add(rel, record_ttl, dns.rdatatype.TXT, record_content)\n\n        try:\n            response = dns.query.tcp(update, self.server, port=self.port)\n        except Exception as e:\n            raise errors.PluginError('Encountered error adding TXT record: {0}'\n                                     .format(e))\n        rcode = response.rcode()\n\n        if rcode == dns.rcode.NOERROR:\n            logger.debug('Successfully added TXT record')\n        else:\n            raise errors.PluginError('Received response from server: {0}'\n                                     .format(dns.rcode.to_text(rcode)))\n\n    def del_txt_record(self, record_name, record_content):\n        \"\"\"\n        Delete a TXT record using the supplied information.\n\n        :param str record_name: The record name (typically beginning with '_acme-challenge.').\n        :param str record_content: The record content (typically the challenge validation).\n        :param int record_ttl: The record TTL (number of seconds that the record may be cached).\n        :raises certbot.errors.PluginError: if an error occurs communicating with the DNS server\n        \"\"\"\n\n        domain = self._find_domain(record_name)\n\n        n = dns.name.from_text(record_name)\n        o = dns.name.from_text(domain)\n        rel = n.relativize(o)\n\n        update = dns.update.Update(\n            domain,\n            keyring=self.keyring,\n            keyalgorithm=self.algorithm)\n        update.delete(rel, dns.rdatatype.TXT, record_content)\n\n        try:\n            response = dns.query.tcp(update, self.server, port=self.port)\n        except Exception as e:\n            raise errors.PluginError('Encountered error deleting TXT record: {0}'\n                                     .format(e))\n        rcode = response.rcode()\n\n        if rcode == dns.rcode.NOERROR:\n            logger.debug('Successfully deleted TXT record')\n        else:\n            raise errors.PluginError('Received response from server: {0}'\n                                     .format(dns.rcode.to_text(rcode)))\n\n    def _find_domain(self, record_name):\n        \"\"\"\n        Find the closest domain with an SOA record for a given domain name.\n\n        :param str record_name: The record name for which to find the closest SOA record.\n        :returns: The domain, if found.\n        :rtype: str\n        :raises certbot.errors.PluginError: if no SOA record can be found.\n        \"\"\"\n\n        domain_name_guesses = dns_common.base_domain_name_guesses(record_name)\n\n        # Loop through until we find an authoritative SOA record\n        for guess in domain_name_guesses:\n            if self._query_soa(guess):\n                return guess\n\n        raise errors.PluginError('Unable to determine base domain for {0} using names: {1}.'\n                                 .format(record_name, domain_name_guesses))\n\n    def _query_soa(self, domain_name):\n        \"\"\"\n        Query a domain name for an authoritative SOA record.\n\n        :param str domain_name: The domain name to query for an SOA record.\n        :returns: True if found, False otherwise.\n        :rtype: bool\n        :raises certbot.errors.PluginError: if no response is received.\n        \"\"\"\n\n        domain = dns.name.from_text(domain_name)\n\n        request = dns.message.make_query(domain, dns.rdatatype.SOA, dns.rdataclass.IN)\n        # Turn off Recursion Desired bit in query\n        request.flags ^= dns.flags.RD\n\n        try:\n            response = dns.query.udp(request, self.server, port=self.port)\n            rcode = response.rcode()\n\n            # Authoritative Answer bit should be set\n            if (rcode == dns.rcode.NOERROR and response.get_rrset(response.answer,\n                domain, dns.rdataclass.IN, dns.rdatatype.SOA) and response.flags & dns.flags.AA):\n                logger.debug('Received authoritative SOA response for %s', domain_name)\n                return True\n\n            logger.debug('No authoritative SOA record found for %s', domain_name)\n            return False\n        except Exception as e:\n            raise errors.PluginError('Encountered error when making query: {0}'\n                                     .format(e))\n", "path": "certbot-dns-rfc2136/certbot_dns_rfc2136/dns_rfc2136.py"}]}