rendere sicuro accesso monitor da remoto SSL HTTPS

Discussioni relative a software necessario per il monitoraggio e il Raspberry
metus
Messaggi: 120
Iscritto il: 10/05/2019, 1:04

rendere sicuro accesso monitor da remoto SSL HTTPS

Messaggioda metus » 01/10/2019, 12:00

Buongiorno,
chiedo a voi visto che non riesco ad ottenere risultati. Sono partito mesi fa ad utilizzare la SolarStrech3.1 che mi ha aperto un mondo. Logicamente ho modellato l'immagine installandoci molto altro tra cui Home Assistant in ambiente virtuale e tutto funziona perfettamente. Ho editato veramente poco anche il cruscotto della "signora maria" e il menu iniziale del webserver apache. Ora volevo passare tutto sotto https ssl. Ad oggi sono riuscito a passare home assistant (perchè risiede in un ambiente virtuale) ma non riesco a passare sotto https il menu iniziale 123solar metern monitorRPI ecc ecc.... [e il menu iniziale con password iniziale ecc ecc]
I file da toccare se non ho capito male sono due:
/etc/apache2/sites-available/000-default.conf
/etc/apache2/sites-available/default-ssl.conf

Per generarmi le varie chiavi ho usato "dehydrated" che deriva da "let's encrypt" con "duck dns" e mi fornisce tutte le key e certificati vari anche concatenati [che funzionano perfettamente perchè utlizzo per accedere ad home assistant che risiede sullo stesso raspbarry].

Ho abilitato la porta 443 sia nel mio router sia come regola nel firewall del raspbarry ma sicuramente sbaglio qualcosa.

Nessuno di voi ha già provato tutto ciò? Avete una configurazione funzionante che vi permette di accedere al raspbarry con https:// usando apache?

Grazie in anticipo per una risposta e siate buoni nelle critiche visto che sono i miei primi esperimenti



metus
Messaggi: 120
Iscritto il: 10/05/2019, 1:04

Re: rendere sicuro accesso monitor da remoto SSL HTTPS

Messaggioda metus » 04/10/2019, 12:16

PER FAVORE CREATEVI UNA COPIA DELLA SD PRIMA DI FARE LE MODIFICHE non dovete rischiare di perdere tutto.
Premetto che non ho risolto tutto al 100% tuttavia ho ottenuto qualcosa di accettabile.
Ho solo un problema riguardante i link http://localhost oppure http://127.0.0.1 che non riesco a trasformare in https e che quindi mi fa comparire sui browser usuali (chrome firefox ecc...) un avviso che dice che alcune pagine non sono sicure (ma comunque risultano navigabili ed utilizzabili).

Anticipo che ho usato numerose guide e fatto innumerevoli prove quindi provo a riportare la sequenza che per me ha funzionato ma può essere che manchi qualcosa (procedure che ho fatto pensando non funzionassero magari sono quelle che mi han permesso di far girare il tutto dopo, ma non me ne sono reso conto. Rimango quindi a disposizione e premetto che può non funzionare tutto al primo colpo).

Per prima cosa ho usato questa guida https://indomus.it/guide/remotizzare-home-assistant-su-raspberry-pi-in-piena-sicurezza/ (voi evitate i passaggi che non vi interessano... quelli riferiti a home assistant). L'obbiettivo è registrarsi a DuckDNS e ottenere sul raspberry i due file con i relativi certificati e chiavi. Della guida sopra linkata se non avete home assistant seguirei i passaggi: "Configurare DuckDNS" + "Attivare il port forwarding sul router" (stando a voi scegliere la porta... io ne ho scelta una complicata che si colleghi internamente al raspberry con la porta 443 che è la canonica per i siti https!) +"Installare e configurare “dehydrated”" (qui dovrete decidere voi il percorso in cui salvare i file e in cui saranno i certificati e tutto quello che servirà per la connessione tramite https... io ho seguito passo passo il capitolo perchè avevo installato home assistant... fossi in voi per essere sicuro gli script funzionino creerei la stessa cartella e stesso percorso così da avere meno variabili in caso di errori) + "Automatizzare il rinnovo del certificato". Volendo potete anche fare "Aggiornamento automatico".

