Getting Self Signed Cert to work with Home Assistant in Docker - docker

I am running HA in a docker container. I have created a wildcard self-signed cert that I use elsewhere within my homelab. But I cannot get it to work within HA. Here is how I created my cert using openSSL
Create CA - Root Key
openssl genrsa -aes256 -out ca-key.pem 4096
Create Request
openssl req -new -x509 -sha256 -days 3650 -key ca-key.pem -out ca.pem
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:OH
Locality Name (eg, city) []:Cortland
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Real World Developers
Organizational Unit Name (eg, section) []:Internal
Common Name (e.g. server FQDN or YOUR name) []:RWD.com
Email Address []:realworlddevs#outlook.com
Create Server Cert Signing Request
create key
openssl genrsa -out cert-key.pem 4096
create request
openssl req -new -sha256 -subj "/CN=RealWorldDevelopers" -key cert-key.pem -out cert.csr (subject=anything)
create config
echo "subjectAltName=DNS:*.RWD.com,IP:192.168.50.10" >> extfile.cnf (powershell will at BOM - need to open with notepad++ and set to UTF8)
create cert
openssl x509 -req -sha256 -days 3650 -in cert.csr -CA ca.pem -CAkey ca-key.pem -out cert.pem -extfile extfile.cnf -CAcreateserial
I am also running Pi-Hole as my local DNS. Without the cert, my DNS routes to ha.rwd.com within my homelab just fine.
My configuration.yaml file contain the http node like so
# TLS Certs
http:
ssl_certificate: /config/fullchain.pem
ssl_key: /config/cert-key.pem
Spacing in the config is correct. The certs are in the config folder within the container.
Yet in my logs, i still get this:
2022-09-12 18:55:41.931 ERROR (MainThread) [homeassistant.setup] Error during setup of component http
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/components/http/init.py", line 355, in _create_ssl_context
context.load_cert_chain(self.ssl_certificate, self.ssl_key)
ssl.SSLError: [SSL] PEM lib (_ssl.c:3874)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/setup.py", line 235, in _async_setup_component
result = await task
File "/usr/src/homeassistant/homeassistant/components/http/init.py", line 180, in async_setup
await server.async_initialize(
File "/usr/src/homeassistant/homeassistant/components/http/init.py", line 272, in async_initialize
self.context = await self.hass.async_add_executor_job(
File "/usr/local/lib/python3.10/concurrent/futures/thread.py", line 58, in run
result = self.fn(*self.args, **self.kwargs)
File "/usr/src/homeassistant/homeassistant/components/http/init.py", line 358, in _create_ssl_context
raise HomeAssistantError(
homeassistant.exceptions.HomeAssistantError: Could not use SSL certificate from /config/fullchain.pem: [SSL] PEM lib (_ssl.c:3874)
2022-09-12 18:55:41.933 ERROR (MainThread) [homeassistant.setup] Unable to set up dependencies of api. Setup failed for dependencies: http
2022-09-12 18:55:41.935 ERROR (MainThread) [homeassistant.setup] Setup failed for api: (DependencyError(...), 'Could not setup dependencies: http')
2022-09-12 18:55:41.936 ERROR (MainThread) [homeassistant.setup] Unable to set up dependencies of auth. Setup failed for dependencies: http
2022-09-12 18:55:41.936 ERROR (MainThread) [homeassistant.setup] Setup failed for auth: (DependencyError(...), 'Could not setup dependencies: http')

Home Assistant in a docker container, so u must add the path of certs' directory to docker by adding mount:
Commandline arg:
--mount type=bind,source=/certdirectory,target=/config/ssl
Docker Compose:
volumes:
- type: bind
source: /certdirectory
target: /config/ssl
Or use Portainer GUI (must install)
Then modify the configuration.yaml:
http:
ssl_certificate: /config/ssl/fullchain.pem
ssl_key: /config/ssl/cert-key.pem

Related

2 way Secured Mosquitto MQTT error

I'm new to MQTT. I create a mosquitto broker with ssl and connect successfully. My commands to create certificates as:
openssl req -new -x509 -days durations -keyout mqtt_ca.key -out mqtt_ca.crt
openssl genrsa -des3 -out mqtt_server.key size_bits
openssl req -out mqtt_server.csr -key mqtt_server.key -new
openssl x509 -req -in mqtt_server.csr -CA mqtt_ca.crt -CAkey mqtt_ca.key -CAcreateserial -out mqtt_server.crt -days durations*
In mosquitto.conf:
port 8883
cafile your_path/mqtt_ca.crt
certfile your_path/mqtt_server.crt
keyfile your_path/mqtt_server.key
require_certificate false
tls_version tlsv1.1
But it is just one way connection. I want to set `require_certificate true but I don't know how to create client certificates and modify mosquitto.conf. Please show me how to do that. Thank you so much!
Creating a Certificate Authority is too detailed to go into here, but there are plenty of examples online e.g There are many examples of how to create your own Certificate Authority (CA) online e.g.
https://jamielinux.com/docs/openssl-certificate-authority/
For the broker certificate the CN should match the host name of the machine running the broker.
For client certificates the CN can be anything you want.
The only changes to the mosquitto.conf file will be to make sure the cafile entry points to the CA certificate you generate at the start of the instructions for setting up the CA.
If you want to enforce require_certificate true then you should probably also look at use_identity_as_username true as well to user the CN from the client certificate as the username when matching against ACLs

Error In Push Notification on Distribution

I have implement the push notification after create the ck.pem file on development end. But when i create on distribution end then we check the ck.pem file is correct or not.I have error show below:-
pksinghs-Mac-mini:SchoolPush pksingh$ php /Users/pksingh/Desktop/SchoolPush/simplepush.php
Warning: stream_socket_client(): SSL operation failed with code 1. OpenSSL Error messages:
error:14094416:SSL routines:SSL3_READ_BYTES:sslv3 alert certificate unknown in /Users/pksingh/Desktop/SchoolPush/simplepush.php on line 21
Warning: stream_socket_client(): Failed to enable crypto in /Users/pksingh/Desktop/SchoolPush/simplepush.php on line 21
Warning: stream_socket_client(): unable to connect to ssl://gateway.push.apple.com:2195 (Unknown error) in /Users/pksingh/Desktop/SchoolPush/simplepush.php on line 21
Failed to connect: 0
pksinghs-Mac-mini:SchoolPush pksingh$
i have ck.pem file and pushnofication.php in same folder on desktop.
Can anybody help me.
Find the tutorial for how to create certificate and implement notification from below link
https://www.raywenderlich.com/123862/push-notifications-tutorial
you can use below command to create certificate
so there are something wrong in creating distribution certificate
Use below command to create certificate
openssl x509 -in aps_production.cer -inform der -out PushChatCert.pem
openssl pkcs12 -nocerts -out PushChatKey.pem -in Certificates_dist.p12
cat PushChatCert.pem PushChatKey.pem > ck_dist.pem
openssl s_client -connect gateway.push.apple.com:2195 -cert PushChatCert.pem -key PushChatKey.pem
where
aps_production.cer = downloaded from developer apple
Certificates_dist.p12 = Exported from your keychain after installing aps_production.cer

Verify return code: 20 (unable to get local issuer certificate) while creating push notification P EM file

I am creating PEM file for Production APNS , and i have done this several time before .
But i am facing an error on terminal while testing my PEm file from below command :
$ openssl s_client -connect gateway.push.apple.com:2195
-cert myCert.pem -key myKey.pem
It gives me :
Verify return code: 20 (unable to get local issuer certificate)
as response.
I have tried so many times but did not identify the problem .
May be it is because of my distribution certificates created on diffrent Mac .
But i am not sure .
Any help suggestion will be helpfull.
The developer link asks to include -CAfile server-ca-cert.pem, which does'nt work either.
All other options of indicating the CAfile gave me errors like 'unable to load certificate'.
The below actually worked for me after trying other options.
openssl s_client -connect gateway.push.apple.com:2195
-cert myCert.pem -key myKey.pem -CAfile entrust_2048_ca.cer
This solution gives 'Verify return code: 0 (ok)'.
On an additional note: You can also specify the .key file as the -key value & it will work too i.e. something like, ref here
openssl s_client -connect gateway.push.apple.com:2195 -cert myCert.pem -key myprivatekey.key -CAfile entrust_2048_ca.cer
You need to give a CA certificate as CAfile commandline argument to s_client. The trusted root certificate for the push servers is the Entrust CA (2048) root certificate which you can download from Entrust's site.
$ openssl s_client -connect gateway.push.apple.com:2195
-cert myCert.pem -key myKey.pem -CAfile entrust_2048_ca.cer
For more information and other possible reasons, please, check Apple developer guide Troubleshooting Push Notifications.

AFNetworking 2.2 SSL pinning with self-signed certificate

I want to prevent my app/server communication from a MITM attack so I am trying to setup SSL pinning, but I am having problems getting it working with AFNetworking 2.2, using a self-signed certificate. I think it's mostly a problem with how I am generating the certificate.
I first tried generating a self-signed certificate according to these instructions:
Generating the private key:
sudo openssl genrsa -des3 -out server.key 2048
Generating the Signing Request, and using the domain name when asked for the Common Name:
sudo openssl req -new -key server.key -out server.csr
Generating the certificate:
sudo openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
Finally, converting it to der format (since AFNetworking requires it)
sudo openssl x509 -outform der -in server.crt -out server.der
The server is Ubuntu 12.04, running ngninx+passenger to serve up a Rails 4 app. Here is the bit of my nginx server config to turn on SSL:
server {
listen 80;
listen 443;
server_name myapp.com;
passenger_enabled on;
root /var/www/myapp/current/public;
rails_env production;
ssl on;
ssl_certificate /etc/nginx/ssl/server.crt;
ssl_certificate_key /etc/nginx/ssl/server.key;
}
After restarting nginx, downloading the der file, adding it to my project, and renaming it "server.cer" (since AFNetworking requires the certificate to use the .cer extension), I use this code to turn on SSL pinning for my AFHTTPSessionManager subclass:
client.securityPolicy = [AFSecurityPolicy
policyWithPinningMode:AFSSLPinningModeCertificate];
Then, with the first request to the server AFNetworking attempts to verify that the "trust is valid in the AFServerTrustIsValid function:
static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) {
SecTrustResultType result = 0;
OSStatus status = SecTrustEvaluate(serverTrust, &result);
NSCAssert(status == errSecSuccess, #"SecTrustEvaluate error: %ld", (long int)status);
return (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
}
If I put a breakpoint at the return, I can see that the result is always kSecTrustResultRecoverableTrustFailure.
If I skip the AFServerTrustIsValid function by setting allowInvalidCertificates to YES on the security policy, then the request succeeds. But I don't really want to allow invalid certificates if I don't have to.
Back to the drawing board, this SO question lead me to this tutorial on creating a self-signed cert with also creating a CA. I setup my openssl.cnf file like so:
[ req ]
default_md = sha1
distinguished_name = req_distinguished_name
[ req_distinguished_name ]
countryName = United Kingdon
countryName_default = UK
countryName_min = 2
countryName_max = 2
localityName = Locality
localityName_default = London
organizationName = Organization
organizationName_default = Eric Organization
commonName = Common Name
commonName_max = 64
[ certauth ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer:always
basicConstraints = CA:true
crlDistributionPoints = #crl
[ server ]
basicConstraints = CA:FALSE
keyUsage = digitalSignature, keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
nsCertType = server
subjectAltName = DNS:myapp.com
crlDistributionPoints = #crl
[ crl ]
URI=http://testca.local/ca.crl
And then used these commands to generate everything. First the CA stuff:
sudo openssl req -config ./openssl.cnf -newkey rsa:2048 -nodes -keyform PEM -keyout ca.key -x509 -days 3650 -extensions certauth -outform PEM -out ca.cer
Then again the server's private key:
sudo openssl genrsa -out server.key 2048
The signing request:
sudo openssl req -config ./openssl.cnf -new -key server.key -out server.req
The certificate:
sudo openssl x509 -req -in server.req -CA ca.cer -CAkey ca.key -set_serial 100 -extfile openssl.cnf -extensions server -days 365 -outform PEM -out server.cer
And finally the der file:
sudo openssl x509 -outform der -in server.cer -out stopcastapp.com.der
When I update and restart nginx,, download and add the server.der to my project (making sure to rename it to server.cer and to reset the Simulator), I get the same exact result.
The dreaded kSecTrustResultRecoverableTrustFailure rears its ugly head again.
What am I doing wrong? Am I like WAY off on how this all works, or do I need to tweak just one little thing to get it all working? If you could help in any way I would really, really appreciate it (I've been on this problem for two days now). Thanks!
Somewhere in your code you need to specify this, or something similar. You need to tell the code to accept invalid certificates (AKA self signed).
self.allowsInvalidSSLCertificate = YES;

Creating p12 iOS developer certificate on Windows - error in last step

So, I've been looking around a lot of how to create a p12 file for iPhone development, and I think I'm doing exactly as I am supposed to, but at the last step I get some errors that are more or less impossible to decipher.
I am running Windows 7, and these are the steps I do:
1) Create the private key. I do this by running this command (cmd is opened in Administrator mode):
openssl genrsa -out mykey.key 2048
2) Create the CSR file
openssl req -new -key mykey.key -out developer_identify.csr
3) Upload the csr file to the iPhone dev site. Here I do the following:
Click on menu Identifiers --> App IDs, select the correct App ID, click Edit, click Create Certificate, click Continue, select the CSR-file created above and proceed. Wait for the site to tell me its all OK, and then download the *aps_development.cer* file.
4) Create the PEM file:
openssl x509 -in aps_development.cer -inform DER -out
developer_identity.pem -outform PEM
5) And lastly, create the p12 file (and this is where it fails):
openssl pkcs12 -export -inkey mykey.key -in developer_identity.pem
-out iphone_dev.p12
The output after the last command:
Loading 'screen' into random state - done
Enter Export Password:
Verifying - Enter Export Password:
8216:error:060740A0:lib(6):func(116):reason(160):NA:0:
8216:error:23077073:lib(35):func(119):reason(115):NA:0:
8216:error:2306C067:lib(35):func(108):reason(103):NA:0:
8216:error:23073067:lib(35):func(115):reason(103):NA:0:
The p12 file is 0 bytes.
The PEM file looks alright, starts with
-----BEGIN CERTIFICATE-----
then a lot of jibberish and then ends with
-----END CERTIFICATE-----

Resources