Connect remotely to Home Assistant on Raspberry in complete safety

8 minutes of reading
PURPOSES OF THE GUIDE:
  • Supply to proprio Home Assistant (installed on Raspberry Pi) the highest possible degree of security for remote connection via the Internet (the guide for HASSIO and instead here)
  • Difficulty level: medium / high
CONCEPTS FACED:
  • Software installation and configuration
  • Modem / router configuration
USED ​​SOFTWARE COMPONENTS:
Prerequisites:
  • Home Assistant configured and working
  • Raspberry Pi configured with fixed IP within the proyour home network and reach the Internet
PHYSICAL DEVICES USED:
GUIDE more indicated for:

All environments

Notes and disclaimer
  • qualsiasi modifica all'impianto elettrico dev'essere progettata ed effettuata da personale qualificato;
  • any changes implemented in probefore is a propersonal responsibility as well as a profirst risk and danger (the contents of the present page are purely educational);
  • any changes implemented in proprior to a device it voids the guarantee, quality approvals and certifications.
Driving review: 3.8
CAUTION: this guide is dedicated to users who have installed Home Assistant How appLicense on Raspberry /Windows/Mac or other operational realities. Users HASSIO must instead refer to theadd-on "DuckDNS" illustrated in this other guide.

Abstract

As explained during an episode of our podcast, security in the domotic environment it's never too much. It is not - too much - never in absolute, but when we run the risk of exposing our domotic components to potential criminals (not bad when it comes to thelumination, it is worse when it comes to alarms, locks or other) it is necessary to have a system that is as safe as possible.

For those who have wisely decided to adopt thepersonale HUB Home Assistant, one of the most important rocks to face is to make it reachable from the outside of the propious home automation environment.

