Debian Codegraph @

examples/dump.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # -*- coding: utf-8 -*-
2 #
3 # This file is part of Python-ASN1. Python-ASN1 is free software that is
4 # made available under the MIT license. Consult the file "LICENSE" that
5 # is distributed together with this file for the exact licensing terms.
6 #
7 # Python-ASN1 is copyright (c) 2007-2016 by the Python-ASN1 authors. See
8 # the file "AUTHORS" for a complete overview.
9
10 from __future__ import absolute_import, division, print_function, unicode_literals
11 from builtins import open, bytes, str
12 import sys
13 import base64
14 import binascii
15
16 import asn1
17 import optparse
18
19
20 def read_pem(input_file):
21 """Read PEM formatted input."""
22 data = []
23 state = 0
24 for line in input_file:
25 if state == 0:
26 if line.startswith('-----BEGIN'):
27 state = 1
28 elif state == 1:
29 if line.startswith('-----END'):
30 state = 2
31 else:
32 data.append(line)
33 elif state == 2:
34 break
35 if state != 2:
36 raise ValueError('No PEM encoded input found')
37 data = ''.join(data)
38 return base64.b64decode(data)
39
40
41 tag_id_to_string_map = {
42 asn1.Numbers.Boolean: "BOOLEAN",
43 asn1.Numbers.Integer: "INTEGER",
44 asn1.Numbers.BitString: "BIT STRING",
45 asn1.Numbers.OctetString: "OCTET STRING",
46 asn1.Numbers.Null: "NULL",
47 asn1.Numbers.ObjectIdentifier: "OBJECT",
48 asn1.Numbers.PrintableString: "PRINTABLESTRING",
49 asn1.Numbers.IA5String: "IA5STRING",
50 asn1.Numbers.UTCTime: "UTCTIME",
51 asn1.Numbers.GeneralizedTime: "GENERALIZED TIME",
52 asn1.Numbers.Enumerated: "ENUMERATED",
53 asn1.Numbers.Sequence: "SEQUENCE",
54 asn1.Numbers.Set: "SET"
55 }
56
57 class_id_to_string_map = {
58 asn1.Classes.Universal: "U",
59 asn1.Classes.Application: "A",
60 asn1.Classes.Context: "C",
61 asn1.Classes.Private: "P"
62 }
63
64 object_id_to_string_map = {
65 "1.2.840.113549.1.1.1": "rsaEncryption",
66 "1.2.840.113549.1.1.5": "sha1WithRSAEncryption",
67
68 "1.3.6.1.5.5.7.1.1": "authorityInfoAccess",
69
70 "2.5.4.3": "commonName",
71 "2.5.4.4": "surname",
72 "2.5.4.5": "serialNumber",
73 "2.5.4.6": "countryName",
74 "2.5.4.7": "localityName",
75 "2.5.4.8": "stateOrProvinceName",
76 "2.5.4.9": "streetAddress",
77 "2.5.4.10": "organizationName",
78 "2.5.4.11": "organizationalUnitName",
79 "2.5.4.12": "title",
80 "2.5.4.13": "description",
81 "2.5.4.42": "givenName",
82
83 "1.2.840.113549.1.9.1": "emailAddress",
84
85 "2.5.29.14": "X509v3 Subject Key Identifier",
86 "2.5.29.15": "X509v3 Key Usage",
87 "2.5.29.16": "X509v3 Private Key Usage Period",
88 "2.5.29.17": "X509v3 Subject Alternative Name",
89 "2.5.29.18": "X509v3 Issuer Alternative Name",
90 "2.5.29.19": "X509v3 Basic Constraints",
91 "2.5.29.30": "X509v3 Name Constraints",
92 "2.5.29.31": "X509v3 CRL Distribution Points",
93 "2.5.29.32": "X509v3 Certificate Policies Extension",
94 "2.5.29.33": "X509v3 Policy Mappings",
95 "2.5.29.35": "X509v3 Authority Key Identifier",
96 "2.5.29.36": "X509v3 Policy Constraints",
97 "2.5.29.37": "X509v3 Extended Key Usage"
98 }
99
100
101 def tag_id_to_string(identifier):
102 """Return a string representation of a ASN.1 id."""
103 if identifier in tag_id_to_string_map:
104 return tag_id_to_string_map[identifier]
105 return '{:#02x}'.format(identifier)
106
107
108 def class_id_to_string(identifier):
109 """Return a string representation of an ASN.1 class."""
110 if identifier in class_id_to_string_map:
111 return class_id_to_string_map[identifier]
112 raise ValueError('Illegal class: {:#02x}'.format(identifier))
113
114
115 def object_identifier_to_string(identifier):
116 if identifier in object_id_to_string_map:
117 return object_id_to_string_map[identifier]
118 return identifier
119
120
121 def value_to_string(tag_number, value):
122 if tag_number == asn1.Numbers.ObjectIdentifier:
123 return object_identifier_to_string(value)
124 elif isinstance(value, bytes):
125 return '0x' + str(binascii.hexlify(value).upper())
126 elif isinstance(value, str):
127 return value
128 else:
129 return repr(value)
130
131
132 def pretty_print(input_stream, output_stream, indent=0):
133 """Pretty print ASN.1 data."""
134 while not input_stream.eof():
135 tag = input_stream.peek()
136 if tag.typ == asn1.Types.Primitive:
137 tag, value = input_stream.read()
138 output_stream.write(' ' * indent)
139 output_stream.write('[{}] {}: {}\n'.format(class_id_to_string(tag.cls), tag_id_to_string(tag.nr), value_to_string(tag.nr, value)))
140 elif tag.typ == asn1.Types.Constructed:
141 output_stream.write(' ' * indent)
142 output_stream.write('[{}] {}\n'.format(class_id_to_string(tag.cls), tag_id_to_string(tag.nr)))
143 input_stream.enter()
144 pretty_print(input_stream, output_stream, indent + 2)
145 input_stream.leave()
146
147
148 # Main script
149
150 parser = optparse.OptionParser()
151 parser.add_option('-p', '--pem', dest='mode', action='store_const', const='pem', help='PEM encoded input')
152 parser.add_option('-r', '--raw', dest='mode', action='store_const', const='raw', help='raw input')
153 parser.add_option('-o', '--output', dest='output', help='output to FILE instead', metavar='FILE')
154 parser.set_default('mode', 'pem')
155 (opts, args) = parser.parse_args()
156
157 if opts.mode == 'pem':
158 input_file = open(args[0], 'r')
159 input_data = read_pem(input_file)
160 else:
161 input_file = open(args[0], 'rb')
162 input_data = input_file.read()
163
164 if opts.output:
165 output_file = open(opts.output, 'w')
166 else:
167 output_file = sys.stdout
168
169 decoder = asn1.Decoder()
170 decoder.start(input_data)
171
172 pretty_print(decoder, output_file)