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:
ZeliardM
2026-11-23 11:59:18 -05:00
committed by GitHub
parent 7a5b3a2658
commit 347ce1ba9b
2 changed files with 98 additions and 41 deletions

View File

@@ -117,8 +117,6 @@ class KlapTransport(BaseTransport):
self._local_auth_owner = self.generate_owner_hash(self._credentials).hex()
else:
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._query_lock = asyncio.Lock()
self._handshake_done: bool = False
@@ -230,48 +228,21 @@ class KlapTransport(BaseTransport):
_LOGGER.debug("handshake1 hashes match with expected credentials")
return local_seed, remote_seed, self._local_auth_hash # type: ignore
# Now check against the default setup credentials
for key, value in DEFAULT_CREDENTIALS.items():
if key not in self._default_credentials_auth_hash:
default_credentials = get_default_credentials(value)
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(
"Device response did not match our expected hash on ip %s,"
"but an authentication with %s default credentials worked",
self._host,
key,
)
return local_seed, remote_seed, self._default_credentials_auth_hash[key] # type: ignore
# Finally check against blank credentials if not already blank
blank_creds = Credentials()
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:
for description, auth_hash, save_hash in self._fallback_auth_hashes():
if (
self.handshake1_seed_auth_hash(local_seed, remote_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",
"but %s worked",
self._host,
description,
)
return local_seed, remote_seed, self._blank_auth_hash # type: ignore
if save_hash:
# A stored hash has no e-mail to rebuild this one from
self._local_auth_hash = auth_hash
return local_seed, remote_seed, auth_hash
msg = (
f"Device response did not match our challenge on ip {self._host}, "
@@ -280,6 +251,32 @@ class KlapTransport(BaseTransport):
_LOGGER.debug(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(
self, local_seed: bytes, remote_seed: bytes, auth_hash: bytes
) -> KlapEncryptionSession:

View File

@@ -1,5 +1,6 @@
from __future__ import annotations
import base64
import json
import logging
import re
@@ -467,12 +468,13 @@ async def test_protocol_invalid_response(
get_default_credentials(DEFAULT_CREDENTIALS["KASA"]),
does_not_raise(),
),
(Credentials("foo", "kasaSetup"), does_not_raise()),
(
Credentials("shouldfail", "shouldfail"),
pytest.raises(AuthenticationError),
),
],
ids=("client", "blank", "kasa_setup", "shouldfail"),
ids=("client", "blank", "kasa_setup", "account_kasa_setup", "shouldfail"),
)
@pytest.mark.parametrize(
("transport_class", "seed_auth_hash_calc"),
@@ -520,9 +522,67 @@ async def test_handshake1(
assert local_seed == client_seed
assert device_remote_seed == server_seed
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()
@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(
("transport_class", "seed_auth_hash_calc1", "seed_auth_hash_calc2"),
[