| 1 |
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license |
| 2 |
|
| 3 |
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. |
| 4 |
# |
| 5 |
# Permission to use, copy, modify, and distribute this software and its |
| 6 |
# documentation for any purpose with or without fee is hereby granted, |
| 7 |
# provided that the above copyright notice and this permission notice |
| 8 |
# appear in all copies. |
| 9 |
# |
| 10 |
# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES |
| 11 |
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |
| 12 |
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR |
| 13 |
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |
| 14 |
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |
| 15 |
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT |
| 16 |
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
| 17 |
|
| 18 |
"""A place to store TSIG keys.""" |
| 19 |
|
| 20 |
import base64 |
| 21 |
from typing import Any, Dict |
| 22 |
|
| 23 |
import dns.name |
| 24 |
import dns.tsig |
| 25 |
|
| 26 |
|
| 27 |
def from_text(textring: Dict[str, Any]) -> Dict[dns.name.Name, Any]: |
| 28 |
"""Convert a dictionary containing (textual DNS name, base64 secret) |
| 29 |
pairs into a binary keyring which has (dns.name.Name, bytes) pairs, or |
| 30 |
a dictionary containing (textual DNS name, (algorithm, base64 secret)) |
| 31 |
pairs into a binary keyring which has (dns.name.Name, dns.tsig.Key) pairs. |
| 32 |
@rtype: dict""" |
| 33 |
|
| 34 |
keyring: Dict[dns.name.Name, Any] = {} |
| 35 |
for name, value in textring.items(): |
| 36 |
kname = dns.name.from_text(name) |
| 37 |
if isinstance(value, str): |
| 38 |
keyring[kname] = dns.tsig.Key(kname, value).secret |
| 39 |
else: |
| 40 |
(algorithm, secret) = value |
| 41 |
keyring[kname] = dns.tsig.Key(kname, secret, algorithm) |
| 42 |
return keyring |
| 43 |
|
| 44 |
|
| 45 |
def to_text(keyring: Dict[dns.name.Name, Any]) -> Dict[str, Any]: |
| 46 |
"""Convert a dictionary containing (dns.name.Name, dns.tsig.Key) pairs |
| 47 |
into a text keyring which has (textual DNS name, (textual algorithm, |
| 48 |
base64 secret)) pairs, or a dictionary containing (dns.name.Name, bytes) |
| 49 |
pairs into a text keyring which has (textual DNS name, base64 secret) pairs. |
| 50 |
@rtype: dict""" |
| 51 |
|
| 52 |
textring = {} |
| 53 |
|
| 54 |
def b64encode(secret): |
| 55 |
return base64.encodebytes(secret).decode().rstrip() |
| 56 |
|
| 57 |
for name, key in keyring.items(): |
| 58 |
tname = name.to_text() |
| 59 |
if isinstance(key, bytes): |
| 60 |
textring[tname] = b64encode(key) |
| 61 |
else: |
| 62 |
if isinstance(key.secret, bytes): |
| 63 |
text_secret = b64encode(key.secret) |
| 64 |
else: |
| 65 |
text_secret = str(key.secret) |
| 66 |
|
| 67 |
textring[tname] = (key.algorithm.to_text(), text_secret) |
| 68 |
return textring |