Debian Codegraph @

test/integration/targets/module_utils_urls/library/test_peercert.py

raw
1 #!/usr/bin/python
2
3 # Copyright: (c) 2020, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 from __future__ import annotations
6
7 DOCUMENTATION = r"""
8 ---
9 module: test_perrcert
10 short_description: Test getting the peer certificate of a HTTP response
11 description: Test getting the peer certificate of a HTTP response.
12 options:
13 url:
14 description: The endpoint to get the peer cert for
15 required: true
16 type: str
17 author:
18 - Ansible Project
19 """
20
21 EXAMPLES = r"""
22 #
23 """
24
25 RETURN = r"""
26 #
27 """
28
29 import base64
30
31 from ansible.module_utils.basic import AnsibleModule
32 from ansible.module_utils.common.text.converters import to_text
33 from ansible.module_utils.urls import getpeercert, Request
34
35
36 def get_x509_shorthand(name, value):
37 prefix = {
38 'countryName': 'C',
39 'stateOrProvinceName': 'ST',
40 'localityName': 'L',
41 'organizationName': 'O',
42 'commonName': 'CN',
43 'organizationalUnitName': 'OU',
44 }[name]
45
46 return '%s=%s' % (prefix, value)
47
48
49 def main():
50 module_args = dict(
51 url=dict(type='str', required=True),
52 )
53 module = AnsibleModule(
54 argument_spec=module_args,
55 supports_check_mode=True,
56 )
57 result = {
58 'changed': False,
59 'cert': None,
60 'raw_cert': None,
61 }
62
63 req = Request().get(module.params['url'])
64 try:
65 cert = getpeercert(req)
66 b_cert = getpeercert(req, binary_form=True)
67
68 finally:
69 req.close()
70
71 if cert:
72 processed_cert = {
73 'issuer': '',
74 'not_after': cert.get('notAfter', None),
75 'not_before': cert.get('notBefore', None),
76 'serial_number': cert.get('serialNumber', None),
77 'subject': '',
78 'version': cert.get('version', None),
79 }
80
81 for field in ['issuer', 'subject']:
82 field_values = []
83 for x509_part in cert.get(field, []):
84 field_values.append(get_x509_shorthand(x509_part[0][0], x509_part[0][1]))
85
86 processed_cert[field] = ",".join(field_values)
87
88 result['cert'] = processed_cert
89
90 if b_cert:
91 result['raw_cert'] = to_text(base64.b64encode(b_cert))
92
93 module.exit_json(**result)
94
95
96 if __name__ == '__main__':
97 main()