Ora avrete i file che vi interessano nel percorso /home/homeassistant/dehydrated/certs (sempre che abbiate deciso di creare il percorso seguendo la guida sopra).

Arrivati a questo punto io riuscivo ad accedere con https://XXXXXXXXXX.duckdns.org:portaesternachehoscelto alla mia domotica e il sito risultava perfettamente sicuro con i vari certificati SSL riconosciuti da google chrome firefox smartphone vari ecc ecc...

A voi però interessa poter accedere a 123 solar metern monitor cruscotto ecc...

Quindi il mio scopo era utilizzare i file di duckdns (che funzionavano in quanto per home assistant funzionavano) nel webserver apache2 che permette la visualizzazione di tutto ciò che ci interessa e in particolare quello contenuto nella cartella WWW del nostro raspberry.
Qui ho provato un po di tutto.... Mi ha aiutato molto leggere i log contenuto in /var/log/apache2 quando incorrevo in errori.
Ho smanettato anche con il firewall del raspberry con il comando iptables per aprire la porta 443 tipica dei siti https usando i seguenti due comandi:

Codice: Seleziona tutto

iptables -A INPUT -p tcp -m tcp --sport 443 -j ACCEPT
iptables -A OUTPUT -p tcp -m tcp --dport 443 -j ACCEPT

Non so se servissero ma li ho lanciati.
Inoltre ad ogni riavvio iptables si resetta quindi se si vuole mantenere la modifica bisogna digitare:

Codice: Seleziona tutto

/sbin/service iptables save


Una volta aperte le porte e una volta localizzati i file di duckdns nel percorso teorico: /home/homeassistant/dehydrated/certs
ho cercato di modificare apache2. Per far ciò sono andato in /etc/apache2 il file ports.conf era già ok in quanto se attivo il modulo ssl ascoltava la porta 443. Ho aperto il file apache2.conf e non ricordo se ho decommentato qualcosa per attivare il modulo ssl, tuttavia va lanciato da terminale il comando per attivare tale modulo in apache

Codice: Seleziona tutto

$ sudo a2ensite ssl
oppure se non va nel mio caso il seguente comando

Codice: Seleziona tutto

sudo a2ensite default-ssl


Per passare ad apache i certificati ssl di duckdns va modificato il seguente file: /etc/apache2/sites-available/default-ssl.conf dove va controllata sulla seconda riga che la porta sia 443 e modificati i percorsi dei certificati SSL.

Riporto il mio file censurato del dominio: tuttavia voi dovete modificare SSLCertificateFile e SSLCertificateKeyFile col vostro dominio registrato e il vostro percorso. I file a cui puntare sono quelli scritti "fullchain.pem" e "privkey.pem"

Codice: Seleziona tutto

