Debian Codegraph @

lib/ansible/utils/hashing.py

raw
1 # (c) 2012-2014, Michael DeHaan <[email protected]>
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17
18 from __future__ import annotations
19
20 import os
21
22 from hashlib import sha1
23
24 try:
25 from hashlib import md5 as _md5
26 except ImportError:
27 # Assume we're running in FIPS mode here
28 _md5 = None
29
30 from ansible.errors import AnsibleError
31 from ansible.module_utils.common.text.converters import to_bytes
32
33
34 def secure_hash_s(data, hash_func=sha1):
35 """ Return a secure hash hex digest of data. """
36
37 digest = hash_func()
38 data = to_bytes(data, errors='surrogate_or_strict')
39 digest.update(data)
40 return digest.hexdigest()
41
42
43 def secure_hash(filename, hash_func=sha1):
44 """ Return a secure hash hex digest of local file, None if file is not present or a directory. """
45
46 if not os.path.exists(to_bytes(filename, errors='surrogate_or_strict')) or os.path.isdir(to_bytes(filename, errors='strict')):
47 return None
48 digest = hash_func()
49 blocksize = 64 * 1024
50 try:
51 with open(filename, 'rb') as infile:
52 block = infile.read(blocksize)
53 while block:
54 digest.update(block)
55 block = infile.read(blocksize)
56 except OSError as ex:
57 raise AnsibleError(f"Error while accessing the file {filename!r}.") from ex
58 return digest.hexdigest()
59
60
61 checksum = secure_hash
62 checksum_s = secure_hash_s
63
64
65 #
66 # Backwards compat functions. Some modules include md5s in their return values
67 # Continue to support that for now. As of ansible-1.8, all of those modules
68 # should also return "checksum" (sha1 for now)
69 # Do not use md5 unless it is needed for:
70 # 1) Optional backwards compatibility
71 # 2) Compliance with a third party protocol
72 #
73 # MD5 will not work on systems which are FIPS-140-2 compliant.
74 #
75
76 def md5s(data):
77 if not _md5:
78 raise ValueError('MD5 not available. Possibly running in FIPS mode')
79 return secure_hash_s(data, _md5)
80
81
82 def md5(filename):
83 if not _md5:
84 raise ValueError('MD5 not available. Possibly running in FIPS mode')
85 return secure_hash(filename, _md5)