Gå til innhold
  • Bli medlem
Støtt hjemmeautomasjon.no!

HomeSeer + nginx + TLS + 2FA (Google)


ZoRaC

Anbefalte innlegg

Kjører i dag HomeSeer med en nginx foran (med TLS-kryptering og pålogging).

Jeg har ikke åpnet for tilgang via internett og bruker da VPN til en server hjemme og deretter pålogging via webgrensesnittet.

 

Ønsker å få åpnet for tilgang fra internett, men da vil jeg ha 2FA! :)

Kom over denne guiden: https://dev.to/ahmedmusaad/add-google-authentication-to-any-website-using-nginx-and-oauth-proxy-259l

Der ser det ut til at man kan integrere f.eks Google pålogging, slik at man får brukt samme 2FA som jeg allerede har på epost OG man får single-sign-on!

 

Er det noen som har konfigurert dette?

Jeg er ikke så stødig på nginx-konfig, så skulle gjerne sett noen konkrete eksempler mot HS... 

Lenke til kommentar
Del på andre sider

1 time siden, Moskus skrev:

... uten internett? 

 

Hehe, det er en sannhet med modifikasjoner da... Har åpnet enkelt URLer for tilgang utenfra (f.eks for å bruke PHLocation). Da med TLS og autentisering.

Men hvis jeg skal "åpne helt", så vil jeg gjerne ha 2FA. :) Og det med SSO (altså, så lenge jeg er pålogget Google-kontoen), så er jeg automatisk innlogget høres jo ut som "nice to have" også! ;) 

Lenke til kommentar
Del på andre sider

Noen som er gode på nginx her?

Jeg er nesten i mål - får det tilsynelatende til å funke når jeg kjører opp en ekstra webserver på port 85, men når jeg legger samme konfig på port 443 så får jeg bare 404-feilmelding. Ønsker egentlig ikke å dele hele config-fila her, så glad om noen melder seg som jeg kan sende den til på PM. :) 

Lenke til kommentar
Del på andre sider

Da var jeg i mål! :)

Fant ut av problemet, det var kombinasjonen av vanlig "basic auth" og OAuth2 som skapte problemer. Takk til @Charlie for å ha sett igjennom konfig etterpå, for å utelukke evt store "tabber"... :P

 

Jeg fulgte i utgangspunktet denne guiden:

https://dev.to/ahmedmusaad/add-google-authentication-to-any-website-using-nginx-and-oauth-proxy-259l

(men last ned nyeste versjon, ikke 5.0.0!!!)

Også viktig å merke seg at man i "oauth_proxy.service" må bruke to bindestrek foran config, når man bruker nyere versjoner av oauth2-proxy:

"--config=/opt/oauth2_proxy/oauth2_proxy.cfg"

 

"Oppskriften" for hva man måtte gjøre på Google sine sider var litt utdatert, så den delen stemmer bedre med denne guiden:

https://devopsloggers.com/2020/05/30/oauth2_proxy-google-authentication-using-nginx-on-ubuntu-18-04/

 

Min oauth2_proxy.cfg:

## OAuth2 Proxy Config File
## https://github.com/oauth2-proxy/oauth2-proxy
 
## <addr>:<port> to listen on for HTTP/HTTPS clients
http_address = "127.0.0.1:4180"
# https_address = ":443"
 
## Are we running behind a reverse proxy? Will not accept headers like X-Real-Ip unless this is set.
reverse_proxy = true
 
## TLS Settings
# tls_cert_file = ""
# tls_key_file = ""
 
## the OAuth Redirect URL.
# defaults to the "https://" + requested host header + "/oauth2/callback"
redirect_url = "https://mitt-domene.no/oauth2/callback"
 
## the http url(s) of the upstream endpoint. If multiple, routing is based on path
# upstreams = [
#     "http://127.0.0.1:8080/"
# ]
 
## Logging configuration
logging_filename = "/var/log/oauth2.log"
logging_max_size = 100
logging_max_age = 30
logging_local_time = true
#logging_compress = false
standard_logging = true
#standard_logging_format = "[{{.Timestamp}}] [{{.File}}] {{.Message}}"
request_logging = true
#request_logging_format = "{{.Client}} - {{.Username}} [{{.Timestamp}}] {{.Host}} {{.RequestMethod}} {{.Upstream}} {{.RequestURI}} {{.Protocol}} {{.UserAgent}} {{.StatusCode}} {{.ResponseSize}} {{.RequestDuration}}"
auth_logging = true
#auth_logging_format = "{{.Client}} - {{.Username}} [{{.Timestamp}}] [{{.Status}}] {{.Message}}"
 
