msgbartop
Blog di Dino Ciuffetti (Bernardino in realtà)
msgbarbottom

29 Lug 21 Don’t use SORBS DNSBL

Sorbs is a infamous DNS blacklist born to try to fight spam. They have a too much restrictive policy that won’t block spam at all but they just create some pain to your MTA.

They can delist your IP a couple of times but if one of your clients get hacked your good quality MTA will be listed for months, even years!

What they don’t understand is that we work with our IP reputation, so just change the IP is not a valid solution. When a valid MTA got abused to send spam the problem is generally solved in hours, or even minutes. A one month list will generate a great problem to the hacked MTA’s clients.

The only solution is: DON’T USE SORBS AT ALL. The list is not business oriented and so is only valid for lamers, bofh sysadmins and nerds…. ok I’m a bofh, nerd sysadmin but I don’t use Sorbs anymore. Sorry.

NOTA: Tell your sysadmins to NOT USE SORBS.

13 Mag 21 How to create a Certification Authority with CRL, OCSP and SAN on OpenSSL

Anyone knows that OpenSSL is a very cool full featured, free and open source SSL/TLS framework and toolkit but few people use it to create a custom Private Certification Authority.

The reasons to create a Private CA are many, but they are out of scope here, so I’ll just say how to achieve the goal.

First you must create a personalized version of my openssl.conf configuration file. You can safely do it modifing this labels below and running this one, on a single line:

# C="IT"; ST="Italy"; L="Rome"; O="My org"; OU="My Unit"; CN="My CA"; eml="my@email.com"; CABASEDIR="/tmp/B"; DD=730; mkdir -p "$CABASEDIR"; cd "$CABASEDIR"; echo 'H4sIAGM8nWACA7VVbYvjNhD+rl8hCIYuhOx2r3fQFMOlyRbChc2SXD4cIQRFmsTq
2ZJPkjeb+/UdyXZsX5JCW/rJmmdG8/povOZsQwTsWZG6LWfxeLStJLJuzhui4Ljl
YJzdCmniaDz6fbR8mkwXERHMsR2z0Abvg+lA7M6uMxHbhD2+/0BynUp+irMThtuW
ArFgJEuveLDwjXCTqiLbgenqTVre8vofNYMcMvL2/uHXLbw5UFZqZePCmlAC4To/
tRVeJoplsNW5izGrugPe+kesLkiwk42jySRqumfSEn3387WyDWC+rxArXbeg/Gwz
5nhC1m1pgzkWypnTM2YVlwbWMQdz82L0q1QcWppUc5ZK1zbW5sCU/M4cFngDZulK
SReUWGIAMGqWVRdskeepBEEgYzIdCYH528ZybeAbEkdaJ9WhkDYBsfUtjBHfXsKE
OWfkrnBgg0UjXozp9R0Sg3ijLogI9sCgX+yR/UpjqnS2QyTkciVmt4nj8ky9QH96
pCk4B4ZyLeCubVgPGikVdfBMqvixi7A3RK7NZekxqg2t0SrsvkhT6nO7u3atCb38
HHWnOquEyg8c+pSjeNexau7PIvIwuODAvAW0HeksZwp9XV5pPM6jW+SZd2Dq8ZZz
C9wr7m7cbgVYRW36jcOx5ejLfLWoWteYhRF8+KXL0Scv0ErqqJpokKVRV1V5WnfZ
uSFr/6yRiRvCCpdog73+BKepAOXkXuJS+gonKYYsPeLTJ2vNbb4huA8lHyNxnWFS
OYtrdfjHaLZ8IrbY/Ykt6bpImE3+1n1fWluAISisLDtAzNFQ4uT7Qh6kY+lSHhRz
hQESHo0A8enCdD5evng7fCVkXS/D67nuGS7XJprSagF5IWSY3kXMPho+KS7zBEyG
iff9L6ENXCYVVqEZYcl9jltGOX/8j80pP6O0pGUpDcNuxxFOpC1nigW86FDnRz9Z
qfaa9M7upyiOOPc0+uhHWerXYSdt/mV+FTeqNGumXGu7M0Wr63wx8y323R3jpPy5
zqAuMjC4rPF/rL623JAe/aILQ8eLGbWJLlJBd0DzYpeGrYuvXVOeaG2Bnrwdzjz3
0chqMR08xIlz+fD+PjtxNsA3fP5Rr8+xmggj6tkZmIub9EowjJXBEQkGhLNpKNf+
diMOC2Eq1/4ZUHzyuUZGmn9Wh7/bDeJTH5wjBaaEP2OPftaUCUGXo2daKL+ykBXU
JUB7lClBc8zXb0L5HW5PtdefPC+Hx+NxkGjrfIgA1AL5CyDty6++CQAA' | openssl base64 -d | gunzip |sed "s/%C%/$C/g"|sed "s/%ST%/$ST/g"|sed "s/%L%/$L/g"|sed "s/%O%/$O/g"|sed "s/%OU%/$OU/g"|sed "s/%eml%/$eml/g"|sed "s|%CABASEDIR%|$CABASEDIR|g"|sed "s/%DD%/$DD/g" > openssl.conf

So, those labels must be modified to your needs:

C="IT"; ST="Italy"; L="Rome"; O="My org"; OU="My Unit"; eml="my@email.com" CABASEDIR="/tmp/B"; DD=730

where C is your Country, ST is your State or Province name, L is locality, O is organization, OU is organization unit, eml is your CA email (if any), CABASEDIR is the directory that will hold all your CA stuff (private keys, certificates, config files, certificate serials and ca db) and DD is your default certificate validity in days.

At this time you should have a file called openssl.conf into your CABASEDIR directory.

As an alternative, you could directly copy and modify the openssl.conf file here.

Next, you obviously need to create the private key and self sign the certificate of your brand new CA, in this example we’ll create a clear RSA private key with 4096 bit encryption length, and a CA certificate that is valid for about 10 years. You mileage may vary, feel free to customize things:

# openssl genrsa -out ca.key 4096
# openssl req -new -x509 -days 3650 -key ca.key -out ca.crt -extensions 'v3_ca' -config openssl.conf

