Debian Codegraph @

ansible_collections/community/crypto/plugins/module_utils/_crypto/_asn1.py

raw
1 # Copyright (c) 2020, Jordan Borean <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import enum
11 import re
12
13 from ansible.module_utils.common.text.converters import to_bytes
14
15 # An ASN.1 serialized as a string in the OpenSSL format:
16 # [modifier,]type[:value]
17 #
18 # 'modifier':
19 # The modifier can be 'IMPLICIT:<tag_number><tag_class>,' or 'EXPLICIT:<tag_number><tag_class>' where IMPLICIT
20 # changes the tag of the universal value to encode and EXPLICIT prefixes its tag to the existing universal value.
21 # The tag_number must be set while the tag_class can be 'U', 'A', 'P', or 'C" for 'Universal', 'Application',
22 # 'Private', or 'Context Specific' with C being the default.
23 #
24 # 'type':
25 # The underlying ASN.1 type of the value specified. Currently only the following have been implemented:
26 # UTF8: The value must be a UTF-8 encoded string.
27 #
28 # 'value':
29 # The value to encode, the format of this value depends on the <type> specified.
30 ASN1_STRING_REGEX = re.compile(
31 r"^((?P<tag_type>IMPLICIT|EXPLICIT):(?P<tag_number>\d+)(?P<tag_class>U|A|P|C)?,)?"
32 r"(?P<value_type>[\w\d]+):(?P<value>.*)"
33 )
34
35
36 class TagClass(enum.Enum):
37 UNIVERSAL = 0
38 APPLICATION = 1
39 CONTEXT_SPECIFIC = 2
40 PRIVATE = 3
41
42
43 # Universal tag numbers that can be encoded.
44 class TagNumber(enum.Enum):
45 UTF8_STRING = 12
46
47
48 def _pack_octet_integer(value: int) -> bytes:
49 """Packs an integer value into 1 or multiple octets."""
50 # NOTE: This is *NOT* the same as packing an ASN.1 INTEGER like value.
51 octets = bytearray()
52
53 # Continue to shift the number by 7 bits and pack into an octet until the
54 # value is fully packed.
55 while value:
56 octet_value = value & 0b01111111
57
58 # First round (last octet) must have the MSB set.
59 if len(octets):
60 octet_value |= 0b10000000
61
62 octets.append(octet_value)
63 value >>= 7
64
65 # Reverse to ensure the higher order octets are first.
66 octets.reverse()
67 return bytes(octets)
68
69
70 def serialize_asn1_string_as_der(value: str) -> bytes:
71 """Deserializes an ASN.1 string to a DER encoded byte string."""
72 asn1_match = ASN1_STRING_REGEX.match(value)
73 if not asn1_match:
74 raise ValueError(
75 "The ASN.1 serialized string must be in the format [modifier,]type[:value]"
76 )
77
78 tag_type = asn1_match.group("tag_type")
79 tag_number = asn1_match.group("tag_number")
80 tag_class = asn1_match.group("tag_class") or "C"
81 value_type = asn1_match.group("value_type")
82 asn1_value = asn1_match.group("value")
83
84 if value_type != "UTF8":
85 raise ValueError(
86 f'The ASN.1 serialized string is not a known type "{value_type}", only UTF8 types are supported'
87 )
88
89 b_value = to_bytes(asn1_value, encoding="utf-8", errors="surrogate_or_strict")
90
91 # We should only do a universal type tag if not IMPLICITLY tagged or the tag class is not universal.
92 if not tag_type or (tag_type == "EXPLICIT" and tag_class != "U"):
93 b_value = pack_asn1(
94 tag_class=TagClass.UNIVERSAL,
95 constructed=False,
96 tag_number=TagNumber.UTF8_STRING,
97 b_data=b_value,
98 )
99
100 if tag_type:
101 tag_class_enum = {
102 "U": TagClass.UNIVERSAL,
103 "A": TagClass.APPLICATION,
104 "P": TagClass.PRIVATE,
105 "C": TagClass.CONTEXT_SPECIFIC,
106 }[tag_class]
107
108 # When adding support for more types this should be looked into further. For now it works with UTF8Strings.
109 constructed = tag_type == "EXPLICIT" and tag_class_enum != TagClass.UNIVERSAL
110 b_value = pack_asn1(
111 tag_class=tag_class_enum,
112 constructed=constructed,
113 tag_number=int(tag_number),
114 b_data=b_value,
115 )
116
117 return b_value
118
119
120 def pack_asn1(
121 *,
122 tag_class: TagClass,
123 constructed: bool,
124 tag_number: TagNumber | int,
125 b_data: bytes,
126 ) -> bytes:
127 """Pack the value into an ASN.1 data structure.
128
129 The structure for an ASN.1 element is
130
131 | Identifier Octet(s) | Length Octet(s) | Data Octet(s) |
132 """
133 b_asn1_data = bytearray()
134
135 # Bit 8 and 7 denotes the class.
136 identifier_octets = tag_class.value << 6
137 # Bit 6 denotes whether the value is primitive or constructed.
138 identifier_octets |= (1 if constructed else 0) << 5
139
140 # Bits 5-1 contain the tag number, if it cannot be encoded in these 5 bits
141 # then they are set and another octet(s) is used to denote the tag number.
142 if isinstance(tag_number, TagNumber):
143 tag_number = tag_number.value
144 if tag_number < 31:
145 identifier_octets |= tag_number
146 b_asn1_data.append(identifier_octets)
147 else:
148 identifier_octets |= 31
149 b_asn1_data.append(identifier_octets)
150 b_asn1_data.extend(_pack_octet_integer(tag_number))
151
152 length = len(b_data)
153
154 # If the length can be encoded in 7 bits only 1 octet is required.
155 if length < 128:
156 b_asn1_data.append(length)
157
158 else:
159 # Otherwise the length must be encoded across multiple octets
160 length_octets = bytearray()
161 while length:
162 length_octets.append(length & 0b11111111)
163 length >>= 8
164
165 length_octets.reverse() # Reverse to make the higher octets first.
166
167 # The first length octet must have the MSB set alongside the number of
168 # octets the length was encoded in.
169 b_asn1_data.append(len(length_octets) | 0b10000000)
170 b_asn1_data.extend(length_octets)
171
172 return bytes(b_asn1_data) + b_data
173
174
175 __all__ = ("TagClass", "TagNumber", "pack_asn1", "serialize_asn1_string_as_der")