## pass HTTP Basic Auth, X-Forwarded-User and X-Forwarded-Email information to upstream
# pass_basic_auth = true
# pass_user_headers = true
## pass the request Host Header to upstream
## when disabled the upstream Host is used as the Host Header
# pass_host_header = true
 
## Email Domains to allow authentication for (this authorizes any email on this domain)
## for more granular authorization use `authenticated_emails_file`
## To authorize any email addresses use "*"
 email_domains = [
     "mitt-domene.no"
 ]
 
## The OAuth Client ID, Secret
client_id = "**********************"
client_secret = "*******************"
 
## Pass OAuth Access token to upstream via "X-Forwarded-Access-Token"
# pass_access_token = false
 
## Authenticated Email Addresses File (one email per line)
#authenticated_emails_file = "/etc/oauth2-proxy/authorized_emails.txt"
 
## Htpasswd File (optional)
## Additionally authenticate against a htpasswd file. Entries must be created with "htpasswd -s" for SHA encryption
## enabling exposes a username/login signin form
# htpasswd_file = ""
 
## Templates
## optional directory with custom sign_in.html and error.html
# custom_templates_dir = ""
 
## skip SSL checking for HTTPS requests
# ssl_insecure_skip_verify = false
 
 
## Cookie Settings
## Name     - the cookie name
## Secret   - the seed string for secure cookies; should be 16, 24, or 32 bytes
##            for use with an AES cipher when cookie_refresh or pass_access_token
##            is set
## Domain   - (optional) cookie domain to force cookies to (ie: .yourcompany.com)
## Expire   - (duration) expire timeframe for cookie
## Refresh  - (duration) refresh the cookie when duration has elapsed after cookie was initially set.
##            Should be less than cookie_expire; set to 0 to disable.
##            On refresh, OAuth token is re-validated.
##            (ie: 1h means tokens are refreshed on request 1hr+ after it was set)
## Secure   - secure cookies are only sent by the browser of a HTTPS connection (recommended)
## HttpOnly - httponly cookies are not readable by javascript (recommended)
cookie_name = "_oauth2_proxy"
cookie_secret = "******************"
#cookie_domains = "gmail.com"
cookie_expire = "24h"
cookie_refresh = "1h"
cookie_secure = true
#cookie_httponly = true

 

 

Min nginx-konfig:

##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# http://wiki.nginx.org/Pitfalls
# http://wiki.nginx.org/QuickStart
# http://wiki.nginx.org/Configuration
#
# Generally, you will want to move this file somewhere, and start with a clean
# file but keep this around for reference. Or just disable in sites-enabled.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# These IPs will be allowed to use HTTP and won't redirect to HTTPS
geo $allow_http {
   default 0;
   10.0.1.100 1; # NodeMCU
   10.0.1.123 1; # Arduino
}

# HTTP-server
server {
    listen      80;
    server_name homeseer.local;

    error_log /var/log/nginx/error.log;
    access_log /var/log/nginx/access-80.log;

    #rewrites http to https, but not for allowed HTTP-clients (see geo-statement)
    if ($allow_http = 0) {
       rewrite ^ https://$server_name$request_uri? permanent;
    }
    
    root /usr/local/HomeSeer/html;
    add_header X-Whom direct;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html index.php;

    #Prevents hidden files (beginning with a period) from being served
    location ~ \/\. { access_log off; log_not_found off; deny all; }

    # serve HS3 json api via proxy
    location ~* \/(JSON|json) {
       proxy_http_version 1.1;
       proxy_set_header Connection "";

       # Require login or spesific IP
       satisfy any;
       auth_basic "Krever autentisering!";
       auth_basic_user_file '/etc/nginx/.htpasswd';
       allow 127.0.0.1;
       allow 10.0.1.100; # NodeMCU
       deny  all;

       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_pass http://127.0.0.1:8080 ; # Homeseer running on port 8080
       add_header X-Whom json;
       expires -1;
    }

    # Mostly used to host files to show on Chromecasts
    # Allow access for IoT-network
    location ~* \/(cast) {
      allow 10.0.2.0/24;
      deny all;

      include /etc/nginx/fastcgi.conf;
      fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }

    ## All PHP-files should be handled as PHP
    location ~ \.php$ {
        try_files $uri =404;

	include /etc/nginx/fastcgi.conf;
	fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }
}