This way you’ll get a clear (not encrypted) private key, so a password is not needed when you’ll going to use it to sign things, generate new certificates, etc. btw, for security reasons, you may need to encrypt your PK with a passphrase. In that case, add -des attribute to your openssl genrsa command. Also you’ll have your precious CA certificate.
Choose a cool CN for your CA Name.

Now it’s time to create a large random number that will be used by OpenSSL as a starting point for your certificates’ Serial Numbers. You can create a large random number with this one (you could also create one by hand…):

# hexdump -n 20 -e '20/1 "%02X" 1 "\n"' /dev/random > certs.seq
C17FA21B11EE604633317891658DCC421F2EDFD5

Perfect. Now proceed creating an empty file called certs.db:

# touch certs.db

Also create a starting serial number for revoked certificates and an empty CRL:

# echo 00 > crlserial
# openssl ca -config openssl.conf -keyfile ca.key -cert ca.crt -gencrl -out crl.pem 
Using configuration from openssl.conf

At this point, you should have something like this:

# ls -lrth
totale 16K
-rw-r--r-- 1 dino dino 1,5K mag 5 20:06 openssl.conf
-rw------- 1 dino dino 3,2K mag 5 20:06 ca.key
-rw-r--r-- 1 dino dino 2,0K mag 5 20:07 ca.crt
-rw-r--r-- 1 dino dino 41 mag 5 20:07 certs.seq
-rw-r--r-- 1 dino dino 3 mag 5 20:08 crlserial
-rw-r--r-- 1 dino dino 999 mag 5 20:08 crl.pem
-rw-r--r-- 1 dino dino 0 mag 5 20:08 certs.db

Well. Now we can start creating our server (or client) certificates.
We start from its private key (here at 2048 bit but you can choose your own key length):

# openssl genrsa -out server.key 2048

And now the certificate:

# openssl req -new -key server.key -out server.csr -extensions 'v3_req' -config openssl.conf
# openssl ca -cert ca.crt -keyfile ca.key -in server.csr -out server.crt -config openssl.conf

If you don’t want to use the default certificates expiry days setted into openssl.conf (param default_days), you can pass the -days attribute to the last command, for example -days 365.
When asked, pay attention to correctly set all the requested attributes, principally the Common Name. Press Y when asked to sign and commit.

If everything gone OK you’ll have your brand new key and certificate:

# ls -lrth server.*
-rw------- 1 dino dino 1,7K mag 5 22:26 server.key
-rw-r--r-- 1 dino dino 1,2K mag 5 22:26 server.csr
-rw-r--r-- 1 dino dino 5,7K mag 5 22:28 server.crt

You can check the certificate with this command:

# openssl x509 -in server.crt -noout -text

Please note that the new certificate is signed by our CA, and also has the following useful properties:

    X509v3 extensions:
        X509v3 Key Usage: 
            Digital Signature, Non Repudiation, Key Encipherment, Data Encipherment
        X509v3 Basic Constraints: 
            CA:FALSE
        X509v3 Extended Key Usage: 
            TLS Web Server Authentication, TLS Web Client Authentication
Signature Algorithm: sha256WithRSAEncryption

Also note that the generated certificate is valid for both Server and Client purposes and has a X509v3 CRL Distribution Points extension that points to URI:http://myca.com/crl.pem: please change this value inside your openssl.conf before generating the CA certificate. This is where you’ll publish your CRL.

As an added bonus, you could also add SANs (Subject Alternative Names) to your certificate, if you like. This permits you to have cool certificates like wildcard domains, multiple domains and IP address on your certificates.

To add a SAN you can modify the last line of openssl.conf configuration file, so that you can include your SANs. For example:

...
[v3_req]
# To add SAN uncomment the # and personalize
subjectAltName=email:copy,DNS:www.host.com,DNS:host.com

and create your CSR and certificate like done above (but first remember to revoke or manually remove the certificate from certs.db or you’ll get the “ERROR:There is already a certificate for…” error):

# openssl req -new -key server.key -out server.csr -extensions 'v3_req' -config openssl.conf
# openssl ca -cert ca.crt -keyfile ca.key -in server.csr -out server.crt -config openssl.conf

To revoke a certificate (in this example is called 792FCB9AE9BBBFFAE33796CF3D1D0D7B6AF399DF.pem) you can simply do this (this will set the given certificate as revoked into the certs.db file):

# openssl ca -config openssl.conf -keyfile ca.key -cert ca.crt -revoke 792FCB9AE9BBBFFAE33796CF3D1D0D7B6AF399DF.pem -crl_reason unspecified
Using configuration from openssl.conf
Revoking Certificate 792FCB9AE9BBBFFAE33796CF3D1D0D7B6AF399DF.
Data Base Updated

After that you need to update the CRL with all the revoked certificates inside. Also, remember to refresh the CRL with the same command almost every default_crl_days (check openssl.conf) even if no certificates are revoked or your CRL will expire:

# openssl ca -config openssl.conf -keyfile ca.key -cert ca.crt -gencrl -updatedb -out crl.pem

At this poin you might want to arrange your OCSP responder with its key and certificate.

Please note that the configuration of OCSP Stapling or responder is out of scope in this article, we just realized how to create its certificates with OpenSSL. If you don’t need OCSP on your certificates, left commented out the authorityInfoAccess attribute in openssl.conf and skip this last step, btw I can tell you, as a testing purposes, how to create a OCSP test responder:

# openssl genrsa -out ocsp.key 2048
# openssl req -new -key ocsp.key -out ocsp.csr -extensions 'v3_req' -config openssl.conf
# openssl ca -cert ca.crt -keyfile ca.key -in ocsp.csr -out ocsp.crt -extensions ocsp -config openssl.conf

When you create the OCSP certificate, keep in mind that the common name must match the OCSP;URI.0 attribute defined into the [ocsp_info] section of your openssl.conf.

# openssl ocsp -index certs.db -port 9999 -rsigner ocsp.crt -rkey ocsp.key -CA ca.crt
ocsp: waiting for OCSP client connections...

And then, to test:

# openssl ocsp -issuer ca.crt -CAfile ca.crt -cert server.crt -url http://ocsp:9999
Response verify OK
server.crt: good
	This Update: May 13 15:10:17 2021 GMT

