mirror of
https://github.com/python-kasa/python-kasa.git
synced 2026-11-26 16:01:40 +00:00
Try the account e-mail with the Kasa setup password over KLAP (#1840)
Some Kasa IoT devices accept the account e-mail with `kasaSetup` instead of the account password over KLAP. python-kasa only tries that password with the default Kasa account, so these devices fail to authenticate even with the correct account credentials. This PR checks the account e-mail with the setup password locally against handshake1, after the supplied credentials, without an extra request. In details: - Try the e-mail as given, then trimmed and lowercased as the Kasa app sends it. - Keep the fallbacks in one ordered list, with an explicit `save_hash` flag controlling hash persistence. - Save only a matching account/setup hash as `credentials_hash`, so stored configs can reconnect without the e-mail. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -117,8 +117,6 @@ class KlapTransport(BaseTransport):
|
|||||||
self._local_auth_owner = self.generate_owner_hash(self._credentials).hex()
|
self._local_auth_owner = self.generate_owner_hash(self._credentials).hex()
|
||||||
else:
|
else:
|
||||||
self._local_auth_hash = base64.b64decode(self._credentials_hash.encode()) # type: ignore[union-attr]
|
self._local_auth_hash = base64.b64decode(self._credentials_hash.encode()) # type: ignore[union-attr]
|
||||||
self._default_credentials_auth_hash: dict[str, bytes] = {}
|
|
||||||
self._blank_auth_hash: bytes | None = None
|
|
||||||
self._handshake_lock = asyncio.Lock()
|
self._handshake_lock = asyncio.Lock()
|
||||||
self._query_lock = asyncio.Lock()
|
self._query_lock = asyncio.Lock()
|
||||||
self._handshake_done: bool = False
|
self._handshake_done: bool = False
|
||||||
@@ -230,48 +228,21 @@ class KlapTransport(BaseTransport):
|
|||||||
_LOGGER.debug("handshake1 hashes match with expected credentials")
|
_LOGGER.debug("handshake1 hashes match with expected credentials")
|
||||||
return local_seed, remote_seed, self._local_auth_hash # type: ignore
|
return local_seed, remote_seed, self._local_auth_hash # type: ignore
|
||||||
|
|
||||||
# Now check against the default setup credentials
|
for description, auth_hash, save_hash in self._fallback_auth_hashes():
|
||||||
for key, value in DEFAULT_CREDENTIALS.items():
|
if (
|
||||||
if key not in self._default_credentials_auth_hash:
|
self.handshake1_seed_auth_hash(local_seed, remote_seed, auth_hash)
|
||||||
default_credentials = get_default_credentials(value)
|
== server_hash
|
||||||
self._default_credentials_auth_hash[key] = self.generate_auth_hash(
|
):
|
||||||
default_credentials
|
|
||||||
)
|
|
||||||
|
|
||||||
default_credentials_seed_auth_hash = self.handshake1_seed_auth_hash(
|
|
||||||
local_seed,
|
|
||||||
remote_seed,
|
|
||||||
self._default_credentials_auth_hash[key], # type: ignore
|
|
||||||
)
|
|
||||||
|
|
||||||
if default_credentials_seed_auth_hash == server_hash:
|
|
||||||
_LOGGER.debug(
|
_LOGGER.debug(
|
||||||
"Device response did not match our expected hash on ip %s, "
|
"Device response did not match our expected hash on ip %s, "
|
||||||
"but an authentication with %s default credentials worked",
|
"but %s worked",
|
||||||
self._host,
|
self._host,
|
||||||
key,
|
description,
|
||||||
)
|
)
|
||||||
return local_seed, remote_seed, self._default_credentials_auth_hash[key] # type: ignore
|
if save_hash:
|
||||||
|
# A stored hash has no e-mail to rebuild this one from
|
||||||
# Finally check against blank credentials if not already blank
|
self._local_auth_hash = auth_hash
|
||||||
blank_creds = Credentials()
|
return local_seed, remote_seed, auth_hash
|
||||||
if self._credentials != blank_creds:
|
|
||||||
if not self._blank_auth_hash:
|
|
||||||
self._blank_auth_hash = self.generate_auth_hash(blank_creds)
|
|
||||||
|
|
||||||
blank_seed_auth_hash = self.handshake1_seed_auth_hash(
|
|
||||||
local_seed,
|
|
||||||
remote_seed,
|
|
||||||
self._blank_auth_hash, # type: ignore
|
|
||||||
)
|
|
||||||
|
|
||||||
if blank_seed_auth_hash == server_hash:
|
|
||||||
_LOGGER.debug(
|
|
||||||
"Device response did not match our expected hash on ip %s, "
|
|
||||||
"but an authentication with blank credentials worked",
|
|
||||||
self._host,
|
|
||||||
)
|
|
||||||
return local_seed, remote_seed, self._blank_auth_hash # type: ignore
|
|
||||||
|
|
||||||
msg = (
|
msg = (
|
||||||
f"Device response did not match our challenge on ip {self._host}, "
|
f"Device response did not match our challenge on ip {self._host}, "
|
||||||
@@ -280,6 +251,32 @@ class KlapTransport(BaseTransport):
|
|||||||
_LOGGER.debug(msg)
|
_LOGGER.debug(msg)
|
||||||
raise AuthenticationError(msg)
|
raise AuthenticationError(msg)
|
||||||
|
|
||||||
|
def _fallback_auth_hashes(self) -> list[tuple[str, bytes, bool]]:
|
||||||
|
"""Return fallback descriptions, auth hashes and whether to save the hash."""
|
||||||
|
username = self._credentials.username if self._credentials else ""
|
||||||
|
setup_password = get_default_credentials(DEFAULT_CREDENTIALS["KASA"]).password
|
||||||
|
# The Kasa app uses this pair, with the e-mail trimmed and lowercased,
|
||||||
|
# when the discovery reply has ANS
|
||||||
|
fallbacks = [
|
||||||
|
(
|
||||||
|
"the account e-mail with the setup password",
|
||||||
|
Credentials(name, setup_password),
|
||||||
|
True,
|
||||||
|
)
|
||||||
|
for name in dict.fromkeys([username, username.strip().lower()])
|
||||||
|
if name
|
||||||
|
]
|
||||||
|
fallbacks += [
|
||||||
|
(f"the {key} default credentials", get_default_credentials(value), False)
|
||||||
|
for key, value in DEFAULT_CREDENTIALS.items()
|
||||||
|
]
|
||||||
|
fallbacks.append(("blank credentials", Credentials(), False))
|
||||||
|
return [
|
||||||
|
(description, self.generate_auth_hash(credentials), save_hash)
|
||||||
|
for description, credentials, save_hash in fallbacks
|
||||||
|
if credentials != self._credentials
|
||||||
|
]
|
||||||
|
|
||||||
async def perform_handshake2(
|
async def perform_handshake2(
|
||||||
self, local_seed: bytes, remote_seed: bytes, auth_hash: bytes
|
self, local_seed: bytes, remote_seed: bytes, auth_hash: bytes
|
||||||
) -> KlapEncryptionSession:
|
) -> KlapEncryptionSession:
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import re
|
import re
|
||||||
@@ -467,12 +468,13 @@ async def test_protocol_invalid_response(
|
|||||||
get_default_credentials(DEFAULT_CREDENTIALS["KASA"]),
|
get_default_credentials(DEFAULT_CREDENTIALS["KASA"]),
|
||||||
does_not_raise(),
|
does_not_raise(),
|
||||||
),
|
),
|
||||||
|
(Credentials("foo", "kasaSetup"), does_not_raise()),
|
||||||
(
|
(
|
||||||
Credentials("shouldfail", "shouldfail"),
|
Credentials("shouldfail", "shouldfail"),
|
||||||
pytest.raises(AuthenticationError),
|
pytest.raises(AuthenticationError),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
ids=("client", "blank", "kasa_setup", "shouldfail"),
|
ids=("client", "blank", "kasa_setup", "account_kasa_setup", "shouldfail"),
|
||||||
)
|
)
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
("transport_class", "seed_auth_hash_calc"),
|
("transport_class", "seed_auth_hash_calc"),
|
||||||
@@ -520,9 +522,67 @@ async def test_handshake1(
|
|||||||
assert local_seed == client_seed
|
assert local_seed == client_seed
|
||||||
assert device_remote_seed == server_seed
|
assert device_remote_seed == server_seed
|
||||||
assert device_auth_hash == auth_hash
|
assert device_auth_hash == auth_hash
|
||||||
|
# Of the fallbacks, only the account e-mail with the setup password
|
||||||
|
# becomes the credentials hash
|
||||||
|
expected_hash = (
|
||||||
|
device_auth_hash
|
||||||
|
if device_credentials == Credentials("foo", "kasaSetup")
|
||||||
|
else transport_class.generate_auth_hash(client_credentials)
|
||||||
|
)
|
||||||
|
assert transport.credentials_hash == base64.b64encode(expected_hash).decode()
|
||||||
await protocol.close()
|
await protocol.close()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("transport_class", "seed_auth_hash_calc"),
|
||||||
|
[
|
||||||
|
pytest.param(KlapTransport, lambda c, s, a: c + a, id="KLAP"),
|
||||||
|
pytest.param(KlapTransportV2, lambda c, s, a: c + s + a, id="KLAPV2"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
async def test_handshake1_account_setup_password_is_kept(
|
||||||
|
mocker: MockerFixture,
|
||||||
|
transport_class: type[KlapTransport],
|
||||||
|
seed_auth_hash_calc: Callable[..., bytes],
|
||||||
|
) -> None:
|
||||||
|
"""The account e-mail, as the Kasa app sends it, with the setup password.
|
||||||
|
|
||||||
|
Its hash becomes the credentials hash, so that a config stored with only
|
||||||
|
the hash logs in again.
|
||||||
|
"""
|
||||||
|
server_seed = secrets.token_bytes(16)
|
||||||
|
device_auth_hash = transport_class.generate_auth_hash(
|
||||||
|
Credentials("user@example.com", "kasaSetup")
|
||||||
|
)
|
||||||
|
|
||||||
|
async def _return_handshake1_response(url, params=None, data=None, *_, **__):
|
||||||
|
seed_auth_hash = _sha256(
|
||||||
|
seed_auth_hash_calc(data, server_seed, device_auth_hash)
|
||||||
|
)
|
||||||
|
return _mock_response(200, server_seed + seed_auth_hash)
|
||||||
|
|
||||||
|
mocker.patch.object(
|
||||||
|
aiohttp.ClientSession, "post", side_effect=_return_handshake1_response
|
||||||
|
)
|
||||||
|
|
||||||
|
credentials = Credentials(" User@Example.com", "account-password")
|
||||||
|
transport = transport_class(
|
||||||
|
config=DeviceConfig("127.0.0.1", credentials=credentials)
|
||||||
|
)
|
||||||
|
*_, auth_hash = await transport.perform_handshake1()
|
||||||
|
assert auth_hash == device_auth_hash
|
||||||
|
credentials_hash = transport.credentials_hash
|
||||||
|
assert credentials_hash == base64.b64encode(device_auth_hash).decode()
|
||||||
|
await transport.close()
|
||||||
|
|
||||||
|
stored = transport_class(
|
||||||
|
config=DeviceConfig("127.0.0.1", credentials_hash=credentials_hash)
|
||||||
|
)
|
||||||
|
*_, auth_hash = await stored.perform_handshake1()
|
||||||
|
assert auth_hash == device_auth_hash
|
||||||
|
await stored.close()
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
("transport_class", "seed_auth_hash_calc1", "seed_auth_hash_calc2"),
|
("transport_class", "seed_auth_hash_calc1", "seed_auth_hash_calc2"),
|
||||||
[
|
[
|
||||||
|
|||||||
Reference in New Issue
Block a user