| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# (c) 2018, Jordan Borean <[email protected]> |
| 3 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import os |
| 8 |
import typing as t |
| 9 |
|
| 10 |
import pytest |
| 11 |
|
| 12 |
from unittest.mock import MagicMock |
| 13 |
from ansible.errors import AnsibleConnectionFailure, AnsibleError |
| 14 |
from ansible.module_utils.common.text.converters import to_bytes |
| 15 |
from ansible.playbook.play_context import PlayContext |
| 16 |
from ansible.plugins.loader import connection_loader |
| 17 |
from ansible.plugins.connection import winrm |
| 18 |
|
| 19 |
pytest.importorskip("winrm") |
| 20 |
|
| 21 |
|
| 22 |
class TestConnectionWinRM(object): |
| 23 |
|
| 24 |
OPTIONS_DATA: tuple[tuple[dict[str, t.Any], dict[str, t.Any], dict[str, t.Any], bool], ...] = ( |
| 25 |
# default options |
| 26 |
( |
| 27 |
{'_extras': {}}, |
| 28 |
{}, |
| 29 |
{ |
| 30 |
'_kerb_managed': False, |
| 31 |
'_kinit_cmd': 'kinit', |
| 32 |
'_winrm_connection_timeout': None, |
| 33 |
'_winrm_host': 'inventory_hostname', |
| 34 |
'_winrm_kwargs': {'username': None, 'password': None}, |
| 35 |
'_winrm_pass': None, |
| 36 |
'_winrm_path': '/wsman', |
| 37 |
'_winrm_port': 5986, |
| 38 |
'_winrm_scheme': 'https', |
| 39 |
'_winrm_transport': ['ssl'], |
| 40 |
'_winrm_user': None |
| 41 |
}, |
| 42 |
False |
| 43 |
), |
| 44 |
# http through port |
| 45 |
( |
| 46 |
{'_extras': {}, 'ansible_port': 5985}, |
| 47 |
{}, |
| 48 |
{ |
| 49 |
'_winrm_kwargs': {'username': None, 'password': None}, |
| 50 |
'_winrm_port': 5985, |
| 51 |
'_winrm_scheme': 'http', |
| 52 |
'_winrm_transport': ['plaintext'], |
| 53 |
}, |
| 54 |
False |
| 55 |
), |
| 56 |
# kerberos user with kerb present |
| 57 |
( |
| 58 |
{'_extras': {}, 'ansible_user': '[email protected]'}, |
| 59 |
{}, |
| 60 |
{ |
| 61 |
'_kerb_managed': False, |
| 62 |
'_kinit_cmd': 'kinit', |
| 63 |
'_winrm_kwargs': {'username': '[email protected]', |
| 64 |
'password': None}, |
| 65 |
'_winrm_pass': None, |
| 66 |
'_winrm_transport': ['kerberos'], |
| 67 |
'_winrm_user': '[email protected]' |
| 68 |
}, |
| 69 |
True |
| 70 |
), |
| 71 |
# kerberos user without kerb present |
| 72 |
( |
| 73 |
{'_extras': {}, 'ansible_user': '[email protected]'}, |
| 74 |
{}, |
| 75 |
{ |
| 76 |
'_kerb_managed': False, |
| 77 |
'_kinit_cmd': 'kinit', |
| 78 |
'_winrm_kwargs': {'username': '[email protected]', |
| 79 |
'password': None}, |
| 80 |
'_winrm_pass': None, |
| 81 |
'_winrm_transport': ['kerberos'], |
| 82 |
'_winrm_user': '[email protected]' |
| 83 |
}, |
| 84 |
False |
| 85 |
), |
| 86 |
# kerberos user with managed ticket (implicit) |
| 87 |
( |
| 88 |
{'_extras': {}, 'ansible_user': '[email protected]'}, |
| 89 |
{'remote_password': 'pass'}, |
| 90 |
{ |
| 91 |
'_kerb_managed': True, |
| 92 |
'_kinit_cmd': 'kinit', |
| 93 |
'_winrm_kwargs': {'username': '[email protected]', |
| 94 |
'password': 'pass'}, |
| 95 |
'_winrm_pass': 'pass', |
| 96 |
'_winrm_transport': ['kerberos'], |
| 97 |
'_winrm_user': '[email protected]' |
| 98 |
}, |
| 99 |
True |
| 100 |
), |
| 101 |
# kerb with managed ticket (explicit) |
| 102 |
( |
| 103 |
{'_extras': {}, 'ansible_user': '[email protected]', |
| 104 |
'ansible_winrm_kinit_mode': 'managed'}, |
| 105 |
{'password': 'pass'}, |
| 106 |
{ |
| 107 |
'_kerb_managed': True, |
| 108 |
}, |
| 109 |
True |
| 110 |
), |
| 111 |
# kerb with unmanaged ticket (explicit)) |
| 112 |
( |
| 113 |
{'_extras': {}, 'ansible_user': '[email protected]', |
| 114 |
'ansible_winrm_kinit_mode': 'manual'}, |
| 115 |
{'password': 'pass'}, |
| 116 |
{ |
| 117 |
'_kerb_managed': False, |
| 118 |
}, |
| 119 |
True |
| 120 |
), |
| 121 |
# transport override (single) |
| 122 |
( |
| 123 |
{'_extras': {}, 'ansible_user': '[email protected]', |
| 124 |
'ansible_winrm_transport': 'ntlm'}, |
| 125 |
{}, |
| 126 |
{ |
| 127 |
'_winrm_kwargs': {'username': '[email protected]', |
| 128 |
'password': None}, |
| 129 |
'_winrm_pass': None, |
| 130 |
'_winrm_transport': ['ntlm'], |
| 131 |
}, |
| 132 |
False |
| 133 |
), |
| 134 |
# transport override (list) |
| 135 |
( |
| 136 |
{'_extras': {}, 'ansible_user': '[email protected]', |
| 137 |
'ansible_winrm_transport': ['ntlm', 'certificate']}, |
| 138 |
{}, |
| 139 |
{ |
| 140 |
'_winrm_kwargs': {'username': '[email protected]', |
| 141 |
'password': None}, |
| 142 |
'_winrm_pass': None, |
| 143 |
'_winrm_transport': ['ntlm', 'certificate'], |
| 144 |
}, |
| 145 |
False |
| 146 |
), |
| 147 |
# winrm extras |
| 148 |
( |
| 149 |
{'_extras': {'ansible_winrm_server_cert_validation': 'ignore', |
| 150 |
'ansible_winrm_service': 'WSMAN'}}, |
| 151 |
{}, |
| 152 |
{ |
| 153 |
'_winrm_kwargs': {'username': None, 'password': None, |
| 154 |
'server_cert_validation': 'ignore', |
| 155 |
'service': 'WSMAN'}, |
| 156 |
}, |
| 157 |
False |
| 158 |
), |
| 159 |
# direct override |
| 160 |
( |
| 161 |
{'_extras': {}, 'ansible_winrm_connection_timeout': 5}, |
| 162 |
{'connection_timeout': 10}, |
| 163 |
{ |
| 164 |
'_winrm_connection_timeout': 10, |
| 165 |
}, |
| 166 |
False |
| 167 |
), |
| 168 |
# password as ansible_password |
| 169 |
( |
| 170 |
{'_extras': {}, 'ansible_password': 'pass'}, |
| 171 |
{}, |
| 172 |
{ |
| 173 |
'_winrm_pass': 'pass', |
| 174 |
'_winrm_kwargs': {'username': None, 'password': 'pass'} |
| 175 |
}, |
| 176 |
False |
| 177 |
), |
| 178 |
# password as ansible_winrm_pass |
| 179 |
( |
| 180 |
{'_extras': {}, 'ansible_winrm_pass': 'pass'}, |
| 181 |
{}, |
| 182 |
{ |
| 183 |
'_winrm_pass': 'pass', |
| 184 |
'_winrm_kwargs': {'username': None, 'password': 'pass'} |
| 185 |
}, |
| 186 |
False |
| 187 |
), |
| 188 |
|
| 189 |
# password as ansible_winrm_password |
| 190 |
( |
| 191 |
{'_extras': {}, 'ansible_winrm_password': 'pass'}, |
| 192 |
{}, |
| 193 |
{ |
| 194 |
'_winrm_pass': 'pass', |
| 195 |
'_winrm_kwargs': {'username': None, 'password': 'pass'} |
| 196 |
}, |
| 197 |
False |
| 198 |
), |
| 199 |
) |
| 200 |
|
| 201 |
@pytest.mark.parametrize('options, direct, expected, kerb', |
| 202 |
list(OPTIONS_DATA)) |
| 203 |
def test_set_options(self, options, direct, expected, kerb): |
| 204 |
winrm.HAVE_KERBEROS = kerb |
| 205 |
|
| 206 |
pc = PlayContext() |
| 207 |
|
| 208 |
conn = connection_loader.get('winrm', pc) |
| 209 |
conn.set_options(var_options=options, direct=direct) |
| 210 |
conn._build_winrm_kwargs() |
| 211 |
|
| 212 |
for attr, expected in expected.items(): |
| 213 |
actual = getattr(conn, attr) |
| 214 |
assert actual == expected, \ |
| 215 |
"winrm attr '%s', actual '%s' != expected '%s'"\ |
| 216 |
% (attr, actual, expected) |
| 217 |
|
| 218 |
|
| 219 |
class TestWinRMKerbAuth(object): |
| 220 |
|
| 221 |
@pytest.mark.parametrize('options, expected', [ |
| 222 |
[{"_extras": {}}, |
| 223 |
(["kinit", "user@domain"],)], |
| 224 |
[{"_extras": {}, 'ansible_winrm_kinit_cmd': 'kinit2'}, |
| 225 |
(["kinit2", "user@domain"],)], |
| 226 |
[{"_extras": {'ansible_winrm_kerberos_delegation': True}}, |
| 227 |
(["kinit", "-f", "user@domain"],)], |
| 228 |
[{"_extras": {}, 'ansible_winrm_kinit_args': '-f -p'}, |
| 229 |
(["kinit", "-f", "-p", "user@domain"],)], |
| 230 |
[{"_extras": {}, 'ansible_winrm_kerberos_delegation': True, 'ansible_winrm_kinit_args': '-p'}, |
| 231 |
(["kinit", "-p", "user@domain"],)] |
| 232 |
]) |
| 233 |
def test_kinit_success_subprocess(self, monkeypatch, options, expected): |
| 234 |
def mock_communicate(input=None, timeout=None): |
| 235 |
return b"", b"" |
| 236 |
|
| 237 |
mock_popen = MagicMock() |
| 238 |
mock_popen.return_value.communicate = mock_communicate |
| 239 |
mock_popen.return_value.returncode = 0 |
| 240 |
monkeypatch.setattr("subprocess.Popen", mock_popen) |
| 241 |
|
| 242 |
pc = PlayContext() |
| 243 |
conn = connection_loader.get('winrm', pc) |
| 244 |
conn.set_options(var_options=options) |
| 245 |
conn._build_winrm_kwargs() |
| 246 |
|
| 247 |
conn._kerb_auth("user@domain", "pass") |
| 248 |
mock_calls = mock_popen.mock_calls |
| 249 |
assert len(mock_calls) == 1 |
| 250 |
assert mock_calls[0][1] == expected |
| 251 |
actual_env = mock_calls[0][2]['env'] |
| 252 |
assert sorted(list(actual_env.keys())) == ['KRB5CCNAME', 'PATH'] |
| 253 |
assert actual_env['KRB5CCNAME'].startswith("FILE:/") |
| 254 |
assert actual_env['PATH'] == os.environ['PATH'] |
| 255 |
|
| 256 |
def test_kinit_with_missing_executable_subprocess(self, monkeypatch): |
| 257 |
expected_err = "[Errno 2] No such file or directory: " \ |
| 258 |
"'/fake/kinit': '/fake/kinit'" |
| 259 |
mock_popen = MagicMock(side_effect=OSError(expected_err)) |
| 260 |
|
| 261 |
monkeypatch.setattr("subprocess.Popen", mock_popen) |
| 262 |
|
| 263 |
pc = PlayContext() |
| 264 |
conn = connection_loader.get('winrm', pc) |
| 265 |
options = {"_extras": {}, "ansible_winrm_kinit_cmd": "/fake/kinit"} |
| 266 |
conn.set_options(var_options=options) |
| 267 |
conn._build_winrm_kwargs() |
| 268 |
|
| 269 |
with pytest.raises(AnsibleConnectionFailure) as err: |
| 270 |
conn._kerb_auth("user@domain", "pass") |
| 271 |
assert str(err.value) == "Kerberos auth failure when calling " \ |
| 272 |
"kinit cmd '/fake/kinit': %s" % expected_err |
| 273 |
|
| 274 |
def test_kinit_error_subprocess(self, monkeypatch): |
| 275 |
expected_err = "kinit: krb5_parse_name: " \ |
| 276 |
"Configuration file does not specify default realm" |
| 277 |
|
| 278 |
def mock_communicate(input=None, timeout=None): |
| 279 |
return b"", to_bytes(expected_err) |
| 280 |
|
| 281 |
mock_popen = MagicMock() |
| 282 |
mock_popen.return_value.communicate = mock_communicate |
| 283 |
mock_popen.return_value.returncode = 1 |
| 284 |
monkeypatch.setattr("subprocess.Popen", mock_popen) |
| 285 |
|
| 286 |
pc = PlayContext() |
| 287 |
conn = connection_loader.get('winrm', pc) |
| 288 |
conn.set_options(var_options={"_extras": {}}) |
| 289 |
conn._build_winrm_kwargs() |
| 290 |
|
| 291 |
with pytest.raises(AnsibleConnectionFailure) as err: |
| 292 |
conn._kerb_auth("invaliduser", "pass") |
| 293 |
|
| 294 |
assert str(err.value) == \ |
| 295 |
"Kerberos auth failure for principal invaliduser: %s" % (expected_err) |
| 296 |
|
| 297 |
def test_kinit_error_pass_in_output_subprocess(self, monkeypatch): |
| 298 |
def mock_communicate(input=None, timeout=None): |
| 299 |
return b"", b"Error with kinit\n" + input |
| 300 |
|
| 301 |
mock_popen = MagicMock() |
| 302 |
mock_popen.return_value.communicate = mock_communicate |
| 303 |
mock_popen.return_value.returncode = 1 |
| 304 |
monkeypatch.setattr("subprocess.Popen", mock_popen) |
| 305 |
|
| 306 |
pc = PlayContext() |
| 307 |
conn = connection_loader.get('winrm', pc) |
| 308 |
conn.set_options(var_options={"_extras": {}}) |
| 309 |
conn._build_winrm_kwargs() |
| 310 |
|
| 311 |
with pytest.raises(AnsibleConnectionFailure) as err: |
| 312 |
conn._kerb_auth("username", "password") |
| 313 |
assert str(err.value) == \ |
| 314 |
"Kerberos auth failure for principal username: " \ |
| 315 |
"Error with kinit\n<redacted>" |
| 316 |
|
| 317 |
def test_exec_command_with_timeout(self, monkeypatch): |
| 318 |
requests_exc = pytest.importorskip("requests.exceptions") |
| 319 |
|
| 320 |
pc = PlayContext() |
| 321 |
conn = connection_loader.get('winrm', pc) |
| 322 |
|
| 323 |
mock_proto = MagicMock() |
| 324 |
mock_proto.run_command.side_effect = requests_exc.Timeout("msg") |
| 325 |
|
| 326 |
conn._connected = True |
| 327 |
conn._winrm_host = 'hostname' |
| 328 |
|
| 329 |
monkeypatch.setattr(conn, "_winrm_connect", lambda: mock_proto) |
| 330 |
|
| 331 |
with pytest.raises(AnsibleConnectionFailure) as e: |
| 332 |
conn.exec_command('cmd', in_data=None, sudoable=True) |
| 333 |
|
| 334 |
assert str(e.value) == "winrm connection error: msg" |
| 335 |
|
| 336 |
def test_exec_command_get_output_timeout(self, monkeypatch): |
| 337 |
requests_exc = pytest.importorskip("requests.exceptions") |
| 338 |
|
| 339 |
pc = PlayContext() |
| 340 |
conn = connection_loader.get('winrm', pc) |
| 341 |
|
| 342 |
mock_proto = MagicMock() |
| 343 |
mock_proto.run_command.return_value = "command_id" |
| 344 |
mock_proto.send_message.side_effect = requests_exc.Timeout("msg") |
| 345 |
|
| 346 |
conn._connected = True |
| 347 |
conn._winrm_host = 'hostname' |
| 348 |
|
| 349 |
monkeypatch.setattr(conn, "_winrm_connect", lambda: mock_proto) |
| 350 |
|
| 351 |
with pytest.raises(AnsibleConnectionFailure) as e: |
| 352 |
conn.exec_command('cmd', in_data=None, sudoable=True) |
| 353 |
|
| 354 |
assert str(e.value) == "winrm connection error: msg" |
| 355 |
|
| 356 |
def test_connect_failure_auth_401(self, monkeypatch): |
| 357 |
pc = PlayContext() |
| 358 |
conn = connection_loader.get('winrm', pc) |
| 359 |
conn.set_options(var_options={"ansible_winrm_transport": "basic", "_extras": {}}) |
| 360 |
|
| 361 |
mock_proto = MagicMock() |
| 362 |
mock_proto.open_shell.side_effect = ValueError("Custom exc Code 401") |
| 363 |
|
| 364 |
mock_proto_init = MagicMock() |
| 365 |
mock_proto_init.return_value = mock_proto |
| 366 |
monkeypatch.setattr(winrm, "Protocol", mock_proto_init) |
| 367 |
|
| 368 |
with pytest.raises(AnsibleConnectionFailure, match="the specified credentials were rejected by the server"): |
| 369 |
conn.exec_command('cmd', in_data=None, sudoable=True) |
| 370 |
|
| 371 |
def test_connect_failure_other_exception(self, monkeypatch): |
| 372 |
pc = PlayContext() |
| 373 |
conn = connection_loader.get('winrm', pc) |
| 374 |
conn.set_options(var_options={"ansible_winrm_transport": "basic", "_extras": {}}) |
| 375 |
|
| 376 |
mock_proto = MagicMock() |
| 377 |
mock_proto.open_shell.side_effect = ValueError("Custom exc") |
| 378 |
|
| 379 |
mock_proto_init = MagicMock() |
| 380 |
mock_proto_init.return_value = mock_proto |
| 381 |
monkeypatch.setattr(winrm, "Protocol", mock_proto_init) |
| 382 |
|
| 383 |
with pytest.raises(AnsibleConnectionFailure, match="basic: Custom exc"): |
| 384 |
conn.exec_command('cmd', in_data=None, sudoable=True) |
| 385 |
|
| 386 |
def test_connect_failure_operation_timed_out(self, monkeypatch): |
| 387 |
pc = PlayContext() |
| 388 |
conn = connection_loader.get('winrm', pc) |
| 389 |
conn.set_options(var_options={"ansible_winrm_transport": "basic", "_extras": {}}) |
| 390 |
|
| 391 |
mock_proto = MagicMock() |
| 392 |
mock_proto.open_shell.side_effect = ValueError("Custom exc Operation timed out") |
| 393 |
|
| 394 |
mock_proto_init = MagicMock() |
| 395 |
mock_proto_init.return_value = mock_proto |
| 396 |
monkeypatch.setattr(winrm, "Protocol", mock_proto_init) |
| 397 |
|
| 398 |
with pytest.raises(AnsibleError, match="the connection attempt timed out"): |
| 399 |
conn.exec_command('cmd', in_data=None, sudoable=True) |
| 400 |
|
| 401 |
def test_connect_no_transport(self): |
| 402 |
pc = PlayContext() |
| 403 |
conn = connection_loader.get('winrm', pc) |
| 404 |
conn.set_options(var_options={"_extras": {}}) |
| 405 |
conn._build_winrm_kwargs() |
| 406 |
conn._winrm_transport = [] |
| 407 |
|
| 408 |
with pytest.raises(AnsibleError, match="No transport found for WinRM connection"): |
| 409 |
conn._winrm_connect() |