Now, we try to revoke the server certificate, just for test:

openssl ca -config openssl.conf -keyfile ca.key -cert ca.crt -revoke server.crt -crl_reason unspecified
Using configuration from openssl.conf
Adding Entry with serial number 2DE87D684C64D0BB4B23D0BC9959B8EB23AF932F to DB for /C=IT/ST=Italy/L=Rome/O=My org/OU=My Unit/CN=myserver/emailAddress=my@email.com
Revoking Certificate 2DE87D684C64D0BB4B23D0BC9959B8EB23AF932F.
Data Base Updated

We must also update our CRL and check if the revoked certificate is inserted into our CRL:

# openssl ca -config openssl.conf -keyfile ca.key -cert ca.crt -gencrl -updatedb -out crl.pem                            
Using configuration from openssl.conf
# openssl verify -crl_check -CAfile ca.crt -CRLfile crl.pem server.crt 
C = IT, ST = Italy, L = Rome, O = My org, OU = My Unit, CN = myserver, emailAddress = my@email.com
error 23 at 0 depth lookup: certificate revoked
error server.crt: verification failed

If we recheck now our OCSP responder:

openssl ocsp -issuer ca.crt -CAfile ca.crt -cert server.crt -url http://ocsp:9999 
Response verify OK
server.crt: revoked
	This Update: May 13 15:23:34 2021 GMT
	Reason: unspecified
	Revocation Time: May 13 15:22:14 2021 GMT

Finaly, the mission is complete!!!!

I spent hours getting this things done!! It’s now time to collect and share back to everybody. Bye!!! Ciao, Dino 🙂

24 Nov 20 Aumentare i due utenti contemporanei in desktop remoto su windows

Su quella merda di sistema inoperativo quale è winzozz di default ci si può collegare solo in due utenti contemporaneamente.

Ho trovato un modo per aumentare le sessioni, provando su windows server 2019. Lo enuncio qui senza sapere se funziona (come sempre su winblows):

Da Editor criteri di gruppo locali (gpedit.msc da utente amministratore):

Configurazione Computer
Componenti di Windows
Servizi Desktop remoto
Host sessione di Desktop remoto
Connessioni
Limita il numero di connessioni (attivare e inserire il numero)

Probabilmente in questo modo windoze dovrebbe aumentare il numero di utenti contemporanei in desktop remoto.

Testate e datemi feedback nei commenti, oppure chi sa dica come fare in modo migliore. Grazie.

28 Apr 20 Non usate Whatsapp (r), usate Telegram invece

Questa paginetta solo per consigliare a TUTTI di NON USARE whatsapp (r) e facebook (r) in generale ma Telegram.

Dal mio punto di vista Telegram è estremamente superiore in tutto, specialmente dal punto di vista della sicurezza, della tecnologia, della libertà di utilizzo da parte degli utenti e delle Aziende. Ad esempio l’API per creare i chat bot è gratuita e libera, cosa non vera sull’altra piattaforma. Non ha più senso continuare ad usare whatsapp.

Perchè devo pagare per inviare messaggi nel 2020? Perchè dovrei farlo tramite un’API tra l’altro proprietaria e non aperta???

Piu’ gente userà Telegram e meglio sarà per tutti, datemi retta, Telegram vince bene!! Provate per credere. Convincerete tutti gli amici e i parenti come ho fatto io.

09 Mar 20 Disquisizioni su errori procedurali in ambito enterprise riguardo alla generazione e all’implementazione dei certificati SSL X509