Home Assistant offers the possibility of inhibiting access by use of a single password rather than true management e prowith utilities (starting from the 0.77 version - August '18). What remains uncovered (basic) is the use of cryptography for data transmission, which if implemented protects us against any unsafe networks in which someone "listening" could intercept the data in transit, login credentials included.

Encryption has been active for some time the guide offered by Home Assistant community, which however presents various proproblems:

  • uses the official certbot client, which is very heavy and offers a series of features that ultimately do not serve us in this area;
  • requires that the 80 port is not in use at the time of cryptographic certificate refresh;
  • requires that the 80 port is configured in forwarding to the instance Home Assistant in addition to the canonical 8123.

Andrea Gohn has assembled one procedura which uses:

  • a very light script to generate certificates called "dehydrated";
  • the DNS-01 challenges

together with the usual services of DDNS (DuckDNS) and of issuing certificates free (Let's Encrypt).

Nb Users HASSIO: to connect securely to Home Assistant in distribution HASSIO la procedura is extremely simpler: in fact it is sufficient install and configure theadd-on Duck DNS. This guide is not appyour type of installation.

In this guide we summarize the operational steps to equip your installation with Home Assistant su Raspberry Pi (not the dedicated one HASSIO) cryptographic SSL support and an automatic certificate renewal mechanism that does not present i proproblems mentioned above.

Nb We recommend, before proto give in, to read carefully the page dedicated to the concept and functionnameof the "remote control”In home automation.

It starts

assumptions

The entire guide is based on the assumption that the installation of Home Assistant has been carried out on Raspbian in the Python virtual environment as per our guide (or similar). For users HASSIOinstead, the correct driving it's this one.

It is therefore assumed that the user is dedicated to the service Home Assistant be ithomeassistant"And that the installation of theHUB is present at the path "/home/homeassistant/.homeassistant"

Configure DuckDNS

So that your network can be reached from the outside must have a unique name (FQDN) which sees the IP correspond automatically updated with each change, since the one assigned to your modem / router changes cyclically. To do this, the service intervenes Dynamic DNS (or DDNS), or a service that keeps track of the last change and responds, to systems that request the resolution (translation) of the DNS name, the last known IP, ie the current one.

DuckDNS is the service we have chosen for this function.

Then connect to the service via the address https://www.duckdns.org and, once registered, create a profirst domain that, univocally, rappwill reset your router connected to the Internet.

For this guide, we will assume that you have created the following FQDN:

casamia.duckdns.org

where is it "duckdns.org"Is the fixed part while"Casamia" and the domain name created by us as an example.

Inside your private section of DuckDNS you will also find an important camp called "token", who appare analogous to this:

e3ff465f-c6d6-acb1-4416-44b2af152111

Appgrease it on one side, it will be useful soon.

Configure the "duckdns" component

Now you need to implement on Home Assistant an element that, in the face of the change of the Internet IP of the profirst modem / router, communicate this change to DuckDNS, in order to update the FQDN resolution.

To do this, simply add to the file configuration.yaml di Home Assistant the following code:

duckdns:

  domain: casamia

  access_token: il-tuo-token-duckdns

where:

domaindomain name defined on the DuckDNS service
access_tokentoker defined by DuckDNS

Once this configuration has been entered, it is re-launched Home Assistant, DuckDNS will know in real time the IP of your modem / router, and with it, you and who will query this FQDN.

This however is valid One-off, or when Home Assistant starts. To ensure that the IP is always up to date - in case of changes over time - it is necessary to implement a small one proprocess explained in detail in this guide.

Enable port forwarding on the router

To access, from the external network, to ours Home Assistant it is now necessary to configure the modem / router so that any external call to the port (8123, or other) be shot directly to the static Raspberry IP on the 8123 port, or that of Home Assistant.

To carry out the port forwarding configuration activity we recommend reading this article of the excellent Aranzulla; the necessary data appThis guide is:

  • Destination IP: Static IP of the Raspberry Pi (previously assigned);
  • External door: 8123 (unless you want to use another one, it's the same);
  • Internal door: 8123

Identify now, at Home Assistant, the pre-existing configuration relating to the "http" block by the configuration.yaml and configure it (taking care to replace "Casamia" with the profirst domain) as follows:

http:

  base_url: casamia.duckdns.org:8123

Save e restart Home Assistant.

At this point (configured) cconnecting from outside the network Wi-Fi (via browser or via theapp mobile of Home Assistant for iOS or Android) at:

http://casamia.duckdns.org:8123

(obviously replacing "Casamia"With your previously defined domain) dovrebbe appto file our application for Home Assistant.

Nb. If the "External door" field has been modified by the recommended 8123 port, the address must change in relation to this change.

Install and configure "dehydrated"

Once connected via SSH to the Raspberry Pi, change the user in use to "homeassistant":

sudo su -s /bin/bash homeassistant

then log in to the path dedicated to Home Assistant:

cd /home/homeassistant

and execute:

git clone https://github.com/lukas2511/dehydrated.git

in order to clone the "dehydrated" script from Git into the pathhub.
Enter the script path now appena created and create a new file, “domains.txt"

cd dehydrated
/
nano domains.txt

and copy-paste the following text:

casamia.duckdns.org

where "casamia" should be replaced with profirst domain. Exit and save with CTRL + X / Y / enter.

Now create a new file "config"

nano config

and copy-paste the following text:

# Which challenge should be used? Currently http-01 and dns-01 are supported
CHALLENGETYPE="dns-01"

# Script to execute the DNS challenge and run after cert generation
HOOK="${BASEDIR}/hook.sh"

and exit by saving with CTRL + X / Y / enter.

Now create the file hook.sh:

nano hook.sh

and copy-paste the following text:

#!/usr/bin/env bash
set -e
set -u
set -o pipefail
 
domain="myhome"
token="your-duckdns-token"
 
case "$1" in
    "deploy_challenge")
        curl "https://www.duckdns.org/update?domains=$domain&token=$token&txt=$4"
        echo
        ;;
    "clean_challenge")
        curl "https://www.duckdns.org/update?domains=$domain&token=$token&txt=removed&clear=true"
        echo
        ;;
    "deploy_cert")
        sudo systemctl restart home-assistant@homeassistant.service
        ;;
    "unchanged_cert")
        ;;
    "startup_hook")
        ;;
    "exit_hook")
        ;;
    *)
        echo Unknown hook "${1}"
        exit 0
        ;;
esac

taking care to replace field valuations "domain" and "token”With the data already seen during the DuckDNS configuration up Home Assistant (personal domain name and token).

Finally exit by saving with CTRL + X / Y / enter.

We now render the script "hook.sh" appena created executable:

chmod 0777 hook.sh

Generate the certificate with the command:

./dehydrated --register  --accept-terms

which will report an output similar to this:

# INFO: Using main config file /home/homeassistant/dehydrated/config
+ Generating account key...
+ Registering account key with ACME server...
+ Fetching account ID...
+ Done!

