diff --git a/ldap-auth-server/CHANGELOG.md b/ldap-auth-server/CHANGELOG.md new file mode 100644 index 0000000..7756e33 --- /dev/null +++ b/ldap-auth-server/CHANGELOG.md @@ -0,0 +1,13 @@ + + +# Changelog + +## [Unreleased] + +## 0.1.0 + +### Added + +- Initial release diff --git a/ldap-auth-server/DOCS.md b/ldap-auth-server/DOCS.md new file mode 100644 index 0000000..a8b894c --- /dev/null +++ b/ldap-auth-server/DOCS.md @@ -0,0 +1,62 @@ +# Home Assistant Add-on: LDAP Auth Server + +## How to use + +1. Install the add-on. +2. Configure `LDAP Server URL` and `Bind DN Template` to match your LDAP + server. +3. (Optionally) Configure `Search Base DN` and `Search Filter Template` if you + want to hide some users from Home Assistant. +4. Copy the + [ldap_auth_command.sh](https://github.com/vqvu/home-assistant-addons/ldap-auth-server/ldap_auth_command.sh) + file to your Home Assistant config directory. +5. Add a custom [Command Line authentication + provider](https://www.home-assistant.io/docs/authentication/providers/#command-line) + to your configuration to call that script. + + ```yaml + homeassistant: + auth_providers: + - type: command_line + command: /config/ldap_auth_command.sh + args: + # Provide the hostname of the add-on as the first argument. You can + # the hostname on the add-on's Info page. + - 7860403f-ldap-auth-server + meta: true + # Optionally add the homeassistant provider as a fallback if you're + # concerned about a failed LDAP server locking you out of Home + # Assistant. + # - type: homeassistant + ``` + +## Limitations + +These limitations are current as of Home Assistant v2023.2. + +1. The users created via the `command_line` provider are different from the + ones created via the `homeassistant` provider, even if their usernames are + the same. This means you will lose all user configurations when adopting a + new auth provider. +2. Users created by `command_line` provider are all Administrators, and it is + not possible to change this in the UI. You will need to manually modify the + `group_ids` field of the user in the `/config/.storage/auth` file to be + `system-users`. Example + + ```json + { + "id": "5de09f4cdcdb4d4fa2a39291147803df", + "group_ids": [ + "system-users" + ], + ... + "name": "Non-admin User", + ... + }, + ``` + + Don't forget to restart your Home Assistant afterwards. +3. This add-on is only tested with an [LLDAP + server](https://github.com/nitnelave/lldap), so it is possible (though + probably unlikely) that it doesn't work with other types of LDAP servers for + one reason or another. diff --git a/ldap-auth-server/Dockerfile b/ldap-auth-server/Dockerfile new file mode 100644 index 0000000..16d9e2b --- /dev/null +++ b/ldap-auth-server/Dockerfile @@ -0,0 +1,16 @@ +# # https://developers.home-assistant.io/docs/add-ons/configuration#add-on-dockerfile +ARG BUILD_FROM +FROM $BUILD_FROM AS build + +COPY . /build + +WORKDIR /build + +# Execute during the build of the image +RUN apk add --no-cache go && go build + +FROM $BUILD_FROM + +COPY --from=build /build/ldap-auth-server /usr/bin + +CMD ["/usr/bin/ldap-auth-server", "/data/options.json"] diff --git a/ldap-auth-server/README.md b/ldap-auth-server/README.md new file mode 100644 index 0000000..8da5d31 --- /dev/null +++ b/ldap-auth-server/README.md @@ -0,0 +1,24 @@ +# Home Assistant Add-on: LDAP Authentication Server + +![Supports aarch64 Architecture][aarch64-shield] ![Supports amd64 +Architecture][amd64-shield] ![Supports armhf Architecture][armhf-shield] +![Supports armv7 Architecture][armv7-shield] ![Supports i386 +Architecture][i386-shield] + +This add-on runs a simple HTTP server that can authenticate users against an +LDAP server. It is meant to be used in conjunction with Home Assistant's +[Command Line authentication +provider](https://www.home-assistant.io/docs/authentication/providers/#command-line), +so it only implements the bare minimum functionality to support that. + +This add-on is as an alternative to the shell script at + for containerized Home Assistant +installs. Unlike `ldap-auth-sh`, all LDAP functionality is wrapped in the add-on +and exposed via an HTTP endpoint. That way, only `curl` is needed from within +the Home Assistant container. + +[aarch64-shield]: https://img.shields.io/badge/aarch64-yes-green.svg +[amd64-shield]: https://img.shields.io/badge/amd64-yes-green.svg +[armhf-shield]: https://img.shields.io/badge/armhf-yes-green.svg +[armv7-shield]: https://img.shields.io/badge/armv7-yes-green.svg +[i386-shield]: https://img.shields.io/badge/i386-yes-green.svg diff --git a/ldap-auth-server/apparmor.txt b/ldap-auth-server/apparmor.txt new file mode 100644 index 0000000..d247c2d --- /dev/null +++ b/ldap-auth-server/apparmor.txt @@ -0,0 +1,42 @@ +#include + +profile ldap-auth-server flags=(attach_disconnected,mediate_deleted) { + #include + + # Capabilities + file, + signal (send) set=(kill,term,int,hup,cont), + + # S6-Overlay + /init ix, + /bin/** ix, + /usr/bin/** ix, + /run/{s6,s6-rc*,service}/** ix, + /package/** ix, + /command/** ix, + /etc/services.d/** rwix, + /etc/cont-init.d/** rwix, + /etc/cont-finish.d/** rwix, + /run/{,**} rwk, + /dev/tty rw, + + # Access to options.json and other files within your addon + /data/** rw, + + profile /usr/bin/ldap-auth-server flags=(attach_disconnected,mediate_deleted) { + #include + + # Receive signals from S6-Overlay + signal (receive) peer=*_ldap-auth-server, + + # Access to options.json and other files within your addon + /data/** rw, + + # Access required for service functionality + # Note: List was built by doing the following: + # 1. Add what is obviously needed based on what is in the script + # 2. Add `complain` as a flag to this profile temporarily and run the addon + # 3. Review the audit log with `journalctl _TRANSPORT="audit" -g 'apparmor="ALLOWED"'` and add other access as needed + # Remember to remove the `complain` flag when you are done + } +} diff --git a/ldap-auth-server/build.yaml b/ldap-auth-server/build.yaml new file mode 100644 index 0000000..0f0f5ca --- /dev/null +++ b/ldap-auth-server/build.yaml @@ -0,0 +1,14 @@ +# https://developers.home-assistant.io/docs/add-ons/configuration#add-on-dockerfile +build_from: + aarch64: "ghcr.io/home-assistant/aarch64-base:3.15" + amd64: "ghcr.io/home-assistant/amd64-base:3.15" + armhf: "ghcr.io/home-assistant/armhf-base:3.15" + armv7: "ghcr.io/home-assistant/armv7-base:3.15" + i386: "ghcr.io/home-assistant/i386-base:3.15" +labels: + org.opencontainers.image.title: "Home Assistant Add-on: LDAP Authentication Server add-on" + org.opencontainers.image.description: "Add-on to add LDAP authentication to Home Assistant." + org.opencontainers.image.source: "https://github.com/vqvu/home-assistant-addons/ldap-auth-server" + org.opencontainers.image.licenses: "Apache License 2.0" +args: + TEMPIO_VERSION: "2021.09.0" diff --git a/ldap-auth-server/config.yaml b/ldap-auth-server/config.yaml new file mode 100644 index 0000000..7fffc6f --- /dev/null +++ b/ldap-auth-server/config.yaml @@ -0,0 +1,32 @@ +# https://developers.home-assistant.io/docs/add-ons/configuration#add-on-config +name: LDAP Authentication Server +version: "0.1.2" +slug: ldap-auth-server +description: Add-on to add LDAP authentication to Home Assistant. +url: "https://github.com/BlackDragon-B/ldap-auth-server" +arch: + - armhf + - armv7 + - aarch64 + - amd64 + - i386 +startup: services +init: false +map: + - share:rw +ports: + 80/tcp: null +options: + ldap_server_url: null + bind_dn_template: null + bind_dn_password: null + search_base_dn: "" + search_filter_template: "" + debug_mode: false +schema: + ldap_server_url: str + bind_dn_template: str + bind_dn_password: str + search_base_dn: str? + search_filter_template: str? + debug_mode: bool diff --git a/ldap-auth-server/go.mod b/ldap-auth-server/go.mod new file mode 100644 index 0000000..e41fe65 --- /dev/null +++ b/ldap-auth-server/go.mod @@ -0,0 +1,37 @@ +module github.com/vqvu/home-assistant-addons/ldap-auth-server + +go 1.19 + +require ( + github.com/gin-gonic/gin v1.9.0 + github.com/go-ldap/ldap/v3 v3.4.4 + github.com/sirupsen/logrus v1.9.0 +) + +require ( + github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 // indirect + github.com/bytedance/sonic v1.8.2 // indirect + github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/go-asn1-ber/asn1-ber v1.5.4 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.11.2 // indirect + github.com/goccy/go-json v0.10.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.2.4 // indirect + github.com/leodido/go-urn v1.2.1 // indirect + github.com/mattn/go-isatty v0.0.17 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.0.6 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.10 // indirect + golang.org/x/arch v0.2.0 // indirect + golang.org/x/crypto v0.6.0 // indirect + golang.org/x/net v0.7.0 // indirect + golang.org/x/sys v0.5.0 // indirect + golang.org/x/text v0.7.0 // indirect + google.golang.org/protobuf v1.28.1 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/ldap-auth-server/go.sum b/ldap-auth-server/go.sum new file mode 100644 index 0000000..7da28c3 --- /dev/null +++ b/ldap-auth-server/go.sum @@ -0,0 +1,104 @@ +github.com/Azure/go-ntlmssp v0.0.0-20220621081337-cb9428e4ac1e/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU= +github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 h1:mFRzDkZVAjdal+s7s0MwaRv9igoPqLRdzOLzw/8Xvq8= +github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU= +github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= +github.com/bytedance/sonic v1.8.2 h1:Eq1oE3xWIBE3tj2ZtJFK1rDAx7+uA4bRytozVhXMHKY= +github.com/bytedance/sonic v1.8.2/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= +github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= +github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams= +github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.9.0 h1:OjyFBKICoexlu99ctXNR2gg+c5pKrKMuyjgARg9qeY8= +github.com/gin-gonic/gin v1.9.0/go.mod h1:W1Me9+hsUSyj3CePGrd1/QrKJMSJ1Tu/0hFEH89961k= +github.com/go-asn1-ber/asn1-ber v1.5.4 h1:vXT6d/FNDiELJnLb6hGNa309LMsrCoYFvpwHDF0+Y1A= +github.com/go-asn1-ber/asn1-ber v1.5.4/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0= +github.com/go-ldap/ldap/v3 v3.4.4 h1:qPjipEpt+qDa6SI/h1fzuGWoRUY+qqQ9sOZq67/PYUs= +github.com/go-ldap/ldap/v3 v3.4.4/go.mod h1:fe1MsuN5eJJ1FeLT/LEBVdWfNWKh459R7aXgXtJC+aI= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.11.2 h1:q3SHpufmypg+erIExEKUmsgmhDTyhcJ38oeKGACXohU= +github.com/go-playground/validator/v10 v10.11.2/go.mod h1:NieE624vt4SCTJtD87arVLvdmjPAeV8BQlHtMnw9D7s= +github.com/goccy/go-json v0.10.0 h1:mXKd9Qw4NuzShiRlOXKews24ufknHO7gx30lsDyokKA= +github.com/goccy/go-json v0.10.0/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk= +github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= +github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w= +github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY= +github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= +github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pelletier/go-toml/v2 v2.0.6 h1:nrzqCb7j9cDFj2coyLNLaZuJTLjWjlaz6nvTvIwycIU= +github.com/pelletier/go-toml/v2 v2.0.6/go.mod h1:eumQOmlWiOPt5WriQQqoM5y18pDHwha2N+QD+EUNTek= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= +github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= +github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.10 h1:eimT6Lsr+2lzmSZxPhLFoOWFmQqwk0fllJJ5hEbTXtQ= +github.com/ugorji/go/codec v1.2.10/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/arch v0.2.0 h1:W1sUEHXiJTfjaFJ5SLo0N6lZn+0eO5gWD1MFeTGqQEY= +golang.org/x/arch v0.2.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.6.0 h1:qfktjS5LUO+fFKeJXZ+ikTRijMmljikvG68fpMMruSc= +golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g= +golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w= +google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/ldap-auth-server/ldap_auth_command.sh b/ldap-auth-server/ldap_auth_command.sh new file mode 100644 index 0000000..7bd7e6c --- /dev/null +++ b/ldap-auth-server/ldap_auth_command.sh @@ -0,0 +1,16 @@ +#!/bin/bash +set -o errexit +set -o pipefail +set -o nounset + +HOST="${1:-localhost:8080}" +ESCAPED_USERNAME="$(jq --raw-input <<< "${username}")" +ESCAPED_PASSWORD="$(jq --raw-input <<< "${password}")" +curl http://${HOST}/hass_authenticate \ + -X POST \ + -H "Content-Type: application/json" \ + --fail-with-body \ + -d "$(cat << EOF +{"username": ${ESCAPED_USERNAME},"password": ${ESCAPED_PASSWORD}} +EOF +)" diff --git a/ldap-auth-server/main.go b/ldap-auth-server/main.go new file mode 100644 index 0000000..b21a04b --- /dev/null +++ b/ldap-auth-server/main.go @@ -0,0 +1,265 @@ +package main + +import ( + "encoding/json" + "errors" + "flag" + "fmt" + "net/http" + "os" + "strings" + + "github.com/gin-gonic/gin" + ldap "github.com/go-ldap/ldap/v3" + log "github.com/sirupsen/logrus" +) + +var configFile = flag.String("config", "/data/options.json", "The path to the server's config file") + +// LDAPOptions holds the opotions for an `LDAPAuthenticator`. +type LDAPOptions struct { + ServerURL string + BindDNTemplate string + BindDNPassword string + SearchBaseDN string + SearchFilterTemplate string +} + +// LDAPUser holds metadata about a user from an LDAP server. +type LDAPUser struct { + DisplayName string +} + +// LDAPAuthenticator is a client for authenticating users against an LDAP server. +type LDAPAuthenticator struct { + Options LDAPOptions +} + +// Authenticate authenticates a user given their username and password. +// +// If authentication is successful, it also returns metadata about the +// authenticated user. +func (a *LDAPAuthenticator) Authenticate(username, password string) (bool, LDAPUser, error) { + if password == "" { + return false, LDAPUser{}, nil + } + + conn, err := ldap.DialURL(a.Options.ServerURL) + if err != nil { + return false, LDAPUser{}, fmt.Errorf("could not dial server at %q: %w", a.Options.ServerURL, err) + } + defer conn.Close() + + bindDN := a.Options.BindDNTemplate + log.Debugf("Binding to DN: %q", bindDN) + if err := conn.Bind(a.Options.BindDNTemplate, a.Options.BindDNPassword); err != nil { + log.Debugf("Could not bind to user %q: %q with password %q", bindDN, err, a.Options.BindDNPassword) + return false, LDAPUser{}, nil + } + + searchFilter := fmt.Sprintf(a.Options.SearchFilterTemplate, username) + log.Debugf("Searching with filter: %q", searchFilter) + res, err := conn.Search(ldap.NewSearchRequest( + a.Options.SearchBaseDN, + ldap.ScopeWholeSubtree, + ldap.NeverDerefAliases, + /* SizeLimit= */ 2, + /* TimeLimit= */ 1, + /* TypesOnly= */ false, + searchFilter, + /* Attribuutes= */ nil, + /* Controls= */ nil, + )) + if err != nil { + log.Warnf("Search failed: %v", err) + return false, LDAPUser{}, nil + } + + if len(res.Entries) == 0 { + log.Debugf("No matches found for filter: %q", searchFilter) + return false, LDAPUser{}, nil + } + if len(res.Entries) > 1 { + log.Debugf("More than one (%d) matches found for filter: %q", len(res.Entries), searchFilter) + return false, LDAPUser{}, nil + } + + entry := res.Entries[0] + if log.IsLevelEnabled(log.DebugLevel) { + var entryStr strings.Builder + fmt.Fprintf(&entryStr, "DN: %q\n", entry.DN) + for _, attr := range entry.Attributes { + fmt.Fprintf(&entryStr, "%s: %q\n", attr.Name, attr.Values) + } + log.Debugf("User entry:\n%v", entryStr.String()) + } + return true, LDAPUser{ + DisplayName: entry.GetAttributeValue("cn"), + }, nil +} + +var ErrUserAuthnFailed = errors.New("could not authenticate user") + +type ServerOptions struct { + LDAPOptions LDAPOptions +} + +type HASSAuthenticateRequest struct { + Username string `json:"username" binding:"required"` + Password string `json:"password" binding:"required"` +} + +type ErrorResponse struct { + StatusCode int + PublicError string + Error error +} + +type Server struct { + options ServerOptions + authenticator LDAPAuthenticator + router *gin.Engine +} + +// NewServer creates a new Server. +func NewServer(options ServerOptions) *Server { + server := &Server{ + options: options, + authenticator: LDAPAuthenticator{ + Options: options.LDAPOptions, + }, + router: gin.Default(), + } + if err := server.router.SetTrustedProxies(nil); err != nil { + panic("Not possible") + } + server.router.POST("/hass_authenticate", server.hassAuthenticate) + return server +} + +func (s *Server) writeError(c *gin.Context, err ErrorResponse) { + if err.StatusCode >= 400 && err.StatusCode < 500 { + log.Infof(err.Error.Error()) + } else { + log.Warnf(err.Error.Error()) + } + + if gin.Mode() == gin.DebugMode { + c.JSON(err.StatusCode, gin.H{"error": err.Error.Error()}) + } else { + c.JSON(err.StatusCode, gin.H{"error": err.PublicError}) + } +} + +func (s *Server) hassAuthenticate(c *gin.Context) { + var req HASSAuthenticateRequest + if err := c.BindJSON(&req); err != nil { + s.writeError(c, ErrorResponse{ + StatusCode: http.StatusBadRequest, + PublicError: err.Error(), + Error: err, + }) + return + } + + ok, user, err := s.authenticator.Authenticate(req.Username, req.Password) + if err != nil { + s.writeError(c, ErrorResponse{ + StatusCode: http.StatusBadRequest, + PublicError: fmt.Sprintf("Could not authenticate user %q", req.Username), + Error: fmt.Errorf("when authenticating: %w", err), + }) + return + } + if !ok { + s.writeError(c, ErrorResponse{ + StatusCode: http.StatusBadRequest, + PublicError: fmt.Sprintf("Could not authenticate user: %q", req.Username), + Error: fmt.Errorf("when authenticating %q: %w", req.Username, ErrUserAuthnFailed), + }) + return + } + if user.DisplayName != "" { + safeDN := strings.ReplaceAll(user.DisplayName, "\n", "") + fmt.Fprintf(c.Writer, "name = %v", safeDN) + } +} + +// Serve starts the server listening to requests. +func (s *Server) Serve() error { + addr := ":80" + log.Infof("Starting server at: %q", addr) + return s.router.Run(addr) +} + +// AddOnConfig is the struct representing the add-on's configuration. +type AddOnConfig struct { + LDAPServerURL string `json:"ldap_server_url"` + BindDNTemplate string `json:"bind_dn_template"` + BindDNPassword string `json:"bind_dn_password"` + SearchBaseDN string `json:"search_base_dn"` + SearchFilterTemplate string `json:"search_filter_template"` + DebugMode bool `json:"debug_mode"` +} + +// parseAddOnConfig parses the `AddOnConfig` from a JSON file. +func parseAddOnConfig(configFile string) (AddOnConfig, error) { + jsonBytes, err := os.ReadFile(configFile) + if err != nil { + return AddOnConfig{}, fmt.Errorf("could not read config file: %q: %w", configFile, err) + } + + var config AddOnConfig + err = json.Unmarshal(jsonBytes, &config) + if err != nil { + return AddOnConfig{}, fmt.Errorf("could not parse config file: %q: %w", configFile, err) + } + return config, nil +} + +var ErrInvalidServerOptions = errors.New("invalid server options") + +func toServerOptions(config AddOnConfig) (ServerOptions, error) { + if (config.SearchBaseDN == "") != (config.SearchFilterTemplate == "") { + return ServerOptions{}, fmt.Errorf("search_base_dn (%q) and search_filter (%q) must both be set or both be unset: %w", config.SearchBaseDN, config.SearchFilterTemplate, ErrInvalidServerOptions) + } + + log.Infof("Loaded config: %+v", config) + return ServerOptions{ + LDAPOptions: LDAPOptions{ + ServerURL: config.LDAPServerURL, + BindDNTemplate: config.BindDNTemplate, + SearchBaseDN: config.SearchBaseDN, + SearchFilterTemplate: config.SearchFilterTemplate, + }, + }, nil +} + +func init() { + log.SetReportCaller(true) + log.SetLevel(log.InfoLevel) +} + +func main() { + flag.Parse() + config, err := parseAddOnConfig(*configFile) + if err != nil { + log.Fatalf("Invalid config: %v", err) + } + if config.DebugMode { + gin.SetMode(gin.DebugMode) + log.SetLevel(log.DebugLevel) + } else { + gin.SetMode(gin.ReleaseMode) + } + + options, err := toServerOptions(config) + if err != nil { + log.Fatalf("Invalid config: %v", err) + } + server := NewServer(options) + if err := server.Serve(); err != nil { + log.Fatalf("Error while serving: %v", err) + } + log.Info("Server terminated.") +} diff --git a/ldap-auth-server/translations/en.yaml b/ldap-auth-server/translations/en.yaml new file mode 100644 index 0000000..f812a79 --- /dev/null +++ b/ldap-auth-server/translations/en.yaml @@ -0,0 +1,39 @@ +configuration: + ldap_server_url: + name: LDAP Server URL + description: | + The URL of the server to connect to. Prefix with ldap:// or ldaps://. + + Example: ldaps://ldap.example.com:636 + bind_dn_template: + name: Bind DN Template + description: | + The template for the DN of the user. The first instance of `%s` will be replaced + with the username. + + Example: cn=%s,ou=people,dc=example,dc=com + bind_dn_password: + name: Bind DN Password + description: | + Password to use for Bind DN + search_base_dn: + name: Search Base DN + description: | + The base DN for user searches. Only necessary when using a search filter. + + Example: ou=people,dc=example,dc=com + search_filter_template: + name: Search Filter Template + description: | + The template for the search filter to apply when searching for users. The first + `%s` will be replaced with the username. This option can be used to only allow + members of specific groups. + + Example: (&(uid=%s)(memberof=cn=home_assistant,ou=groups,dc=example,dc=com)) + debug_mode: + name: Debug Mode + description: | + Run the server in debug mode. + +network: + 80/tcp: "The server's port. Generally not necessary, but it can be mapped for debugging."