Breve (anzi no) premessa senza entrare troppo nei dettagli di natura tecnica spinta. In sostanza i certificati X509 possono essere di varia natura e formato ma tutti governati dallo standard X.509 (https://en.wikipedia.org/wiki/X.509) che e’ uno standard internazionale. Secondo come vengono richiesti e poi emessi dalla CA competente (Certification Authority) hanno delle proprietà specifiche, alcune obbligatorie ed altre che cambiano in base alle applicazioni.

La crittografia asimmetrica basasta su certificati X.509 permette la mutua autenticazione (il client verifica il server e viceversa), cripta il canale di comunicazione impedendo il “man in the middle” ovvero rende impossibile per un attore che non conosce le chivi private client e server di poter “sniffare” il traffico mettendosi in mezzo, e conferma la veridicita’ e inalterabilita’ del messaggio in transito, oltre a verificare in modo inequivocabile chi l’ha inviato.

Per generare un certificato vi è sempre necessità di utilizzare una chiave privata (che va sempre tenuta segreta in quanto essa e’ in grado tra l’altro di decifrare i messaggi!). Operativamente e’ possibile generare una nuova chiave privata qualora quella precedente venga compromessa, oppure se si vuole cambiarla per motivi di sicurezza in generale, o ancora se viene richiesto dalla CA competente. Esse possono essere inaccessibili (ad esempio immagazzinate all’interno di una smartcard, un token di autenticazione, un wallet, etc) oppure accessibili. Nel caso fossero accessibili possono essere cifrate (protette da passphrase) oppure in chiaro. In base alla tecnologia su cui e’ implementata la PKI (Public Key Infrastructure) le chiavi possono essere salvate in un file (protetto contro letture non abilitate), un database, etc, ma solitamente non e’ altro che un contenitore come ad esempio un PKCS#12, un PKCS#8, un KeyStore Java (JKS), un Wallet Oracle, IBM, etc, etc.
E’ necessario, come appena detto, utilizzare una private key per generare un nuovo certificato, e questo viene fatto mediante la generazione di una richiesta di certificazione (CSR: Certification Signing Request, anche conosciuto come PKCS#10) che va inoltrata alla CA competente. Sebbene sia possibile generarsi un certificato da soli (self signed certificate) questa NON va considerata buona prassi ma bisognerebbe sempre utilizzare un Ente Certificatore preposto allo scopo. Il PKCS#10 contiene tutte le informazioni che servono alla CA per poter emettere un certificato X.509 valido e verificare in seguito che il richiedente sia quello corretto e il certificato “faccia scopa” con la chiave privata (per mezzo della firma digitale apposta dal richiedente per mezzo della sua chiave privata). Infatti, la chiave privata e il certificato che ne deriva hanno SEMPRE lo stesso “modulo”, cosa MAI vera se il certificato NON deriva da quella chiave privata ma da un’altra. E’ quindi possibile verificare che un determinato certificato derivi da una particolare chiave privata. Da un certificato non e’ possibile ottenere, ovviamente, una chiave privata, altrimenti tutto sarebbe inutile.

Una volta generato il CSR e il conseguente certificato la chiave privata NON va assolutamente buttata ma conservata in modo sicuro e configurata dove serve: senza di essa il certificato sarà completamente inutile e bisognerà rigenerarne un altro con una nuova chiave privata.

A seconda delle varie applicazioni e’ necessario, come sappiamo, implementare e scambiarsi uno o piu’ certificati SSL. Le chiavi private NON si scambiano mai!
Per quello che ci interessa in questa istanza, possiamo identificare le seguenti caratteristiche:

CERTIFICATO SERVER
 |caso 1|–> INSTALLATO SU UN SERVER (apache, tomcat, bea, etc): viene esposto su un server per implementare, ad esempio, il protocollo TLS con le relative ciphersuite. Il server invia il proprio certificato in fase di handshake per poter essere riconosciuto dal client che effettua la richiesta. Configurato come tale ha sempre bisogno della relativa chiave privata (come detto non una a caso ma esattamente quella che e’ stata utilizzata per la generazione e la firma del CSR) ed infatti per le tecnologie basate su java viene conservato nel cosiddetto KeyStore (ad esempio su tomcat e’ puntato dall’attributo keystoreFile nel connettore).
 |caso 2|–> INSTALLATO SU UN CLIENT: il certificato server viene utilizzato dal client per considerare TRUSTED (viene data fiducia) al server in fase di handshake. In questo caso non vi e’ alcun bisogno della chiave privata e infatti chi gestisce il server e ce lo invia la manterra’ privata. Nelle tecnologie java questi certificati vengono inseriti nel cosiddetto TrustStore (come ad esempio il cacerts della JVM).

CERTIFICATO CLIENT
 |caso 3|–> INSTALLATO SU UN CLIENT (ad esempio un browser, ma piu’ solitamente un’applicazione come Apache Axis, un client di una API, un client webservice o un reverse proxy come apache per la sua componente client – guardare ad es. direttiva SSLProxyMachineCertificateFile): viene esposto su un client per implementare la mutua autenticazione. In tal caso il client viene configurato per pubblicare il suo certificato al server in fase di handshake per poter essere riconosciuto dal server. Se configurato come tale ha sempre bisogno della relativa chiave privata (come detto non una a caso ma esattamente quella che e’ stata utilizzata per la generazione e la firma del CSR). Anche in questo caso, come per un certificato server installato su un server (caso 1), il certificato e la relativa chiave privata vanno in un KeyStore (in questo caso non del middleware ma dell’applicazione).
 |caso 4|–> INSTALLATO SU UN SERVER: il certificato client viene utilizzato dal server per considerare TRUSTED (viene data fiducia) al client in fase di handshake, come succede per un certificato server installato su un client (caso 2). Anche in questo caso la chiave privata non serve perche’ chi ce la invia (il client) la mantiene privata. Su tecnologie java, anche in questo caso, il certificato va installato nel TrustStore (in questo caso solitamente dell’applicazione o della JVM).

In tutte e 4 le casistiche indicate, i certificati non vanno installati da soli ma sempre completi della catena di certificazione (detto Chain of Trust), ovvero insieme al certificato della CA che lo ha emesso e nel caso di una CA Intermedia vanno installati tutti i certificati delle varie CA fino a quello della ROOT CA (la prima della catena). Se c’e’ un ordine questo deve procedere dal certificato utente fino a quello della ROOT CA che va installato per ultimo.

Da questo ne conseguono i seguenti punti di interesse di operation:
1) il trustStore NON ha mai chiavi private al suo interno ma solo certificati della controparte da autenticare (se sono server avro’ i certificati dei client, se sono client avro’ i certificati dei server).
2) l’applicazione puo’ usare piu’ trustStore e se e’ scritta in java vince il trustStore cacerts dentro “jre/lib/security/”
3) il keyStore avra’ il certificato con relativa chiave privata e non avra’ i certificati della controparte.
4) l’inserimento nel trustore e nel keystore prevede l’inserimento di tutta la catena di certificazione, ovvero i certificati delle varie CA
5) le operazioni per richiedere alla CA un certificato server o uno client sono le medesime, ma la CA scolpirà all’interno del certificato lo scopo per cui esso viene rilasciato (solo client, solo server o client/server). Diventa quindi importante richiedere alla CA la giusta tipologia di certificato perche’ il server o il client possono/devono verificare il corretto scopo del certificato.
6) sono previste le 4 diverse configurazioni del client e del server indicate sopra. Queste si differenziano nel caso in cui devono solo trustare le controparti (sia essa client o server, quindi senza chiave privata, ovvero i casi 2 e 4) oppure nel caso in cui si debba implementare il servizio vero e proprio (sia esso client o server, con chiave privata, ovvero i casi 1 e 3), con o senza mutua autenticazione
7) se non e’ prevista la mutua autenticazione il client non ha mai bisogno di un keyStore (certificato con chiave privata) ma solo di un trustStore per verificare il server. Nel caso di alcuni middleware o applicazioni non serve neanche quest’ultimo.
8) per un server il discorso e’ opposto, ovvero il server ha sempre e comunque bisogno di un keyStore ma se non c’e’ mutua autenticazione non ha bisogno di un trustStore per verificare il client.
9) le applicazioni o i middleware client e server possono essere configurati e/o implementati per verificare nel modo piu’ disparato e piu’ o meno strettamente i certificati della controparte. Posso ad esempio ignorare che un certificato della controparte sia scaduto o posso comunque fidarmi del certificato della controparte a prescindere che esso sia trustato nel mio truststore e posso ignorare completamente gli attributi del certificato e fidarmi comunque. Oppure invece posso andare a leggere e controllare scrupolosamente e puntualmente il certificato della controparte e verificare, ad esempio, una o piu’ cose tra cui: il seriale del certificato, il suo ente certificatore, il suo scopo, la scadenza, la scadenza del certificato della CA, il CN con cui viene pubblicato, se e’ stato revocato dalla CA (su richiesta del richiedente perche’ magari e’ stata compromessa la private key, oppure dalla ca stessa perche’ magari non si fidano piu’ dell’algoritmo di firma o delle procedure di rilascio, etc), se gli attributi di scopo sono rispettati (solo server, solo client, client/server, solo CA, solo firma digitale, etc), se il certificato e’ distribuito per una lista di nomi (SAN) o per un nome solo e essi fanno scopa con il servizio, etc, etc, etc.