<IfModule mod_ssl.c>
   <VirtualHost _default_:443>
      ServerAdmin webmaster@localhost
      
      DocumentRoot /var/www

      # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
      # error, crit, alert, emerg.
      # It is also possible to configure the loglevel for particular
      # modules, e.g.
      #LogLevel info ssl:warn

      ErrorLog ${APACHE_LOG_DIR}/error.log
      
      # Check for requests to exclude from the access log
      SetEnvIf Request_URI "^/metern/*" log_exclude=true
      SetEnvIf Request_URI "^/123solar/*" log_exclude=true
      SetEnvIf Request_URI "^/menu/*" log_exclude=true
      SetEnvIf Request_URI "^/MyScripts/monitor/*" log_exclude=true
      # Change log to test for not log_exclude
      CustomLog ${APACHE_LOG_DIR}/access.log combined env=!log_exclude

      # For most configuration files from conf-available/, which are
      # enabled or disabled at a global level, it is possible to
      # include a line for only one particular virtual host. For example the
      # following line enables the CGI configuration for this host only
      # after it has been globally disabled with "a2disconf".
      #Include conf-available/serve-cgi-bin.conf

      #   SSL Engine Switch:
      #   Enable/Disable SSL for this virtual host.
      SSLEngine on

      #   A self-signed (snakeoil) certificate can be created by installing
      #   the ssl-cert package. See
      #   /usr/share/doc/apache2/README.Debian.gz for more info.
      #   If both key and certificate are stored in the same file, only the
      #   SSLCertificateFile directive is needed.
      

        SSLCertificateFile   /home/homeassistant/dehydrated/certs/XXXXXXXXX.duckdns.org/fullchain.pem
        SSLCertificateKeyFile /home/homeassistant/dehydrated/certs/XXXXXXXXX.duckdns.org/privkey.pem

      #   Server Certificate Chain:
      #   Point SSLCertificateChainFile at a file containing the
      #   concatenation of PEM encoded CA certificates which form the
      #   certificate chain for the server certificate. Alternatively
      #   the referenced file can be the same as SSLCertificateFile
      #   when the CA certificates are directly appended to the server
      #   certificate for convinience.
      #SSLCertificateChainFile /etc/apache2/ssl.crt/server-ca.crt

      #   Certificate Authority (CA):
      #   Set the CA certificate verification path where to find CA
      #   certificates for client authentication or alternatively one
      #   huge file containing all of them (file must be PEM encoded)
      #   Note: Inside SSLCACertificatePath you need hash symlinks
      #       to point to the certificate files. Use the provided
      #       Makefile to update the hash symlinks after changes.
      #SSLCACertificatePath /etc/ssl/certs/
      #SSLCACertificateFile /etc/apache2/ssl.crt/ca-bundle.crt

      #   Certificate Revocation Lists (CRL):
      #   Set the CA revocation path where to find CA CRLs for client
      #   authentication or alternatively one huge file containing all
      #   of them (file must be PEM encoded)
      #   Note: Inside SSLCARevocationPath you need hash symlinks
      #       to point to the certificate files. Use the provided
      #       Makefile to update the hash symlinks after changes.
      #SSLCARevocationPath /etc/apache2/ssl.crl/
      #SSLCARevocationFile /etc/apache2/ssl.crl/ca-bundle.crl

      #   Client Authentication (Type):
      #   Client certificate verification type and depth.  Types are
      #   none, optional, require and optional_no_ca.  Depth is a
      #   number which specifies how deeply to verify the certificate
      #   issuer chain before deciding the certificate is not valid.
      #SSLVerifyClient require
      #SSLVerifyDepth  10

      #   SSL Engine Options:
      #   Set various options for the SSL engine.
      #   o FakeBasicAuth:
      #    Translate the client X.509 into a Basic Authorisation.  This means that
      #    the standard Auth/DBMAuth methods can be used for access control.  The
      #    user name is the `one line' version of the client's X.509 certificate.
      #    Note that no password is obtained from the user. Every entry in the user
      #    file needs this password: `xxj31ZMTZzkVA'.
      #   o ExportCertData:
      #    This exports two additional environment variables: SSL_CLIENT_CERT and
      #    SSL_SERVER_CERT. These contain the PEM-encoded certificates of the
      #    server (always existing) and the client (only existing when client
      #    authentication is used). This can be used to import the certificates
      #    into CGI scripts.
      #   o StdEnvVars:
      #    This exports the standard SSL/TLS related `SSL_*' environment variables.
      #    Per default this exportation is switched off for performance reasons,
      #    because the extraction step is an expensive operation and is usually
      #    useless for serving static content. So one usually enables the
      #    exportation for CGI and SSI requests only.
      #   o OptRenegotiate:
      #    This enables optimized SSL connection renegotiation handling when SSL
      #    directives are used in per-directory context.
      #SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
      <FilesMatch "\.(cgi|shtml|phtml|php)$">
            SSLOptions +StdEnvVars
      </FilesMatch>
      <Directory /usr/lib/cgi-bin>
            SSLOptions +StdEnvVars
      </Directory>

      #   SSL Protocol Adjustments:
      #   The safe and default but still SSL/TLS standard compliant shutdown
      #   approach is that mod_ssl sends the close notify alert but doesn't wait for
      #   the close notify alert from client. When you need a different shutdown
      #   approach you can use one of the following variables:
      #   o ssl-unclean-shutdown:
      #    This forces an unclean shutdown when the connection is closed, i.e. no
      #    SSL close notify alert is send or allowed to received.  This violates
      #    the SSL/TLS standard but is needed for some brain-dead browsers. Use
      #    this when you receive I/O errors because of the standard approach where
      #    mod_ssl sends the close notify alert.
      #   o ssl-accurate-shutdown:
      #    This forces an accurate shutdown when the connection is closed, i.e. a
      #    SSL close notify alert is send and mod_ssl waits for the close notify
      #    alert of the client. This is 100% SSL/TLS standard compliant, but in
      #    practice often causes hanging connections with brain-dead browsers. Use
      #    this only for browsers where you know that their SSL implementation
      #    works correctly.
      #   Notice: Most problems of broken clients are also related to the HTTP
      #   keep-alive facility, so you usually additionally want to disable
      #   keep-alive for those clients, too. Use variable "nokeepalive" for this.
      #   Similarly, one has to force some clients to use HTTP/1.0 to workaround
      #   their broken HTTP/1.1 implementation. Use variables "downgrade-1.0" and
      #   "force-response-1.0" for this.
      # BrowserMatch "MSIE [2-6]" \
      #      nokeepalive ssl-unclean-shutdown \
      #      downgrade-1.0 force-response-1.0

   </VirtualHost>
