| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# Copyright: (c) 2020, Jordan Borean (@jborean93) <[email protected]> |
| 3 |
# MIT License (see LICENSE or https://opensource.org/licenses/MIT) |
| 4 |
|
| 5 |
import os |
| 6 |
import socket |
| 7 |
|
| 8 |
import pytest |
| 9 |
|
| 10 |
from spnego._text import to_bytes, to_text |
| 11 |
|
| 12 |
HAS_K5TEST = True |
| 13 |
try: |
| 14 |
from k5test.realm import K5Realm |
| 15 |
except Exception: # Can fail with more than ImportError on some systems |
| 16 |
HAS_K5TEST = False |
| 17 |
|
| 18 |
HAS_SSPI = True |
| 19 |
try: |
| 20 |
import win32net |
| 21 |
import win32netcon |
| 22 |
except ImportError: |
| 23 |
HAS_SSPI = False |
| 24 |
|
| 25 |
|
| 26 |
def get_data(name: str) -> bytes: |
| 27 |
with open(os.path.join(os.path.dirname(__file__), "data", name), mode="rb") as fd: |
| 28 |
return fd.read() |
| 29 |
|
| 30 |
|
| 31 |
@pytest.fixture() |
| 32 |
def ntlm_cred(tmpdir, monkeypatch): |
| 33 |
cleanup = None |
| 34 |
try: |
| 35 |
# Use unicode credentials to test out edge cases when dealing with non-ascii chars. |
| 36 |
username = "ÜseӜ" |
| 37 |
password = "Pӓ$sw0r̈d" |
| 38 |
|
| 39 |
if HAS_SSPI: |
| 40 |
domain = to_text(socket.gethostname()) |
| 41 |
|
| 42 |
# Can only test this out with Windows due to issue with gss-ntlmssp when dealing with surrogate pairs. |
| 43 |
# https://github.com/gssapi/gss-ntlmssp/issues/20 |
| 44 |
clef = to_text(b"\xF0\x9D\x84\x9E") |
| 45 |
username += clef |
| 46 |
password += clef |
| 47 |
|
| 48 |
buff = { |
| 49 |
"name": username, |
| 50 |
"password": password, |
| 51 |
"priv": win32netcon.USER_PRIV_USER, |
| 52 |
"comment": "Test account for pypsnego tests", |
| 53 |
"flags": win32netcon.UF_NORMAL_ACCOUNT, |
| 54 |
} |
| 55 |
try: |
| 56 |
win32net.NetUserAdd(None, 1, buff) |
| 57 |
except win32net.error as err: |
| 58 |
if err.winerror != 2224: # Account already exists |
| 59 |
raise |
| 60 |
|
| 61 |
def cleanup() -> None: |
| 62 |
win32net.NetUserDel(None, username) |
| 63 |
|
| 64 |
else: |
| 65 |
domain = "Dȫm̈Ąiᴞ" |
| 66 |
|
| 67 |
tmp_creds = os.path.join(to_text(tmpdir), "pÿspᴞӛgӫ TÈ$" ".creds") |
| 68 |
with open(tmp_creds, mode="wb") as fd: |
| 69 |
fd.write(to_bytes("%s:%s:%s" % (domain, username, password))) |
| 70 |
|
| 71 |
monkeypatch.setenv("NTLM_USER_FILE", to_text(tmp_creds)) |
| 72 |
|
| 73 |
yield "%s\\%s" % (domain, username), password |
| 74 |
|
| 75 |
finally: |
| 76 |
if cleanup: |
| 77 |
cleanup() |
| 78 |
|
| 79 |
|
| 80 |
@pytest.fixture() |
| 81 |
def kerb_cred(monkeypatch): |
| 82 |
if not HAS_K5TEST: |
| 83 |
pytest.skip("Cannot create Kerberos credential without k5test being installed") |
| 84 |
|
| 85 |
realm = K5Realm() |
| 86 |
try: |
| 87 |
for k, v in realm.env.items(): |
| 88 |
monkeypatch.setenv(to_text(k), to_text(v)) |
| 89 |
|
| 90 |
yield realm |
| 91 |
|
| 92 |
finally: |
| 93 |
realm.stop() |
| 94 |
del realm |