Ne consegue quindi che le configurazioni possono essere molto personalizzate e flessibili e testare tutte le casistiche possibili non e’ fattibile. Forse la cosa migliore e’ lavorare a livello di documentazione, specialmente sulle procedure del singolo progetto.

In linea di massima possiamo riassumere le seguenti macro procedure di operation per le casistiche indicate sopra. Essendoci diverse tecnologie le modalita’ operative sono molto diverse nella forma ma uguali nella sostanza:

DEVO IMPLEMENTARE UN SERVER:
1) genero una chiave privata o uso quella precedente se la CA me lo consente (soddisfando i requisiti dettati da CA, esempio RSA 2048 bit)
2) genero un CSR a partire dalla chiave al punto 1 impostando nella richiesta tutti i parametri corretti (CN, scopo server, OU corretto, stato, paese, etc)
3) invio il CSR alla CA di competenza
4) ottengo il certificato solo server oppure client/server dalla CA
5) imposto il mio certificato sul keystore del server di cui sono responsabile insieme alla chiave privata al punto 1 e insieme ai certificati delle CA che lo hanno emesso
6) invio il mio certificato e quello della CA alle controparti SENZA inviare la chiave privata.
SE DEVO ATTIVARE MUTUA AUTENTICAZIONE (OVVERO FORZARE LA VERIFICA DEL CERTIFICATO CLIENT DELLA CONTROPARTE) FARO’ ANCHE QUESTE:
7) richiedo il certificato della controparte
8) inserisco nel mio truststore client o server il certificato della controparte e lo rendo TRUSTED insieme alle loro CA
9) forzo sul middleware le verifiche sui certificati appena messi nel truststore o implemento dei blocchi piu’ restrittivi, ad esempio controllando bene i certificati delle controparti affinche’ rispettino i requisiti di sicurezza richiesti dal progetto

DEVO IMPLEMENTARE UN CLIENT:
  di norma non serve fare nulla se non e’ richiesta mutua autenticazione. In alcune tecnologie, come ad esempio quelle basate su java potrei dover comunque effettuare i punti 1 e 2 indicati sotto:
SE DEVO ATTIVARE MUTUA AUTENTICAZIONE (OVVERO FORZARE LA VERIFICA DEL CERTIFICATO SERVER DELLA CONTROPARTE):
1) ottengo il certificato server dalla controparte
2) in base al middleware e alla tecnologia lo considero trusted sul mio truststore
3) genero una chiave privata o uso quella precedente se la CA me lo consente (soddisfando i requisiti dettati da CA, esempio RSA 2048 bit)
4) genero un CSR a partire dalla chiave al punto 1 impostando nella richiesta tutti i parametri corretti (CN, scopo client, OU corretto, stato, paese, etc)
5) invio il CSR alla CA di competenza
6) ottengo il certificato solo client oppure client/server dalla CA
7) imposto il mio certificato sul keystore del client di cui sono responsabile insieme alla chiave privata al punto 1 e insieme ai certificati delle CA che lo hanno emesso
8) invio il mio certificato e quello della CA alle controparti SENZA inviare la chiave privata
9) forzo sul middleware o sull’applicazione le verifiche sui certificati appena messi nel truststore o implemento dei blocchi piu’ restrittivi, ad esempio controllando bene i certificati delle controparti affinche’ rispettino i requisiti di sicurezza richiesti dal progetto

La maggior parte degli errori, per esperienza, avviene a livello procedurale perche’ spesso chi effettua l’attivita’ non ha la chiara visibilita’ o competenza su tutto il “giro del fumo”, oppure perche’ le informazioni si perdono (ad esempio in caso di passaggio di consegne). Per lo stesso motivo, in caso di disservizio, diventa lungo anche per noi di TS identificare il problema, non conoscendo bene tutte le applicazioni possibili.

Gli errori piu’ frequenti, comunque, risultano essere:

1) un mio certificato (server o client) scade creando disservizio alle controparti;
2) un mio certificato (server o client) viene (ri)generato con le modalita’ non corrette rispetto ai requisiti di progetto creando disservizio alle controparti
3) un certificato (server o client) di una controparte scade e mi crea un disservizio;
4) un certificato (server o client) di una controparte viene (ri)generato con le modalita’ non corrette rispetto ai requisiti di progetto e mi crea un disservizio
5) (ri)genero un certificato e non lo invio alle controparti, appena entra in campo potrei creare disservizio alle controparti
6) una controparte (ri)genera un certificato e non me lo invia, appena entra in campo potrei avere un disservizio
7) potrei per errore inviare alle controparti un certificato sbagliato, magari vecchio o di un altro progetto creando disservizio alle controparti
8) potrei ricevere per errore da una controparte un certificato sbagliato, magari vecchio o di un altro progetto ottenendo un disservizio
9) potrei inviare un certificato corrotto
10) potrei ricevere un certificato corrotto
11) essendoci vari formati (JKS, PEM, DER, P12, PFX, etc) potrei inviare un certificato in un formato che non si aspettano
12) potrei ricevere un certificato in un formato che non mi aspetto

Ricapitolando quindi, sia che ottengo, sia che sto inviando un certificato, esso deve sempre:
1- essere in corso di validita’ (non scaduto)
2- rispettare i requisiti di progetto (CN giusto, formato giusto, CA giusta, SAN, scopo, paese, attributi, etc)
3- essere installato e configurato correttamente sul mio middleware, sulla mia applicazione o su quelle di tutte le controparti

