Debian Codegraph @

test/units/utils/test_encrypt.py

raw
1 # (c) 2018, Matthias Fuchs <[email protected]>
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 from __future__ import annotations
5
6 import pytest
7
8 from pytest_mock import MockerFixture
9
10 from ansible.errors import AnsibleError
11
12 from ansible.plugins.filter.core import get_encrypted_password
13 from ansible.utils import encrypt
14
15
16 def assert_hash(expected, secret, algorithm, **settings):
17 if isinstance(expected, tuple):
18 expected_crypt, expected_passlib = expected
19 else:
20 expected_crypt = expected_passlib = expected
21
22 if encrypt.HAS_CRYPT and algorithm in encrypt.CryptHash.algorithms:
23 assert encrypt.CryptHash(algorithm).hash(secret, **settings) == expected_crypt
24
25 if encrypt.PASSLIB_AVAILABLE:
26 assert encrypt.PasslibHash(algorithm).hash(secret, **settings) == expected_passlib
27
28
29 @pytest.mark.parametrize(
30 ("algorithm", "ident", "salt", "rounds", "expected"),
31 [
32 pytest.param(
33 "bcrypt",
34 None,
35 "1234567890123456789012",
36 None,
37 (
38 "$2b$12$KRGxLBS0Lxe3KBCwKxOzLe6odk8yM9lJBgNtLuDQxUkLDkpGI6twK",
39 "$2b$12$123456789012345678901ugbM1PeTfRQ0t6dCJu5lQA8hwrZOYgDu",
40 ),
41 id="bcrypt_default",
42 ),
43 pytest.param(
44 "bcrypt",
45 "2",
46 "1234567890123456789012",
47 None,
48 "$2$12$123456789012345678901ufd3hZRrev.WXCbemqGIV/gmWaTGLImm",
49 id="bcrypt_ident_2",
50 marks=pytest.mark.xfail(reason="crypt_gensalt rejects old bcrypt ident '2', unlike passlib"),
51 ),
52 pytest.param(
53 "bcrypt",
54 "2y",
55 "1234567890123456789012",
56 None,
57 (
58 "$2y$12$KRGxLBS0Lxe3KBCwKxOzLe6odk8yM9lJBgNtLuDQxUkLDkpGI6twK",
59 "$2y$12$123456789012345678901ugbM1PeTfRQ0t6dCJu5lQA8hwrZOYgDu",
60 ),
61 id="bcrypt_ident_2y",
62 ),
63 pytest.param(
64 "bcrypt",
65 "2a",
66 "1234567890123456789012",
67 None,
68 (
69 "$2a$12$KRGxLBS0Lxe3KBCwKxOzLe6odk8yM9lJBgNtLuDQxUkLDkpGI6twK",
70 "$2a$12$123456789012345678901ugbM1PeTfRQ0t6dCJu5lQA8hwrZOYgDu",
71 ),
72 id="bcrypt_ident_2a",
73 ),
74 pytest.param(
75 "bcrypt",
76 "2b",
77 "1234567890123456789012",
78 None,
79 (
80 "$2b$12$KRGxLBS0Lxe3KBCwKxOzLe6odk8yM9lJBgNtLuDQxUkLDkpGI6twK",
81 "$2b$12$123456789012345678901ugbM1PeTfRQ0t6dCJu5lQA8hwrZOYgDu",
82 ),
83 id="bcrypt_ident_2b",
84 ),
85 pytest.param(
86 "sha256_crypt",
87 "invalid_ident",
88 "12345678",
89 5000,
90 "$5$l6nAoIXB$HtZrcvuIcvGwySXwnxGHuwyIha2FvzAt4QebHp43Wq4",
91 id="sha256_crypt_invalid_ident",
92 marks=pytest.mark.xfail(reason="crypt_gensalt rejects invalid idents, unlike passlib"),
93 ),
94 pytest.param(
95 "crypt16",
96 None,
97 "12",
98 None,
99 "12pELHK2ME3McUFlHxel6uMM",
100 id="crypt16_no_ident",
101 ),
102 ],
103 )
104 @pytest.mark.skipif(not encrypt.PASSLIB_AVAILABLE, reason='passlib must be installed to run this test')
105 def test_encrypt_with_ident(algorithm, ident, salt, rounds, expected):
106 assert_hash(expected, secret="123", algorithm=algorithm, salt=salt, rounds=rounds, ident=ident)
107
108
109 @pytest.mark.parametrize(
110 ("algorithm", "rounds", "expected"),
111 [
112 pytest.param(
113 "sha256_crypt",
114 None,
115 (
116 "$5$rounds=535000$l6nAoIXB$A2HBLoxGx60mfezwjZ6VFd9vI1.V4oKpd.iwYU4n776",
117 "$5$rounds=535000$12345678$uy3TurUPaY71aioJi58HvUY8jkbhSQU8HepbyaNngv.",
118 ),
119 id="sha256_crypt_default_rounds",
120 ),
121 pytest.param(
122 "sha256_crypt",
123 5000,
124 ("$5$l6nAoIXB$HtZrcvuIcvGwySXwnxGHuwyIha2FvzAt4QebHp43Wq4", "$5$12345678$uAZsE3BenI2G.nA8DpTl.9Dc8JiqacI53pEqRr5ppT7"),
125 id="sha256_crypt_rounds_5000",
126 ),
127 pytest.param(
128 "sha256_crypt",
129 10000,
130 (
131 "$5$rounds=10000$l6nAoIXB$//KYvMXLmzwUUYyWJmAJAeZuP7rsroMayX9hUhpwRC.",
132 "$5$rounds=10000$12345678$JBinliYMFEcBeAXKZnLjenhgEhTmJBvZn3aR8l70Oy/",
133 ),
134 id="sha256_crypt_rounds_10000",
135 ),
136 pytest.param(
137 "sha512_crypt",
138 None,
139 (
140 "$6$rounds=656000$l6nAoIXB$wDP2gGfore3TlBdPvi0wqot7zj8oodeHnEPerC1blJBRGEodsNewNfzxM5nYdfPMkvCh5Af/w82wvG2U3PpCT0",
141 "$6$rounds=656000$12345678$InMy49UwxyCh2pGJU1NpOhVSElDDzKeyuC6n6E9O34BCUGVNYADnI.rcA3m.Vro9BiZpYmjEoNhpREqQcbvQ80",
142 ),
143 id="sha512_crypt_default_rounds",
144 ),
145 pytest.param(
146 "sha512_crypt",
147 5000,
148 (
149 "$6$l6nAoIXB$Zva3RkTY95C0FM0fV9WhLyrQO7/jMt1sICo8bQZvpbRIhDYcgiNdL7IzdlGxG6j6CdkWdqeAk4/W49qkAuv/h/",
150 "$6$12345678$LcV9LQiaPekQxZ.OfkMADjFdSO2k9zfbDQrHPVcYjSLqSdjLYpsgqviYvTEP/R41yPmhH3CCeEDqVhW1VHr3L.",
151 ),
152 id="sha512_crypt_rounds_5000",
153 ),
154 pytest.param(
155 "md5_crypt",
156 None,
157 ("$1$l6nAoIXB$FCE6sRsviKJtqJWkAK6ff0", "$1$12345678$tRy4cXc3kmcfRZVj4iFXr/"),
158 id="md5_crypt_default_rounds",
159 ),
160 ],
161 )
162 @pytest.mark.skipif(not encrypt.PASSLIB_AVAILABLE, reason='passlib must be installed to run this test')
163 def test_encrypt_with_rounds(algorithm, rounds, expected):
164 assert_hash(expected, secret="123", algorithm=algorithm, salt="12345678", rounds=rounds)
165
166
167 @pytest.mark.skipif(not encrypt.PASSLIB_AVAILABLE, reason='passlib must be installed to run this test')
168 def test_password_hash_filter_passlib_with_exception():
169
170 with pytest.raises(AnsibleError):
171 get_encrypted_password("123", "sha257", salt="12345678")
172
173
174 @pytest.mark.parametrize(
175 ("algorithm", "rounds", "expected_hash"),
176 [
177 pytest.param(
178 "sha256",
179 None,
180 "$5$rounds=535000$l6nAoIXB$A2HBLoxGx60mfezwjZ6VFd9vI1.V4oKpd.iwYU4n776",
181 id="sha256_default_rounds",
182 ),
183 pytest.param(
184 "sha256",
185 5000,
186 "$5$l6nAoIXB$HtZrcvuIcvGwySXwnxGHuwyIha2FvzAt4QebHp43Wq4",
187 id="sha256_rounds_5000",
188 ),
189 pytest.param(
190 "sha256",
191 10000,
192 "$5$rounds=10000$l6nAoIXB$//KYvMXLmzwUUYyWJmAJAeZuP7rsroMayX9hUhpwRC.",
193 id="sha256_rounds_10000",
194 ),
195 pytest.param(
196 "sha512",
197 5000,
198 "$6$l6nAoIXB$Zva3RkTY95C0FM0fV9WhLyrQO7/jMt1sICo8bQZvpbRIhDYcgiNdL7IzdlGxG6j6CdkWdqeAk4/W49qkAuv/h/",
199 id="sha512_rounds_5000",
200 ),
201 pytest.param(
202 "sha512",
203 6000,
204 "$6$rounds=6000$l6nAoIXB$DMD7Me00a9FHa5hF22mKek6.Hf7dD6UvJBuRLKus7K//G2kRwcKx5pkp5vGDk5E/MEQgR0yaEsv6ooq3iGRqp/",
205 id="sha512_rounds_6000",
206 ),
207 ],
208 )
209 @pytest.mark.skipif(not encrypt.PASSLIB_AVAILABLE, reason='passlib must be installed to run this test')
210 def test_password_hash_filter_passlib(algorithm, rounds, expected_hash):
211 assert get_encrypted_password("123", algorithm, salt="12345678", rounds=rounds) == expected_hash
212
213
214 @pytest.mark.skipif(not encrypt.PASSLIB_AVAILABLE, reason='passlib must be installed to run this test')
215 def test_do_encrypt_passlib_with_exception():
216 with pytest.raises(AnsibleError):
217 encrypt.do_encrypt("123", "sha257_crypt", salt="12345678")
218
219
220 def test_random_salt():
221 res = encrypt.random_salt()
222 expected_salt_candidate_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./'
223 assert len(res) == 8
224 for res_char in res:
225 assert res_char in expected_salt_candidate_chars
226
227
228 def test_passlib_bcrypt_salt(recwarn):
229 passlib_exc = pytest.importorskip("passlib.exc")
230
231 secret = 'foo'
232 salt = '1234567890123456789012'
233 repaired_salt = '123456789012345678901u'
234 expected = '$2b$12$123456789012345678901uMv44x.2qmQeefEGb3bcIRc1mLuO7bqa'
235 ident = '2b'
236
237 passlib_obj = encrypt.PasslibHash('bcrypt')
238
239 result = passlib_obj.hash(secret, salt=salt, ident=ident)
240 passlib_warnings = [w.message for w in recwarn if isinstance(w.message, passlib_exc.PasslibHashWarning)]
241 assert len(passlib_warnings) == 0
242 assert result == expected
243
244 recwarn.clear()
245
246 result = passlib_obj.hash(secret, salt=repaired_salt, ident=ident)
247 assert result == expected
248
249
250 def test_do_encrypt_no_lib(mocker: MockerFixture) -> None:
251 """Test AnsibleError is raised when no encryption library is installed."""
252 mocker.patch('ansible.utils.encrypt.HAS_CRYPT', False)
253 mocker.patch('ansible.utils.encrypt.PASSLIB_AVAILABLE', False)
254
255 with pytest.raises(AnsibleError, match=r"Unable to encrypt nor hash, either libxcrypt \(recommended\), crypt, or passlib must be installed\."):
256 encrypt.do_encrypt("123", "sha256_crypt", salt="12345678")
257
258
259 class TestCryptHash:
260 """
261 Tests for the CryptHash class.
262
263 These tests are hitting code paths that are otherwise impossible to reach
264 through integration tests, but necessary for more complete code coverage.
265 """
266
267 def test_invalid_instantiation(self, mocker: MockerFixture) -> None:
268 """Should not be able to instantiate a CryptHash class without libxcrypt/libcrypt."""
269 mocker.patch('ansible.utils.encrypt.HAS_CRYPT', False)
270
271 with pytest.raises(AnsibleError, match=r"crypt cannot be used as the 'libxcrypt' library is not installed or is unusable\."):
272 encrypt.CryptHash("sha256_crypt")
273
274 def test_ansible_unsupported_algorithm(self) -> None:
275 """Test AnsibleError is raised when Ansible does not support requested algorithm."""
276 with pytest.raises(AnsibleError, match=r"crypt does not support 'foo' algorithm"):
277 encrypt.CryptHash("foo")
278
279 def test_library_unsupported_algorithm(self, mocker: MockerFixture) -> None:
280 """Test AnsibleError is raised when crypt library does not support an Ansible supported algorithm."""
281 # Pretend we have a crypt lib that doesn't like our algo
282 mocker.patch('ansible.utils.encrypt.HAS_CRYPT', True)
283 mocker.patch('ansible._internal._encryption._crypt.CryptFacade.crypt', side_effect=ValueError)
284
285 # instantiate with an Ansible supported algo
286 crypt_hash = encrypt.CryptHash("sha256_crypt")
287
288 with pytest.raises(AnsibleError, match=r"crypt does not support 'sha256_crypt' algorithm"):
289 crypt_hash.hash("123", salt="12345678")
290
291 def test_build_saltstring_bcrypt_cost_padding(self, mocker: MockerFixture) -> None:
292 """musl libc requires a 2-digit bcrypt cost in the salt string."""
293 mocker.patch('ansible.utils.encrypt.HAS_CRYPT', True)
294 mocker.patch('ansible._internal._encryption._crypt.CryptFacade.has_crypt_gensalt', False)
295
296 crypt_hash = encrypt.CryptHash("bcrypt")
297 saltstring = crypt_hash._build_saltstring('2b', 5, '1234567890123456789012', None)
298
299 assert saltstring == '$2b$05$1234567890123456789012'
300
301
302 class TestPasslibHash:
303 """
304 Tests for the PasslibHash class.
305
306 These tests are hitting code paths that are otherwise impossible to reach
307 through integration tests, but necessary for more complete code coverage.
308 """
309
310 def test_invalid_instantiation(self, mocker: MockerFixture) -> None:
311 """Should not be able to instantiate a PasslibHash class without passlib."""
312 mocker.patch('ansible.utils.encrypt.PASSLIB_AVAILABLE', False)
313
314 with pytest.raises(AnsibleError, match=r"The passlib Python package must be installed to hash with the 'sha256_crypt' algorithm\."):
315 encrypt.PasslibHash("sha256_crypt")