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