Skip to content
Draft
Show file tree
Hide file tree
Changes from 6 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
90 changes: 79 additions & 11 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,78 @@
)


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)

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) -> str:
"""Return the translation key for a failed TLS handshake."""
_LOGGER.debug("TLS connection to printer failed: %s", err.reason, exc_info=err)
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()

printer = await ipp.printer()

return {CONF_SERIAL: printer.info.serial, CONF_UUID: printer.info.uuid}
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.
"""
legacy_tls = False
try:
printer = await _async_get_printer(hass, data, legacy_tls)
except IPPConnectionTLSError as err:
if _tls_reason_key(err.reason) != "tls_unsupported":
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,
}


class IPPFlowHandler(ConfigFlow, domain=DOMAIN):
Expand All @@ -86,6 +141,8 @@ 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)})
except IPPConnectionError, IPPResponseError:
_LOGGER.debug("IPP Connection/Response Error", exc_info=True)
return self._show_setup_form({"base": "cannot_connect"})
Expand All @@ -98,6 +155,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 Down Expand Up @@ -155,6 +213,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 +227,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 @@ -229,6 +291,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)
except IPPConnectionError, IPPResponseError:
_LOGGER.debug("IPP Connection/Response Error", exc_info=True)
errors["base"] = "cannot_connect"
Expand All @@ -242,7 +306,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 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."]
}
10 changes: 9 additions & 1 deletion homeassistant/components/ipp/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,21 @@
"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%]"
},
"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