Skip to content

Make cert_expiry work with self-signed / private CA signed certificates #137452

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 14 commits into
base: dev
Choose a base branch
from

Conversation

cromefire
Copy link

@cromefire cromefire commented Feb 5, 2025

Breaking change

Not 100% sure. If people relied on this for checking the cert chain it'd break, but that wasn't the mission of this extension, so IMO this should be fine.

Proposed change

Removes the validation of the certifivate

Type of change

  • Dependency upgrade
  • Bugfix (non-breaking change which fixes an issue)
  • New integration (thank you!)
  • New feature (which adds functionality to an existing integration)
  • Deprecation (breaking change to happen in the future)
  • Breaking change (fix/feature causing existing functionality to break)
  • Code quality improvements to existing code or addition of tests

Additional information

Checklist

  • The code change is tested and works locally.
  • Local tests pass. Your PR cannot be merged unless tests pass - Some tests (in other integrations) are not working, but nothing was changed, dependencies are missing from the requirement files it seems.
  • There is no commented out code in this PR.
  • I have followed the development checklist
  • I have followed the perfect PR recommendations
  • The code has been formatted using Ruff (ruff format homeassistant tests)
  • Tests have been added to verify that the new code works. - Not really possible in a good way here

If user exposed functionality or configuration variables are added/changed:

If the code communicates with devices, web services, or third-party tools:

  • The manifest file has all fields filled out correctly.
    Updated and included derived files by running: python3 -m script.hassfest.
  • New or updated dependencies have been added to requirements_all.txt.
    Updated by running python3 -m script.gen_requirements_all.
  • For the updated dependencies - a link to the changelog, or at minimum a diff between library versions is added to the PR description.

To help with the load of incoming pull requests:

Copy link

@home-assistant home-assistant bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @cromefire

It seems you haven't yet signed a CLA. Please do so here.

Once you do that we will be able to review and accept this pull request.

Thanks!

@home-assistant
Copy link

home-assistant bot commented Feb 5, 2025

Hey there @jjlawren, mind taking a look at this pull request as it has been labeled with an integration (cert_expiry) you are listed as a code owner for? Thanks!

Code owner commands

Code owners of cert_expiry can trigger bot actions by commenting:

  • @home-assistant close Closes the pull request.
  • @home-assistant rename Awesome new title Renames the pull request.
  • @home-assistant reopen Reopen the pull request.
  • @home-assistant unassign cert_expiry Removes the current integration label and assignees on the pull request, add the integration domain after the command.
  • @home-assistant add-label needs-more-information Add a label (needs-more-information, problem in dependency, problem in custom component) to the pull request.
  • @home-assistant remove-label needs-more-information Remove a label (needs-more-information, problem in dependency, problem in custom component) on the pull request.

@cromefire cromefire changed the title Make certificate_expiry work with self-signed / private CA signed certificates. Make cert_expiry work with self-signed / private CA signed certificates. Feb 5, 2025
@cromefire
Copy link
Author

cromefire commented Feb 5, 2025

So it doesn't seem like the async way can be used, because it just doesn't properly provide the peer certificate, so the stdlib way it is.

Also also the docs on setting everything up properly seem to be somewhat trash, it seems to miss many of the packages required for some tests and so a bunch of tests just fail all the time.

@cromefire cromefire marked this pull request as ready for review February 5, 2025 21:29
@cromefire cromefire requested a review from jjlawren as a code owner February 5, 2025 21:29
@MartinHjelmare MartinHjelmare changed the title Make cert_expiry work with self-signed / private CA signed certificates. Make cert_expiry work with self-signed / private CA signed certificates Feb 23, 2025
@@ -67,7 +66,7 @@ async def async_step_user(
await self.async_set_unique_id(f"{host}:{port}")
self._abort_if_unique_id_configured()

if await self._test_connection(user_input):
if self._test_connection(user_input):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can't just do sync operation in async context; this is blocking the loop now.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The only option I can think of is spawning a background thread and awaiting the result. IIRC from my python days many years ago there is a way in the multiprocessing module to do that with a thread pool of some sort. Would that be acceptable?

I don't suppose I've got any other options here, as the async way it was done before only seems to provide the parsed cert, which is only populated if certificate validation is disabled, which it has to be to fix the issue.

Copy link
Contributor

@PaarthShah PaarthShah Mar 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I left a different comment with the hope of helping keep everything pure async (which would be my own preference), but the homeassistant-standard way of achieving this safely would be to follow this:
https://developers.home-assistant.io/docs/asyncio_working_with_async/#calling-sync-functions-from-async

example from linked page:

# hub.update() is a sync function.
result = await hass.async_add_executor_job(hub.update)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@frenck I wrapped the socket call into hass.async_add_executor_job now, is that acceptable? I will still have to retest, didn't get to that yet, but functionality should be the same.

@home-assistant home-assistant bot marked this pull request as draft March 2, 2025 20:45
@home-assistant
Copy link

home-assistant bot commented Mar 2, 2025

Please take a look at the requested changes, and use the Ready for review button when you are done, thanks 👍

Learn more about our pull request process.

@pergolafabio
Copy link

Guys, while you are working on the PR, can you also change to :

add 2 lines:


        ctx=get_default_context()
        ctx.verify_mode=ssl.CERT_REQUIRED
async def async_get_cert(
    hass: HomeAssistant,
    host: str,
    port: int,
) -> dict[str, Any]:
    """Get the certificate for the host and port combination."""
    async with asyncio.timeout(TIMEOUT):
        ctx=get_default_context()
        ctx.verify_mode=ssl.CERT_REQUIRED
        transport, _ = await hass.loop.create_connection(
            asyncio.Protocol,
            host,
            port,
            ssl=ctx,
            happy_eyeballs_delay=0.25,
            server_hostname=host,
        )
    try:
        return transport.get_extra_info("peercert")  # type: ignore[no-any-return]
    finally:
        transport.close()

this will fix/close issue:
#136634

@cromefire
Copy link
Author

Guys, while you are working on the PR, can you also change to :

No completely sure what you're trying to achieve, but the whole call has changed to:

context = get_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
context.verify_flags = context.verify_flags | ssl.VERIFY_CRL_CHECK_CHAIN

conn = socket.create_connection((host, port), timeout=TIMEOUT)
sock = context.wrap_socket(conn, server_hostname=host)

so I'd ask you to retest once this has landed and see if your issue persists at all.

@cromefire
Copy link
Author

It seems indeed everything is working correctly still, even with the background thread changes:
image
The config flow works as well.

@cromefire cromefire marked this pull request as ready for review March 13, 2025 21:05
@home-assistant home-assistant bot requested a review from frenck March 13, 2025 21:05
@cromefire
Copy link
Author

Okay found one issue, the is valid tag was not working properly because it relied on python to validate the cert before, but now it works again:
image

@Maes152
Copy link

Maes152 commented May 19, 2025

ssl.CERT_REQUIRED

Not sure where the merging of this PR stands, but the code change request specifically targets the following:

context.verify_mode = ssl.CERT_NONE

change to

context.verify_mode = ssl.CERT_REQUIRED

@cromefire
Copy link
Author

ssl.CERT_REQUIRED

Not sure where the merging of this PR stands, but the code change request specifically targets the following:

context.verify_mode = ssl.CERT_NONE

change to

context.verify_mode = ssl.CERT_REQUIRED

It does, otherwise self-signed certs don't work. I'm currently waiting on a review with the changes I made.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Certificate Expiry integration does not handle self signed or personal cert authorities
6 participants