Il caso 1 e’ facilissimo da verificare e da prevedere, basta scaricarsi il certificato e verificare la data di scadenza;
Per il caso 2 bisogna verificare che il certificato faccia scopa con una serie di regole dettate dal singolo progetto o dalla singola tecnologia, volendo e’ possibile verificarlo rispetto ad uno che precedentemente andava bene e far saltare all’occhio le eventuali differenze perche’ potrebbero provocare un probabile disservizio;
Anche per il punto 3 la modalita’ di verifica cambia in base alla tecnologia o al progetto: se si tratta di un server si potrebbe invocare il servizio e prendersi il certificato esposto e verificarlo con le specifiche del progetto o con le proprieta’ di base che ci aspetteremmo da quel certificato. Se c’e’ mutua autenticazione il server potrebbe non risponderci fino a che non gli inviamo un certificato client valido che lui considera attendibile. Se invece e’ un client non si puo’ verificare da remoto ma solo in locale sulla macchina conoscendo il path ed avendo i giusti privilegi di accesso.

Allo stato attuale è possibile preparare uno shell script che permette di verificare visivamente un certificato X509, sia locale che remoto, e di mostrare tutte le sue proprieta’ e la data di emissione e scadenza.

Da qui a scriptare per risolvere i punti 2 e 3 la vedo molto complicata perche’ i requisiti e le tecnologie sono tutte diverse…

Ho completamente tralasciato tutto quello che riguarda i protocolli e le ciphersuite perche’ quello e’ un altro capitolo e la disquisizione e’ gia’ troppo lunga!

Buon Certificato X509 a tutti!

28 Dic 19 How to encrypt and decrypt a text file with vim

I always use VIM any single day of my life starting from 1994, and I did not realize that it’s now possible to encrypt and decrypt files with it without using gnupg! This is one of the reasons why I love vim so much: there are always things that you can learn from it!
So, I’ll now show you how to use vim to encrypt and decrypt your text files.

We can start creating a new encrypted text file with the command below:

# vim -x encryptedfile.txt
Enter encryption key:
Enter same key again:

Once you’ve entered an encryption key (WARNING: don’t forget it or you will lose your clear text data forever!!!) you can use vim as always, write your clear text data, save and quit.