</IfModule>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet



Riavviate apache e nel file log in /var/log/apache2/error.log se non ci sono errori e il servizio apache è ripartito consiglio di riavviare il raspberry e dovrebbe essere possibile accedere da remoto con https adesso al vostro raspberry.
Io ho dovuto modificare /var/www/menu/menu.php per non puntare più a siti http ma https tuttavia avevo personalizzato il file quindi magari a voi non serve.

Alcuni comando che cito li ho letti in questa guida che però non ho seguito passo passo https://variax.wordpress.com/2017/03/18/adding-https-to-the-raspberry-pi-apache-web-server/comment-page-1/


NON sono riuscito a rendere sicuro tramite https il rpimonitor quindi nel file menu.php ho dovuto lasciare

Codice: Seleziona tutto

            <li><a href="http://<?php echo $_SERVER['SERVER_NAME'];?>:5558/" target="_self">
                 <img src="images/rpi-monitor.png">
                <h2>RPI monitior schedina</h2></a>

e questo fa si che i browser avvisino dicendo... il sito non è sicuro anche se https perchè contiene link http! (ho parafrasato).

Inoltre ho modificato anche il file (che avevo già ampiamente editato) /var/www/MyScripts/monitor/summary.php

modificando gli $URL_123solar e $URL_TOT_DAY e $URL_prel facendoli puntare al dominio duckdns al posto che 127.0.0.1 per evitare almeno in quella pagina il mesaggio url non sicuri http. [non mi piace che per dei dati in locale debba passare in internet allungando i tempi di risposta ma è un pagliativo che ho trovato... onestamente non capisco come mai la funzione contenuta in summary.php file_get_contents

Codice: Seleziona tutto

$json_prel = file_get_contents($URL_prel);
non mi permetta di passargli il percorso del file ma voglia l'url. Spiegandomi meglio
COSI' FUNZIONA:

Codice: Seleziona tutto

$URL_123solar = "https://XXXXXXX.duckdns.org:XXXX/123solar/programs/programmultilive.php";
$json_123solar = file_get_contents($URL_123solar);


COSI' NO:

Codice: Seleziona tutto

$json_123solar = file_get_contents(../../123solar/programs/programmultilive.php);

Anche dandogli il percorso completo NON funziona /var/www/123solar/programs/programmultilive.php e la cosa mi turba perchè poco più sotto sempre nel file summary.php c'è $metern_file = file_get_contents("/dev/shm/metern$ID.txt"); e funziona benissimo.

Spero possa tornare utile a qualcuno.
Buona giornata


wifi75
Messaggi: 213
Iscritto il: 29/07/2019, 10:24

Re: rendere sicuro accesso monitor da remoto SSL HTTPS

Messaggioda wifi75 » 25/03/2020, 15:51

io ho passato tutto sotto ssl ma con un reverse proxy, l'unica cosa che non funziona è il cruscotto , le lancette non si muovono.


Torna a “Software”

Chi c’è in linea

Visitano il forum: Nessuno e 2 ospiti