Then execute the following command:

./dehydrated -c

which will report an output similar to this:

# INFO: Using main config file /home/homeassistant/dehydrated/config

Processing myhome.duckdns.org

+ Signing domains...

+ Generating private key...

+ Generating signing request...

+ Requesting challenge for myhome.duckdns.org...
OK

+ Responding to challenge for myhome.duckdns.org...
OK

+ Challenge is valid!
 + Requesting certificate...

+ Checking certificate...

+ Done!

+ Creating fullchain.pem...

+ Walking chain...

+ Done!

Nb. In case at the end of this execution it is requested the password of the user in use, interrupt with CTRL + C. The execution is however correct.

Automate certificate renewal

Since the cryptographic certificate has a limited duration, we will now configure a proI request that more be requestednameautomatic every first day of the month.

To execute:

export VISUAL=nano; crontab -e

if asked which editor to use, we recommend using "nano".

Then add to the configuration crontab the following entry:

0 1 1 * * /home/homeassistant/dehydrated/dehydrated -c

save and exit.
This configuration will do that the certificate is automatically renewed every first month.

Finally, get out of user impersonation homeassistant with:

exit

Reconfigure Home Assistant

At this point the cryptography entry in the configuration.yaml file must be added.

Identify the pre-existing configuration relating to the "http" block and configure it (taking care to replace "Casamia" with the profirst domain) as follows:

http:

  ssl_certificate: /home/homeassistant/dehydrated/certs/casamia.duckdns.org/fullchain.pem

  ssl_key: /home/homeassistant/dehydrated/certs/casamia.duckdns.org/privkey.pem

  base_url: casamia.duckdns.org:8123

where

ssl_certificateis the certificate appena created
ssl_keyare the keys appena create
base_url is the address to point to to access your instance of Home Assistant (attention to correctly adjusting the FQDN)

Once restarted Home Assistant, both from the outside and from the inside, via the address

https://casamia.duckdns.org:8123

(obviously replacing "casamia" with your previously defined domain) dovrebbe appto file our application for Home Assistant.

Nb. If the "External door" field has been modified by the recommended 8123 port, the address must change in relation to this change.

Now yours Home Assistant it is remotely controllable safely.

Check the certificate expiration

It is also possible to check at the frontend the duration of the certificate in use through a specific sensor, as follows:

sensor:
  - platform: command_line
    name: Scadenza certificato SSL
    #12 ore indicato in secondi
    scan_interval: 43200
    command: "/usr/bin/sudo ssl-cert-check -b -c /home/homeassistant/dehydrated/certs/my_domain.duckdns.org/cert.pem | awk '{ print $NF }'"

Obviously you will need to customize the string "my_domain" with the profirst name domain.

For this sensor to work it is necessary that ssh-cert-check is installed.
In case it is absent, install it via the command:

sudo apt-get install ssl-cert-check

It is also necessary execute the following command:

sudo visudo

e appurare that the following line exists (otherwise, add it) in the file that apparirà:

homeassistant ALL=(ALL) NOPASSWD:ALL

Then save, exit and restart.

Update Searchnameautomatic

It may happen that the WAN IP assigned to the router you change and that the greaternamento not received by DuckDNS, as such such an updatenameis carried out only when starting Home Assistant, based on what has been achieved through this guide so far.

We therefore recommend following the following guide to configure the Raspbian operating system so that, cyclically, send an updatenameof the IP to DuckDNS:

Automatically update DuckDNS from profirst Raspberry

Local connection

When you are at home - then connect to the Wi-Fi/ Home LAN - you can connect to Home Assistant without having to necessarily use external FQDN address, but directly pointing at mDNS "Raspberry.local" or to the IP address of the Raspberry. The only necessary care will be to use the proSSL protocol.

In essence, instead of using:

https://casamia.duckdns.org:8123

it will be possible to use the address (if activated themDNS):

https://raspberry.local:8123

or, more simply:

https://IP_DEL_RASPBERRY:8123

where obviously "IP_DEL_RASPBERRY”Will be the IP address assigned to the profirst Raspberry IP and already used for the portforwarding at the router.


Home Assistant Official LogoATTENZIONE: remember that there is on our FORUM community an ad hoc section dedicated to Home Assistant, for any doubt, question, information on the specific merit of these components.