# file encryptedfile.txt
encryptedfile.txt: Vim encrypted file data
# cat encryptedfile.txt
VimCrypt~03!�-
�
��[�v��>P��(�%

So, your file is now encrypted. To recover access to your clear text data, just open the file back with vim using the correct passphrase you used to create your file:

# vim encryptedfile.txt
Need encryption key for "encryptedfile.txt"
Enter encryption key:

You could also decide to change your passphrase or encrypt a clear text file, using the :set key=pwd vim command, like this:

:set key=mystrongpasswordyou'llneverfind
:wq
# file encryptedfile.txt 
encryptedfile.txt: Vim encrypted file data

If you want to decrypt the file and save it clear text, just use an empty key with the :set key= command, after you opened the encrypted file with the correct passphrase:

:set key=
:wq
# file encryptedfile.txt
encryptedfile.txt: ASCII text

So, this way you can create an encrypted file protected with a passphrase, get read/write access to the encrypted file, decrypt the file to clear text and change the passphrase.

Hope you all will enjoy this like me!!

10 Dic 19 How to view files and directory name representration as a tree on linux

There is a cool command on linux that can be used to view directories and files in a cool tree way, this is called tree.

Try this one:

tree -shugaDFC --du

You hopefully get something formatted like this:

.
├── [root     root       40 Dec 10 11:38]  .font-unix/
├── [root     root       80 Dec 10 11:39]  .ICE-unix/
│   ├── [Debian-gdm Debian-gdm    0 Dec 10 11:38]  2040=
│   └── [dino     dino        0 Dec 10 11:39]  2530=
├── [dino     dino        0 Dec 10 11:51]  opensc-debug.log
├── [root     root       40 Dec 10 11:38]  pulse-PKdhtXMmr18n/
├── [root     root        0 Dec 10 11:38]  SemFetchAndIncSem
├── [dino     dino       60 Dec 10 11:39]  ssh-Lu1SMknjwYCh/
│   └── [dino     dino        0 Dec 10 11:39]  agent.2530=
├── [root     root      140 Dec 10 11:38]  systemd-private-6ca1b00e83794d86a258dafff95a5ade-apache2.service-LGtMHO/
│   └── [root     root       80 Dec 10 11:38]  tmp/
│       ├── [root     root        0 Dec 10 11:38]  access_log
│       └── [root     root        0 Dec 10 11:38]  error_log
├── [root     root      100 Dec 10 11:39]  systemd-private-6ca1b00e83794d86a258dafff95a5ade-bolt.service-uuY7ay/
│   └── [root     root       40 Dec 10 11:39]  tmp/
├── [root     root      100 Dec 10 11:38]  systemd-private-6ca1b00e83794d86a258dafff95a5ade-colord.service-8gsnRd/
│   └── [root     root       40 Dec 10 11:38]  tmp/
├── [root     root      100 Dec 10 11:39]  systemd-private-6ca1b00e83794d86a258dafff95a5ade-fwupd.service-6puu9X/
│   └── [root     root       40 Dec 10 11:39]  tmp/
├── [root     root      100 Dec 10 11:38]  systemd-private-6ca1b00e83794d86a258dafff95a5ade-minissdpd.service-BJBYoN/
│   └── [root     root       40 Dec 10 11:38]  tmp/
├── [root     root      100 Dec 10 11:38]  systemd-private-6ca1b00e83794d86a258dafff95a5ade-ModemManager.service-T2ih67/
│   └── [root     root       40 Dec 10 11:38]  tmp/
├── [root     root      100 Dec 10 11:38]  systemd-private-6ca1b00e83794d86a258dafff95a5ade-ntp.service-DWl6NV/
│   └── [root     root       40 Dec 10 11:38]  tmp/
├── [root     root      100 Dec 10 11:38]  systemd-private-6ca1b00e83794d86a258dafff95a5ade-rtkit-daemon.service-B5JIPO/
│   └── [root     root       40 Dec 10 11:38]  tmp/
├── [root     root      100 Dec 10 11:38]  systemd-private-6ca1b00e83794d86a258dafff95a5ade-systemd-resolved.service-N3OP1K/
│   └── [root     root       40 Dec 10 11:38]  tmp/
├── [root     root      100 Dec 10 11:38]  systemd-private-6ca1b00e83794d86a258dafff95a5ade-upower.service-1MLpQa/
│   └── [root     root       40 Dec 10 11:38]  tmp/
├── [dino     dino       40 Dec 10 12:38]  Temp-78a83a1b-0d23-4bb2-b176-e7ae54b4b2d6/
├── [dino     dino       40 Dec 10 12:38]  Temp-897559cc-50ea-4ac1-b4da-780a5864e32c/
├── [dino     dino       40 Dec 10 11:52]  Temp-a7dd7308-8df0-42b3-9188-6ce51c3da1de/
├── [root     root       40 Dec 10 11:38]  .Test-unix/
├── [dino     dino       40 Dec 10 11:39]  tracker-extract-files.1000/
├── [root     root       80 Dec 10 11:39]  .X11-unix/
│   ├── [Debian-gdm Debian-gdm    0 Dec 10 11:38]  X0=
│   └── [dino     dino        0 Dec 10 11:39]  X1=
└── [root     root       40 Dec 10 11:38]  .XIM-unix/

 2.0K used in 31 directories, 9 files

If you get an error like command not found: tree then you have to install the tree package. For example, on debian/ubuntu:

apt install tree

You can experiment with tree alone or using different switches.

06 Lug 18 How to setup xtables GeoIP for iptables on OpenWRT

I’m not racist, but sometimes you may need to keep some people out of your network based on its geographical region… in reality I’m referring to its public source IP address.

Requests are coming from the big internet, so you can check if the source IP of the peers that are trying to connect to your powerful OpenWRT Linux router are coming from a particular region and you may want to stop all those requests accordingly.

If you are using iptables and ip6tables (if you are on linux this is the standard) you can setup GeoIP based packet filtering with iptables: it’s an iptables extension that make use of the glorious and free MaxMind GeoLite Legacy Downloadable Database (that is now dying…).

On OpenWRT this is supported automatically, but generally your router does not have all the disk space to host the entire GeoLite GeoIP database. So, you need to prepare all the records of the geographical regions that you want to block on your firewall.

Take a linux workstation or server (your notebook, a raspberry pi you own always on, one of your client’s server… better not IMHO…) and run those commands:

root@firegate2:~# mkdir /tmp/temp
root@firegate2:~# cd /tmp/temp
root@firegate2:/tmp/temp# /usr/share/xt_geoip/xt_geoip_dl
–2018-07-05 23:54:40– http://geolite.maxmind.com/download/geoip/database/GeoIPv6.csv.gz
Risoluzione di geolite.maxmind.com (geolite.maxmind.com)… 104.16.37.47, 104.16.38.47, 2400:cb00:2048:1::6810:262f, …
Connessione a geolite.maxmind.com (geolite.maxmind.com)|104.16.37.47|:80… connesso.
Richiesta HTTP inviata, in attesa di risposta… 200 OK
Lunghezza: 1715246 (1,6M) [application/octet-stream]
Salvataggio in: “GeoIPv6.csv.gz”

GeoIPv6.csv.gz 100%[================================================================>] 1,64M –.-KB/s in 0,1s

2018-07-05 23:54:40 (10,9 MB/s) – “GeoIPv6.csv.gz” salvato [1715246/1715246]

–2018-07-05 23:54:40– http://geolite.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip
Riutilizzo della connessione esistente a geolite.maxmind.com:80.
Richiesta HTTP inviata, in attesa di risposta… 200 OK
Lunghezza: 2540312 (2,4M) [application/zip]
Salvataggio in: “GeoIPCountryCSV.zip”

GeoIPCountryCSV.zip 100%[================================================================>] 2,42M 11,3MB/s in 0,2s

2018-07-05 23:54:40 (11,3 MB/s) – “GeoIPCountryCSV.zip” salvato [2540312/2540312]

TERMINATO –2018-07-05 23:54:40–
Tempo totale: 0,4s
Scaricati: 2 file, 4,1M in 0,4s (11,1 MB/s)
Archive: GeoIPCountryCSV.zip
inflating: GeoIPCountryWhois.csv
root@firegate2:/tmp/temp#
root@firegate2:/tmp/temp# /usr/share/xt_geoip/xt_geoip_build -D . *.csv
209370 entries total
0 IPv6 ranges for A1 Anonymous Proxy
32 IPv4 ranges for A1 Anonymous Proxy
0 IPv6 ranges for A2 Satellite Provider
36 IPv4 ranges for A2 Satellite Provider
3 IPv6 ranges for AD Andorra
26 IPv4 ranges for AD Andorra
51 IPv6 ranges for AE United Arab Emirates
302 IPv4 ranges for AE United Arab Emirates
… and continues …
11 IPv6 ranges for ZM Zambia
64 IPv4 ranges for ZM Zambia
14 IPv6 ranges for ZW Zimbabwe
59 IPv4 ranges for ZW Zimbabwe
root@firegate2:/tmp/temp#

The script /usr/share/xt_geoip/xt_geoip_build it’s part of xtables-addons package that you may or may not find on your distribution. Search on google for that.

This will create LE and BE directories. Now you want to extract only the geo regions that you need (ex: CN,UA,TW,VN,VG,KP,VI,KR), like that:

root@firegate2:/tmp/temp# du -csh BE/CN.iv? BE/UA.iv? BE/TW.iv? BE/VN.iv? BE/VG.iv? BE/KP.iv? BE/VI.iv? BE/KR.iv? LE/CN.iv? LE/UA.iv? LE/TW.iv? LE/VN.iv? LE/VG.iv? LE/KP.iv? LE/VI.iv? LE/KR.iv?
36K BE/CN.iv4
48K BE/CN.iv6
24K BE/UA.iv4
16K BE/UA.iv6
8,0K BE/TW.iv4
4,0K BE/TW.iv6
4,0K BE/VN.iv4
4,0K BE/VN.iv6
4,0K BE/VG.iv4
4,0K BE/VG.iv6
4,0K BE/KP.iv4
0 BE/KP.iv6
4,0K BE/VI.iv4
4,0K BE/VI.iv6
8,0K BE/KR.iv4
4,0K BE/KR.iv6
36K LE/CN.iv4
48K LE/CN.iv6
24K LE/UA.iv4
16K LE/UA.iv6
8,0K LE/TW.iv4
4,0K LE/TW.iv6
4,0K LE/VN.iv4
4,0K LE/VN.iv6
4,0K LE/VG.iv4
4,0K LE/VG.iv6
4,0K LE/KP.iv4
0 LE/KP.iv6
4,0K LE/VI.iv4
4,0K LE/VI.iv6
8,0K LE/KR.iv4
4,0K LE/KR.iv6
352K totale

So, in this case we will need 352 Kb of router disk space. After we created the /usr/share/xt_geoip/BE/ and /usr/share/xt_geoip/LE/ directories on our router’s filesystem:

root@dam2ktplinkrouter:~# mkdir -p /usr/share/xt_geoip/BE /usr/share/xt_geoip/LE

We are going to copy those files on our OpenWRT router:

root@firegate2:/tmp/temp# scp LE/CN.iv? LE/UA.iv? LE/TW.iv? LE/VN.iv? LE/VG.iv? LE/KP.iv? LE/VI.iv? LE/KR.iv? root@192.168.10.1:/usr/share/xt_geoip/LE
root@192.168.10.1’s password:
CN.iv4 100% 35KB 109.8KB/s 00:00
CN.iv6 100% 47KB 76.0KB/s 00:00
UA.iv4 100% 23KB 108.4KB/s 00:00
UA.iv6 100% 15KB 87.9KB/s 00:00
TW.iv4 100% 4704 47.5KB/s 00:00
TW.iv6 100% 3104 77.8KB/s 00:00
VN.iv4 100% 3888 98.9KB/s 00:00
VN.iv6 100% 3584 87.9KB/s 00:00
VG.iv4 100% 536 40.1KB/s 00:00
VG.iv6 100% 224 20.0KB/s 00:00
KP.iv4 100% 40 3.9KB/s 00:00
KP.iv6 100% 0 0.0KB/s 00:00
VI.iv4 100% 392 30.6KB/s 00:00
VI.iv6 100% 160 14.4KB/s 00:00
KR.iv4 100% 8128 105.8KB/s 00:00
KR.iv6 100% 3616 87.0KB/s 00:00
root@firegate2:/tmp/temp# scp BE/CN.iv? BE/UA.iv? BE/TW.iv? BE/VN.iv? BE/VG.iv? BE/KP.iv? BE/VI.iv? BE/KR.iv? root@192.168.10.1:/usr/share/xt_geoip/BE/
root@192.168.10.1’s password:
CN.iv4 100% 35KB 114.4KB/s 00:00
CN.iv6 100% 47KB 66.0KB/s 00:00
UA.iv4 100% 23KB 115.2KB/s 00:00
UA.iv6 100% 15KB 74.9KB/s 00:00
TW.iv4 100% 4704 93.8KB/s 00:00
TW.iv6 100% 3104 75.7KB/s 00:00
VN.iv4 100% 3888 108.8KB/s 00:00
VN.iv6 100% 3584 76.2KB/s 00:00
VG.iv4 100% 536 40.3KB/s 00:00
VG.iv6 100% 224 20.0KB/s 00:00
KP.iv4 100% 40 4.1KB/s 00:00
KP.iv6 100% 0 0.0KB/s 00:00
VI.iv4 100% 392 33.1KB/s 00:00
VI.iv6 100% 160 15.4KB/s 00:00
KR.iv4 100% 8128 111.1KB/s 00:00
KR.iv6 100% 3616 71.8KB/s 00:00
root@firegate2:/tmp/temp#

OK, now we have our pieces of geo ip informations. We now need to install the iptables-mod-geoip from the LuCI web interface (or by hand if you like).
Now you can create your Firewall Traffic Rules. Go to Network -> Firewall -> Traffic Rules on the router’s LuCI web interface and add a custom traffic rule. In my case I created 2 that I called “CinamerdaMuoriUDPeTCP” and “CinamerdaMuoriICMP”, the first to block TCP and UDP and the second to block ICMP traffic.

After that you can setup your custom rule setting your protocol and address families, set “source zone” to WAN, “destination zone” to “Any zone (forward)”, action to DROP, and the “Extra arguments” field like this:

-m geoip –source-country CN,UA,TW,VN,VG,KP,VI,KR

You can check the image below.

OpenWRT Firewall geoip example

Now you can say hello to most chinaspammers and something like that, but don’t abuse, this is not ethic if you set up this on a server that offers some sort of public service.

01 Gen 16 Buon anno nuovo!

Auguri a tutti!
Buon anno nuovo!

28 Nov 15 How to enable HTML5 video playback in firefox

If you use Mozilla Firefox and you want to view video streaming with HTML5 embedded players, you may need to enable some video functionality into the firefox configuration.
For some reason obscure to me Mozilla Firefox will not play some HTML5 based video streaming, and the embedded player will probably fall back to Adobe Flash based streaming (that is what I don’t want since it’s closed source and it’s a very insecure application).

For example, youtube has a HTML5 based player that you could choose to use instead of flv. You can verify and enable HTML5 based streaming functionality of your browser navigating to https://www.youtube.com/html5.

In my case (Firefox 64 bit on Linux Debian) the tabs “Media Source Extensions”, “MSE & H.264” and “MSE & WebM VP9” are disabled by default.

If you want to enable those functionalities simply write “about:config” into the firefox navigation bar.
You will be alerted to pay attention to not modify things or your warranty will be broken.
Just ignore the warning and proceed.

Now, if you did not already, switch the following configuration parameters to true:

media.fragmented-mp4.exposed
media.fragmented-mp4.ffmpeg.enabled
media.fragmented-mp4.gmp.enabled
media.mediasource.webm.enabled
media.mediasource.enabled

If you try to refresh the HTML5 based youtube player, you should hopefully have all video streaming tabs ready and enabled.
If you want, you can now switch the youtube default player to HTML5.