Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
140 changes: 128 additions & 12 deletions homeassistant/components/ipp/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@
from pyipp import (
IPP,
IPPConnectionError,
IPPConnectionTLSError,
IPPConnectionUpgradeRequired,
IPPError,
IPPParseError,
IPPResponseError,
IPPVersionNotSupportedError,
Printer,
)

from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
Expand All @@ -28,8 +30,8 @@
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo

from .const import CONF_BASE_PATH, CONF_SERIAL, DOMAIN, REQUEST_TIMEOUT
from .coordinator import IPPConfigEntry
from .const import CONF_BASE_PATH, CONF_LEGACY_TLS, CONF_SERIAL, DOMAIN, REQUEST_TIMEOUT
from .coordinator import IPPConfigEntry, ipp_ssl_context

_LOGGER = logging.getLogger(__name__)

Expand All @@ -44,25 +46,101 @@
)


async def validate_input(hass: HomeAssistant, data: dict) -> dict[str, Any]:
"""Validate the user input allows us to connect.
# OpenSSL reasons with a more specific message than "tls_error".
_TLS_ERROR_KEYS = (
("CERTIFICATE_VERIFY_FAILED", "tls_certificate"),
("WRONG_VERSION_NUMBER", "tls_not_offered"),
("RECORD_LAYER_FAILURE", "tls_not_offered"),
("PACKET_LENGTH_TOO_LONG", "tls_not_offered"),
("HANDSHAKE_FAILURE", "tls_unsupported"),
("PROTOCOL_VERSION", "tls_unsupported"),
("INSUFFICIENT_SECURITY", "tls_unsupported"),
("NO_PROTOCOLS_AVAILABLE", "tls_unsupported"),
("UNSUPPORTED_PROTOCOL", "tls_unsupported"),
("NO_CIPHERS_AVAILABLE", "tls_unsupported"),
Comment thread
Copilot marked this conversation as resolved.
Resolved
)

Data has the keys from DATA_SCHEMA with values provided by the user.
"""
session = async_get_clientsession(hass)

# Failures the older cipher suites can fix. The intermediate profile does not
# allow older TLS versions, so protocol version failures are not among them.
_LEGACY_CIPHER_REASONS = (
"HANDSHAKE_FAILURE",
"INSUFFICIENT_SECURITY",
"NO_CIPHERS_AVAILABLE",
)


def _legacy_ciphers_may_help(reason: str) -> bool:
"""Return whether the older cipher suites may fix a failed handshake."""
return any(code in reason for code in _LEGACY_CIPHER_REASONS)


def _tls_reason_key(reason: str) -> str:
"""Return the translation key for an OpenSSL failure reason."""
for code, key in _TLS_ERROR_KEYS:
if code in reason:
return key
return "tls_error"


def _tls_error_key(err: IPPConnectionTLSError, verify_ssl: bool = False) -> str:
"""Return the translation key for a failed TLS handshake."""
_LOGGER.debug("TLS connection to printer failed: %s", err.reason, exc_info=err)
if verify_ssl and _legacy_ciphers_may_help(err.reason):
# The older cipher suites are only tried without verification
return "tls_unsupported_verify_ssl"
return _tls_reason_key(err.reason)


async def _async_get_printer(
hass: HomeAssistant, data: dict, legacy_tls: bool
) -> Printer:
"""Connect to the printer and return its attributes."""
ipp = IPP(
host=data[CONF_HOST],
port=data[CONF_PORT],
base_path=data[CONF_BASE_PATH],
tls=data[CONF_SSL],
verify_ssl=data[CONF_VERIFY_SSL],
session=session,
ssl_context=ipp_ssl_context(data[CONF_VERIFY_SSL], legacy_tls),
session=async_get_clientsession(hass),
request_timeout=REQUEST_TIMEOUT,
)
return await ipp.printer()


async def validate_input(hass: HomeAssistant, data: dict) -> dict[str, Any]:
"""Validate the user input allows us to connect.

Data has the keys from DATA_SCHEMA with values provided by the user. A
printer that rejects the TLS handshake is tried again with the older cipher
suites of the intermediate profile, but only without certificate
verification. With it, a forged handshake failure could otherwise make us
store a weaker profile for a printer that does not need it.
"""
legacy_tls = False
try:
printer = await _async_get_printer(hass, data, legacy_tls)
except IPPConnectionTLSError as err:
if data[CONF_VERIFY_SSL] or not _legacy_ciphers_may_help(err.reason):
raise
_LOGGER.debug(
"Printer rejected the TLS handshake (%s), retrying with older cipher"
" suites",
err.reason,
)
legacy_tls = True
printer = await _async_get_printer(hass, data, legacy_tls)
Comment thread
brianegge marked this conversation as resolved.
Resolved

return {
CONF_SERIAL: printer.info.serial,
CONF_UUID: printer.info.uuid,
CONF_LEGACY_TLS: legacy_tls,
}

printer = await ipp.printer()