# Default server configuration
#
server {
    server_name homeseer.local;

    # SSL configuration
    #
      listen 443 ssl http2 default_server;
    # listen [::]:443 ssl default_server;
    #
    # Note: You should disable gzip for SSL traffic.
    # See: https://bugs.debian.org/773332
    #
    # Read up on ssl_ciphers to ensure a secure configuration.
    # See: https://bugs.debian.org/765782
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;

    include snippets/ssl-homeseer.local.conf;
    include snippets/ssl-params.conf;

    proxy_intercept_errors on;
    # Don’t show the Nginx version number (in error pages / headers)
    server_tokens off;

    access_log /var/log/nginx/access-443.log;
    error_log /var/log/nginx/error.log;

    error_page 404 /error/HTTP404.html;
    error_page 403 /error/HTTP403.html;
    error_page 502 /error/HTTP502.html;
#    error_page 401 /error/HTTP401.html;

    root /usr/local/HomeSeer/html;
    add_header X-Whom direct;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html index.php;

    #Prevents hidden files (beginning with a period) from being served
    location ~ \/\. { access_log off; log_not_found off; deny all; }

    # Everyone needs access to /oauth2 to be able to authenticate
    location ^~ /oauth2 {
        proxy_pass http://127.0.0.1:4180;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Scheme $scheme;
    }
    
    # serve HS3 json api via proxy
    location ~* \/(JSON|json) {
       proxy_http_version 1.1;
       proxy_set_header Connection "";
    
       satisfy any;
       auth_basic "Krever autentisering!";
       auth_basic_user_file '/etc/nginx/.htpasswd';
       allow 127.0.0.1;
       deny  all;
    
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_pass http://127.0.0.1:8080 ; # Homeseer running on port 8080
       add_header X-Whom json;
       expires -1;
    }

    location ~ \.php$ {
        auth_request /oauth2/auth;
        error_page 401 = /oauth2/sign_in;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass_header Server;

        # if you enabled --cookie-refresh, this is needed for it to work with auth_request
        auth_request_set $auth_cookie $upstream_http_set_cookie; add_header Set-Cookie $auth_cookie;

        try_files $uri =404;

	include /etc/nginx/fastcgi.conf;
	fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
      deny all;
    }

    # Default matches everything and requires authentication
    location ~* / {
        auth_request /oauth2/auth;
        error_page 401 = /oauth2/sign_in;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass_header Server;

        # if you enabled --cookie-refresh, this is needed for it to work with auth_request
        auth_request_set $auth_cookie $upstream_http_set_cookie; add_header Set-Cookie $auth_cookie;

        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;      
        proxy_pass http://127.0.0.1:8080 ; # Homeseer running on port 8080
        add_header X-Whom HS3;
        expires -1;
    }
    
    location ^~ /error/ {
      internal;
      alias /usr/local/HomeSeer/html-error/;
      auth_basic "off";
      allow all;
    }
}	

 

Hvis oauth-servicen stopper så gir nginx en 500-server-error, så det er ikke slik at all autentisering bypasses om den krasjer. :)

Jeg kjører selvsagt Monit til å sjekke at den kjører og restarter den hvis ikke... ;) 

  • Like 1
  • Thanks 1
Lenke til kommentar
Del på andre sider

Bli med i samtalen

Du kan publisere innhold nå og registrere deg senere. Hvis du har en konto, logg inn nå for å poste med kontoen din.

Gjest
Skriv svar til emnet...

×   Du har limt inn tekst med formatering.   Lim inn uten formatering i stedet

  Du kan kun bruke opp til 75 smilefjes.

×   Lenken din har blitt bygget inn på siden automatisk.   Vis som en ordinær lenke i stedet

×   Tidligere tekst har blitt gjenopprettet.   Tøm tekstverktøy

×   Du kan ikke lime inn bilder direkte. Last opp eller legg inn bilder fra URL.

×
×
  • Opprett ny...

Viktig informasjon

Vi har plassert informasjonskapsler/cookies på din enhet for å gjøre denne siden bedre. Du kan justere dine innstillinger for informasjonskapsler, ellers vil vi anta at dette er ok for deg.