Skip to content

Commit

Permalink
Wireguard component (esphome#4256)
Browse files Browse the repository at this point in the history
Co-authored-by: Jesse Hills <[email protected]>
Co-authored-by: Simone Rossetto <[email protected]>
Co-authored-by: Thomas Bernard <[email protected]>
  • Loading branch information
4 people authored Sep 11, 2023
1 parent d264865 commit b107948
Show file tree
Hide file tree
Showing 11 changed files with 648 additions and 1 deletion.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ jobs:
fail-fast: false
max-parallel: 2
matrix:
file: [1, 2, 3, 3.1, 4, 5, 6, 7, 8]
file: [1, 2, 3, 3.1, 4, 5, 6, 7, 8, 10]
steps:
- name: Check out code from GitHub
uses: actions/checkout@v4
Expand Down
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ __pycache__/
# Intellij Idea
.idea

# Eclipse
.project
.cproject
.pydevproject
.settings/

# Vim
*.swp

Expand Down
1 change: 1 addition & 0 deletions CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,7 @@ esphome/components/web_server_idf/* @dentra
esphome/components/whirlpool/* @glmnet
esphome/components/whynter/* @aeonsablaze
esphome/components/wiegand/* @ssieb
esphome/components/wireguard/* @droscy @lhoracek @thomas0bernard
esphome/components/wl_134/* @hobbypunk90
esphome/components/x9c/* @EtienneMD
esphome/components/xiaomi_lywsd03mmc/* @ahpohl
Expand Down
113 changes: 113 additions & 0 deletions esphome/components/wireguard/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import re
import ipaddress
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.const import (
CONF_ID,
CONF_TIME_ID,
CONF_ADDRESS,
CONF_REBOOT_TIMEOUT,
)
from esphome.components import time

CONF_NETMASK = "netmask"
CONF_PRIVATE_KEY = "private_key"
CONF_PEER_ENDPOINT = "peer_endpoint"
CONF_PEER_PUBLIC_KEY = "peer_public_key"
CONF_PEER_PORT = "peer_port"
CONF_PEER_PRESHARED_KEY = "peer_preshared_key"
CONF_PEER_ALLOWED_IPS = "peer_allowed_ips"
CONF_PEER_PERSISTENT_KEEPALIVE = "peer_persistent_keepalive"
CONF_REQUIRE_CONNECTION_TO_PROCEED = "require_connection_to_proceed"

DEPENDENCIES = ["time", "esp32"]
CODEOWNERS = ["@lhoracek", "@droscy", "@thomas0bernard"]

# The key validation regex has been described by Jason Donenfeld himself
# url: https://lists.zx2c4.com/pipermail/wireguard/2020-December/006222.html
_WG_KEY_REGEX = re.compile(r"^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw480]=$")

wireguard_ns = cg.esphome_ns.namespace("wireguard")
Wireguard = wireguard_ns.class_("Wireguard", cg.Component, cg.PollingComponent)


def _wireguard_key(value):
if _WG_KEY_REGEX.match(cv.string(value)) is not None:
return value
raise cv.Invalid(f"Invalid WireGuard key: {value}")


def _cidr_network(value):
try:
ipaddress.ip_network(value, strict=False)
except ValueError as err:
raise cv.Invalid(f"Invalid network in CIDR notation: {err}")
return value


CONFIG_SCHEMA = cv.Schema(
{
cv.GenerateID(): cv.declare_id(Wireguard),
cv.GenerateID(CONF_TIME_ID): cv.use_id(time.RealTimeClock),
cv.Required(CONF_ADDRESS): cv.ipv4,
cv.Optional(CONF_NETMASK, default="255.255.255.255"): cv.ipv4,
cv.Required(CONF_PRIVATE_KEY): _wireguard_key,
cv.Required(CONF_PEER_ENDPOINT): cv.string,
cv.Required(CONF_PEER_PUBLIC_KEY): _wireguard_key,
cv.Optional(CONF_PEER_PORT, default=51820): cv.port,
cv.Optional(CONF_PEER_PRESHARED_KEY): _wireguard_key,
cv.Optional(CONF_PEER_ALLOWED_IPS, default=["0.0.0.0/0"]): cv.ensure_list(
_cidr_network
),
cv.Optional(CONF_PEER_PERSISTENT_KEEPALIVE, default=0): cv.Any(
cv.positive_time_period_seconds,
cv.uint16_t,
),
cv.Optional(
CONF_REBOOT_TIMEOUT, default="15min"
): cv.positive_time_period_milliseconds,
cv.Optional(CONF_REQUIRE_CONNECTION_TO_PROCEED, default=False): cv.boolean,
}
).extend(cv.polling_component_schema("10s"))


async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])

cg.add(var.set_address(str(config[CONF_ADDRESS])))
cg.add(var.set_netmask(str(config[CONF_NETMASK])))
cg.add(var.set_private_key(config[CONF_PRIVATE_KEY]))
cg.add(var.set_peer_endpoint(config[CONF_PEER_ENDPOINT]))
cg.add(var.set_peer_public_key(config[CONF_PEER_PUBLIC_KEY]))
cg.add(var.set_peer_port(config[CONF_PEER_PORT]))
cg.add(var.set_keepalive(config[CONF_PEER_PERSISTENT_KEEPALIVE]))
cg.add(var.set_reboot_timeout(config[CONF_REBOOT_TIMEOUT]))

if CONF_PEER_PRESHARED_KEY in config:
cg.add(var.set_preshared_key(config[CONF_PEER_PRESHARED_KEY]))

allowed_ips = list(
ipaddress.collapse_addresses(
[
ipaddress.ip_network(ip, strict=False)
for ip in config[CONF_PEER_ALLOWED_IPS]
]
)
)

for ip in allowed_ips:
cg.add(var.add_allowed_ip(str(ip.network_address), str(ip.netmask)))

cg.add(var.set_srctime(await cg.get_variable(config[CONF_TIME_ID])))

if config[CONF_REQUIRE_CONNECTION_TO_PROCEED]:
cg.add(var.disable_auto_proceed())

# This flag is added here because the esp_wireguard library statically
# set the size of its allowed_ips list at compile time using this value;
# the '+1' modifier is relative to the device's own address that will
# be automatically added to the provided list.
cg.add_build_flag(f"-DCONFIG_WIREGUARD_MAX_SRC_IPS={len(allowed_ips) + 1}")
cg.add_library("droscy/esp_wireguard", "0.3.2")

await cg.register_component(var, config)
28 changes: 28 additions & 0 deletions esphome/components/wireguard/binary_sensor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import binary_sensor
from esphome.const import (
CONF_STATUS,
DEVICE_CLASS_CONNECTIVITY,
)

from . import Wireguard

CONF_WIREGUARD_ID = "wireguard_id"

DEPENDENCIES = ["wireguard"]

CONFIG_SCHEMA = {
cv.GenerateID(CONF_WIREGUARD_ID): cv.use_id(Wireguard),
cv.Optional(CONF_STATUS): binary_sensor.binary_sensor_schema(
device_class=DEVICE_CLASS_CONNECTIVITY,
),
}


async def to_code(config):
parent = await cg.get_variable(config[CONF_WIREGUARD_ID])

if status_config := config.get(CONF_STATUS):
sens = await binary_sensor.new_binary_sensor(status_config)
cg.add(parent.set_status_sensor(sens))
30 changes: 30 additions & 0 deletions esphome/components/wireguard/sensor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import sensor
from esphome.const import (
DEVICE_CLASS_TIMESTAMP,
ENTITY_CATEGORY_DIAGNOSTIC,
)

from . import Wireguard

CONF_WIREGUARD_ID = "wireguard_id"
CONF_LATEST_HANDSHAKE = "latest_handshake"

DEPENDENCIES = ["wireguard"]

CONFIG_SCHEMA = {
cv.GenerateID(CONF_WIREGUARD_ID): cv.use_id(Wireguard),
cv.Optional(CONF_LATEST_HANDSHAKE): sensor.sensor_schema(
device_class=DEVICE_CLASS_TIMESTAMP,
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
),
}


async def to_code(config):
parent = await cg.get_variable(config[CONF_WIREGUARD_ID])

if latest_handshake_config := config.get(CONF_LATEST_HANDSHAKE):
sens = await sensor.new_sensor(latest_handshake_config)
cg.add(parent.set_handshake_sensor(sens))
Loading

0 comments on commit b107948

Please sign in to comment.