return {CONF_SERIAL: printer.info.serial, CONF_UUID: printer.info.uuid}
# Connection settings a stored entry must share with the validated endpoint
_CONNECTION_KEYS = (CONF_PORT, CONF_BASE_PATH, CONF_SSL, CONF_VERIFY_SSL)


class IPPFlowHandler(ConfigFlow, domain=DOMAIN):
Expand All @@ -86,6 +164,10 @@ async def async_step_user(
info = await validate_input(self.hass, user_input)
except IPPConnectionUpgradeRequired:
return self._show_setup_form({"base": "connection_upgrade"})
except IPPConnectionTLSError as err:
return self._show_setup_form(
{"base": _tls_error_key(err, user_input[CONF_VERIFY_SSL])}
)
except IPPConnectionError, IPPResponseError:
_LOGGER.debug("IPP Connection/Response Error", exc_info=True)
return self._show_setup_form({"base": "cannot_connect"})
Expand All @@ -98,6 +180,7 @@ async def async_step_user(
_LOGGER.debug("IPP Error", exc_info=True)
return self.async_abort(reason="ipp_error")

user_input[CONF_LEGACY_TLS] = info[CONF_LEGACY_TLS]
Comment thread
brianegge marked this conversation as resolved.
Resolved
unique_id = user_input[CONF_UUID] = info[CONF_UUID]

if not unique_id and info[CONF_SERIAL]:
Expand All @@ -110,7 +193,12 @@ async def async_step_user(
_LOGGER.debug("Unable to determine unique id from IPP response")

await self.async_set_unique_id(unique_id)
self._abort_if_unique_id_configured(updates={CONF_HOST: user_input[CONF_HOST]})
self._abort_if_unique_id_configured(
updates={
CONF_HOST: user_input[CONF_HOST],
**self._legacy_tls_update(user_input),
}
)

return self.async_create_entry(title=user_input[CONF_HOST], data=user_input)

Expand Down Expand Up @@ -155,6 +243,8 @@ async def async_step_zeroconf(
info = await validate_input(self.hass, self.discovery_info)
except IPPConnectionUpgradeRequired:
return self.async_abort(reason="connection_upgrade")
except IPPConnectionTLSError as err:
return self.async_abort(reason=_tls_error_key(err))
except IPPConnectionError, IPPResponseError:
_LOGGER.debug("IPP Connection/Response Error", exc_info=True)
return self.async_abort(reason="cannot_connect")
Expand All @@ -167,6 +257,8 @@ async def async_step_zeroconf(
_LOGGER.debug("IPP Error", exc_info=True)
return self.async_abort(reason="ipp_error")

self.discovery_info[CONF_LEGACY_TLS] = info[CONF_LEGACY_TLS]

if not unique_id and info[CONF_UUID]:
_LOGGER.debug(
"Printer UUID is missing from discovery info. Falling back to IPP UUID"
Expand Down Expand Up @@ -198,6 +290,7 @@ async def _async_set_unique_id_and_abort_if_already_configured(
updates={
CONF_HOST: self.discovery_info[CONF_HOST],
CONF_NAME: self.discovery_info[CONF_NAME],
**self._legacy_tls_update(self.discovery_info),
},
)

Expand Down Expand Up @@ -229,6 +322,8 @@ async def async_step_reconfigure(
info = await validate_input(self.hass, user_input)
except IPPConnectionUpgradeRequired:
errors["base"] = "connection_upgrade"
except IPPConnectionTLSError as err:
errors["base"] = _tls_error_key(err, user_input[CONF_VERIFY_SSL])
except IPPConnectionError, IPPResponseError:
_LOGGER.debug("IPP Connection/Response Error", exc_info=True)
errors["base"] = "cannot_connect"
Expand All @@ -242,7 +337,11 @@ async def async_step_reconfigure(
return self.async_abort(reason="different_device")
return self.async_update_reload_and_abort(
reconfigure_entry,
data_updates={**user_input, CONF_UUID: info[CONF_UUID]},
data_updates={
**user_input,
CONF_UUID: info[CONF_UUID],
CONF_LEGACY_TLS: info[CONF_LEGACY_TLS],
},
)

return self.async_show_form(
Expand All @@ -253,6 +352,23 @@ async def async_step_reconfigure(
errors=errors,
)

def _legacy_tls_update(self, data: dict[str, Any]) -> dict[str, bool]:
"""Return the update that keeps a configured printer reachable.

Only applies to an entry with the connection settings that were
validated, and only ever turns the older cipher suites on.
"""
if not data.get(CONF_LEGACY_TLS) or self.unique_id is None:
return {}
entry = self.hass.config_entries.async_entry_for_domain_unique_id(
DOMAIN, self.unique_id
)
if entry is None or any(
entry.data.get(key) != data[key] for key in _CONNECTION_KEYS
):
return {}
return {CONF_LEGACY_TLS: True}

def _is_same_printer(self, entry: IPPConfigEntry, info: dict[str, Any]) -> bool:
"""Return whether the printer info belongs to the config entry."""
if entry.unique_id == (info[CONF_UUID] or info[CONF_SERIAL]):
Expand Down
2 changes: 2 additions & 0 deletions homeassistant/components/ipp/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,7 @@

# Config Keys
CONF_BASE_PATH = "base_path"
# The printer needs the older cipher suites of the intermediate TLS profile
CONF_LEGACY_TLS = "legacy_tls"
CONF_SERIAL = "serial"
CONF_TLS = "tls"
29 changes: 28 additions & 1 deletion homeassistant/components/ipp/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from datetime import timedelta
import logging
from ssl import SSLContext
from typing import override

from pyipp import IPP, IPPConnectionError, IPPError, Printer as IPPPrinter
Expand All @@ -15,8 +16,14 @@
UpdateFailed,
UpdateFailedUnreachable,
)
from homeassistant.util.ssl import (
SSL_ALPN_HTTP11,
SSLCipherList,
client_context,
client_context_no_verify,
)

from .const import CONF_BASE_PATH, DOMAIN, REQUEST_TIMEOUT
from .const import CONF_BASE_PATH, CONF_LEGACY_TLS, DOMAIN, REQUEST_TIMEOUT

SCAN_INTERVAL = timedelta(seconds=60)

Expand All @@ -25,6 +32,22 @@
type IPPConfigEntry = ConfigEntry[IPPDataUpdateCoordinator]


def ipp_ssl_context(verify_ssl: bool, legacy_tls: bool) -> SSLContext | None:
"""Return the SSL context for talking to a printer over IPPS.

Some printers only offer TLS_RSA_* cipher suites, which Python's default
client context leaves out. For those, use the intermediate profile, which
still prefers ECDHE suites but falls back to them. Other printers keep the
default context, so a printer that prefers static RSA keeps forward
secrecy.
"""
if not legacy_tls:
return None
if verify_ssl:
return client_context(SSLCipherList.INTERMEDIATE, SSL_ALPN_HTTP11)
return client_context_no_verify(SSLCipherList.INTERMEDIATE, SSL_ALPN_HTTP11)


class IPPDataUpdateCoordinator(DataUpdateCoordinator[IPPPrinter]):
"""Class to manage fetching IPP data from single endpoint."""

Expand All @@ -39,6 +62,10 @@ def __init__(self, hass: HomeAssistant, config_entry: IPPConfigEntry) -> None:
base_path=config_entry.data[CONF_BASE_PATH],
tls=config_entry.data[CONF_SSL],
verify_ssl=config_entry.data[CONF_VERIFY_SSL],
ssl_context=ipp_ssl_context(
config_entry.data[CONF_VERIFY_SSL],
config_entry.data.get(CONF_LEGACY_TLS, False),
),
session=async_get_clientsession(hass, config_entry.data[CONF_VERIFY_SSL]),
request_timeout=REQUEST_TIMEOUT,
)
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/ipp/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@
"integration_type": "device",
"iot_class": "local_polling",
"loggers": ["deepmerge", "pyipp"],
"requirements": ["aioipp==0.21.2"],
"requirements": ["aioipp==0.22.0"],
Comment thread
brianegge marked this conversation as resolved.
Resolved
Comment thread
Copilot marked this conversation as resolved.
Resolved
"zeroconf": ["_ipps._tcp.local.", "_ipp._tcp.local."]
}
11 changes: 10 additions & 1 deletion homeassistant/components/ipp/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,22 @@
"ipp_error": "Encountered IPP error.",
"ipp_version_error": "IPP version not supported by printer.",
"parse_error": "Failed to parse response from printer.",
"tls_certificate": "The printer's certificate could not be verified.",
"tls_error": "The secure (TLS) connection to the printer failed.",
"tls_not_offered": "The printer did not answer with TLS on the discovered port.",
"tls_unsupported": "The printer rejected the secure connection. It may not support any of the TLS versions or cipher suites that Home Assistant offers.",
"unique_id_required": "Device missing unique identification required for discovery."
},
"error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
"connection_upgrade": "Failed to connect to printer. Please try again with SSL/TLS option checked.",
"ipp_error": "[%key:component::ipp::config::abort::ipp_error%]",
"ipp_version_error": "[%key:component::ipp::config::abort::ipp_version_error%]"
"ipp_version_error": "[%key:component::ipp::config::abort::ipp_version_error%]",
"tls_certificate": "The printer's certificate could not be verified. If the printer uses a self-signed certificate, uncheck the option to verify the SSL certificate.",
"tls_error": "[%key:component::ipp::config::abort::tls_error%]",
"tls_not_offered": "The printer did not answer with TLS on this port. Uncheck the SSL/TLS option, or check the port.",
"tls_unsupported": "[%key:component::ipp::config::abort::tls_unsupported%]",
"tls_unsupported_verify_ssl": "The printer rejected the secure connection. If it only supports older TLS cipher suites, uncheck the option to verify the SSL certificate to set it up."
},
"flow_title": "{name}",
"step": {
Expand Down
2 changes: 1 addition & 1 deletion requirements_all.txt

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading