Stuck with luasec Lua secure socket - lua

This example code fails:
require("socket")
require("ssl")
-- TLS/SSL server parameters
local params = {
mode = "server",
protocol = "sslv23",
key = "./keys/server.key",
certificate = "./keys/server.crt",
cafile = "./keys/server.key",
password = "123456",
verify = {"peer", "fail_if_no_peer_cert"},
options = {"all", "no_sslv2"},
ciphers = "ALL:!ADH:#STRENGTH",
}
local socket = require("socket")
local server = socket.bind("*", 8888)
local client = server:accept()
client:settimeout(10)
-- TLS/SSL initialization
local conn,emsg = ssl.wrap(client, params)
print(emsg)
conn:dohandshake()
--
conn:send("one line\n")
conn:close()
request
https://localhost:8888/
output
error loading CA locations ((null))
lua: a.lua:25: attempt to index local 'conn' (a nil value)
stack traceback:
a.lua:25: in main chunk
[C]: ?
Not very much info. Any idea how to trace down to the problem ?
Update
Got this now: the cafile parameter is not necessary for server mode:
local params = {
mode = "server",
protocol = "sslv23",
key = "./keys/server.key",
certificate = "./keys/server.crt",
password = "123456",
options = {"all", "no_sslv2"},
ciphers = "ALL:!ADH:#STRENGTH",
}

LuaSec is a binding for OpenSSL, so the error you are getting (error loading CA locations) means that the OpenSSL library cannot read your CA files. Are you sure they are in the current directory and with proper permissions?
EDIT: According to LuaSec sources, it currently uses only the PEM format for private key. Ensure that the private key is stored as PEM, not DER.

CAFile contains the set of certificates (.crt) that your server or client trust. You put the key (.key).

Related

Trying to set up a mail server in OpenBSD: doveadm auth login fails

I set up an OpenBSD 7.0 instance on Vultr in order to get a mail server running with Dovecot and OpenSMTPD. I (mostly) followed the instructions here and here and a bit here.
I set it up to use with virtual mail, creating files in '/etc/mail/virtual' and '/etc/mail/credentials' with a single virtual user: 'user#domain.ca::vmail:2000:2000:/var/vmail/domain.ca/user::userdb_mail=maildir:/var/vmail/domain.ca/user'
I created the encrypted password with 'smtpctl encrypt' and pasted it where it should be in the credentials file.
However, running 'doveadm auth login user#domain.ca' fails.
In /var/log/maillog I get:
Jan 25 14:06:58 vultrBSD dovecot: auth-worker(165): conn unix:auth-worker (pid=44111,uid=518): auth-worker<1>: bsdauth(user#domain.ca): unknown user
Jan 25 14:06:58 vultrBSD dovecot: auth: passwd-file(user#domain.ca): Password mismatch
I know the password is correct, and I tried changing it and pasting in a new one that I created with 'smtpctl encrypt', but still the same error. The '/etc/mail/credentials' file is set to 0440 and owned by _smtpd:_dovecot. Even temporarily setting it to 0777 doesn't work.
I can send mail to the server from another account, I see that is shows up in '/var/vmail/domain.ca/user/new' but I am unable to connect my Thunderbird client to the server. Attempting to set up a new mail account in Thunderbird doesn't seem to work, Thunderbird rejects the password (although it does detect the correct protocols and ports, IMAP/SMTP).
Here is the local.conf file in /etc/dovecot:
auth_debug_passwords = yes
auth_mechanisms = plain
first_valid_uid = 2000
first_valid_gid = 2000
mail_location = maildir:/var/vmail/%d/%n
mail_plugin_dir = /usr/local/lib/dovecot
managesieve_notify_capability = mailto
managesieve_sieve_capability = fileinto reject envelope encoded-character vacation subaddress comparator-i;ascii-numeric relational regex imap4flags copy include variables body enotify environment mailbox date index ihave duplicate mime foreverypart extracttext imapsieve vnd.dovecot.imapsieve
mbox_write_locks = fcntl
mmap_disable = yes
namespace inbox {
inbox = yes
location =
mailbox Archive {
auto = subscribe
special_use = \Archive
}
mailbox Drafts {
auto = subscribe
special_use = \Drafts
}
mailbox Junk {
auto = subscribe
special_use = \Junk
}
mailbox Sent {
auto = subscribe
special_use = \Sent
}
mailbox Trash {
auto = subscribe
special_use = \Trash
}
prefix =
}
plugin {
imapsieve_mailbox1_before = file:/usr/local/lib/dovecot/sieve/report-spam.sieve
imapsieve_mailbox1_causes = COPY
imapsieve_mailbox1_name = Junk
imapsieve_mailbox2_before = file:/usr/local/lib/dovecot/sieve/report-ham.sieve
imapsieve_mailbox2_causes = COPY
imapsieve_mailbox2_from = Junk
imapsieve_mailbox2_name = *
sieve = file:~/sieve;active=~/.dovecot.sieve
sieve_global_extensions = +vnd.dovecot.pipe +vnd.dovecot.environment
sieve_pipe_bin_dir = /usr/local/lib/dovecot/sieve
sieve_plugins = sieve_imapsieve sieve_extprograms
}
protocols = imap sieve
service imap-login {
inet_listener imaps {
port = 993
}
}
service managesieve-login {
inet_listener sieve {
port = 4190
}
inet_listener sieve_deprecated {
port = 2000
}
}
ssl_cert = </etc/ssl/domain.ca.fullchain.pem
ssl_key = </etc/ssl/private/domain.ca.key
userdb {
args = username_format=%u /etc/mail/credentials
driver = passwd-file
name =
}
passdb {
args = scheme=CRYPT username_format=%u /etc/mail/credentials
driver = passwd-file
name =
}
protocol imap {
mail_plugins = " imap_sieve"
}
Has anyone else experienced this and know of a fix?
Thanks.
Hashed strings, including passwords, typically use several layers besides the base hashing algorithm. Two different implementations (dovecot vs smtpd) using the same hashing algorithm will output two different hashes given the same input (password.)
This is due to what is called salt and pepper. Salt is a randomly generated string usually based on some user data as the seed. This salt is then inserted into the password in a way dictated by the implementation (dovecot or smtpd) before hashing the password.
Similarly, pepper is a string dictated by the implementation and inserted into the password before hashing. This combination of salting and peppering creates a unique hash per implementation which makes storing passwords safer. This makes it so that a cracker can't easily compare hashes from several sites or programs to crack user passwords and break into all instances of that password simultaneously.
This is why you can't reuse a password hash stored by one program to unlock the same password when used by another program. Even if both programs use identical hashing algorithms.
The fix should be to set up the credentials individually for each program and not reuse each other's hashes.

MQTT block specific client from connecting via TLS

I have MQTT (VerneMQ) setup with TLS authentication. Also I have setup frequent pulling
CRL (certificate revocation list) from CA (Private). I am able to revoke the specific client certificate to blocking it from connecting to MQTT.
There is one certificate which is shared & I don't want to revoke but also don't want client to be able to authenticate with MQTT. Following is my configuration
DOCKER_VERNEMQ_ACCEPT_EULA = "yes"
MY_POD_NAME = "vernemq"
DOCKER_VERNEMQ_KUBERNETES_APP_LABEL = "vernemq"
DOCKER_VERNEMQ_LOG__CONSOLE__LEVEL = "debug"
DOCKER_VERNEMQ_KUBERNETES_LABEL_SELECTOR = "app=vernemq"
DOCKER_VERNEMQ_LISTENER__TCP__ALLOWED_PROTOCOL_VERSIONS = "3,4,5"
DOCKER_VERNEMQ_ALLOW_ANONYMOUS = "on"
DOCKER_VERNEMQ_KUBERNETES_INSECURE = "1"
DOCKER_VERNEMQ_MAX_ONLINE_MESSAGES = "-1"
DOCKER_VERNEMQ_MAX_OFFLINE_MESSAGES = "-1"
DOCKER_VERNEMQ_MAX_INFLIGHT_MESSAGES = "0"
DOCKER_VERNEMQ_LISTENER__TCP__DEFAULT = "0.0.0.0:1883"
DOCKER_VERNEMQ_LISTENER__SSL__DEFAULT = "0.0.0.0:8883"
DOCKER_VERNEMQ_LISTENER__WS__DEFAULT = "0.0.0.0:8080"
DOCKER_VERNEMQ_LISTENER__HTTP__METRICS = "0.0.0.0:8888"
DOCKER_VERNEMQ_LISTENER__HTTP__DEFAULT = "0.0.0.0:8888"
DOCKER_VERNEMQ_LISTENER__SSL__REQUIRE_CERTIFICATE = "on"
# DOCKER_VERNEMQ_LISTENER__SSL__USE_IDENTITY_AS_USERNAME = "on"
DOCKER_VERNEMQ_LISTENER__SSL__CAFILE = "/vernemq/cert/ca.crt"
DOCKER_VERNEMQ_LISTENER__SSL__CERTFILE = "/vernemq/cert/server.crt"
DOCKER_VERNEMQ_LISTENER__SSL__KEYFILE = "/vernemq/cert/server.key"
DOCKER_VERNEMQ_LISTENER__SSL__CRLFILE = "/tmp/shared/ca.crl"
DOCKER_VERNEMQ_ALLOW_REGISTER_DURING_NETSPLIT = "on"
DOCKER_VERNEMQ_ALLOW_PUBLISH_DURING_NETSPLIT = "on"
DOCKER_VERNEMQ_ALLOW_SUBSCRIBE_DURING_NETSPLIT = "on"
DOCKER_VERNEMQ_ALLOW_UNSUBSCRIBE_DURING_NETSPLIT = "on"
Any way I can block the specific client certificate ?
I'm not familiar with vernemq's specific options but why not just set up the ACL to block the user represented by that certificate from being able to subscribe or publish to any topics.
Clients would still be able to connect with that shared certificate, but would not be able to receive or publish any messages.
To make this work you would probably have to use the Certificate identity as the User name (but you appear to have commented that out of the env vars you have shown in the question)

OfflineImap doesn't sync mail when refresh token is gotten from AppAuth in IOS

I am trying to sync my mails from gmail to my local server using OfflineImap v7.2.1. I followed this tutorial: Using Offlineimap with the Gmail IMAP API and got it working!
Here is my .offlineimaprc file:
[general]
accounts = ExampleCompany
[Account ExampleCompany]
localrepository = ExampleCompanyLocal
remoterepository = ExampleCompanyRemote
postsynchook = notmuch new
#newer versions don't need this
#status_backend = sqlite
[Repository ExampleCompanyRemote]
type = IMAP
remotehost = imap.gmail.com
remoteuser = my-username#gmail.com
ssl = yes
starttls = no
sslcacertfile = /etc/ssl/certs/ca-certificates.crt
### You'll need to configure the gmail API stuff here:
auth_mechanisms = XOAUTH2
oauth2_client_id = XXXX7-eXXXX.apps.googleusercontent.com
oauth2_client_secret = 9XXXXXP
oauth2_request_url = https://accounts.google.com/o/oauth2/token
#oauth2_refresh_token = 1/ZXXXXXw
oauth2_access_token = ya29.XXXXXIHbcS
## remove Gmail prefix on IMAP folders
nametrans = lambda f: f.replace('[Gmail]/', '') if
f.startswith('[Gmail]/') else f
[Repository ExampleCompanyLocal]
type = Maildir
localfolders = ~/mail
restoreatime = no
# Do not sync this folder
folderfilter = lambda folder: folder not in ['2007-2011-inbox']
## Remove GMAIL prefix on Google-specific IMAP folders that are pulled down.
nametrans = lambda f: '[Gmail]/' + f if f in ['Drafts', 'Starred', 'Important', 'Spam', 'Trash', 'All Mail', 'Sent Mail'] else f
I currently generate my Access Token and Refresh Token using this python script from google. I would however like this tokens to be generated from an ios app and then sent to the backend to start syncing. I am using AppAuth to do this but OfflineImap always errors out when using these credentials gotten from the IOS app. error
ERROR: All authentication types failed:
XOAUTH2: [AUTHENTICATIONFAILED] Invalid credentials (Failure)
Any idea why these credentials will be invalid? I am using the same client_id and client_secret when running the script and the app. I think i am missing something obvious.
Here is the authorization request on the app in swift:
// builds authentication request
let request = OIDAuthorizationRequest(configuration: configuration,
clientId: "XXXX7-eXXXX.apps.googleusercontent.com",
clientSecret: "9XXXXXP",
scopes: [OIDScopeEmail],
redirectURL: redirectURI,
responseType: OIDResponseTypeCode,
additionalParameters: nil)
Thank you

Openstack Ovh connection configuration

I am currently working on a rails app and I want to use Openstack with object storage from OVH.
My error is :
connect_nonblock': SSL_connect returned=1 errno=0 state=unknown state:
certificate verify failed (OpenSSL::SSL::SSLError)
Unable to verify certificate. This may be an issue with the remote host or with Excon.Excon has certificates bundled, but these can be customized.
`Excon.defaults[:ssl_ca_path] = path_to_certs`,
`ENV['SSL_CERT_DIR'] = path_to_certs`,
`Excon.defaults[:ssl_ca_file] = path_to_file`,
`ENV['SSL_CERT_FILE'] = path_to_file`,
`Excon.defaults[:ssl_verify_callback] = callback` (see OpenSSL::SSL::SSLContext#verify_callback),
or `Excon.defaults[:ssl_verify_peer] = false` (less secure). (Excon::Errors::CertificateError)
Does anyone have a tips to do it ?
I have followed this tutorial in french:
https://gist.github.com/BaptisteDixneuf/85dc4419a0398446d2d3
and there is my carrierwave config file :
CarrierWave.configure do |config|
config.fog_provider = 'fog/openstack'
config.fog_credentials = {
:provider => 'OpenStack',
:openstack_username => ENV['OS_USERNAME'],
:openstack_api_key => ENV['OS_USER_MDP'],
:openstack_auth_url => ENV['OS_AUTH_URL'],
:openstack_region => 'GRA1'
}
end
As it says, your app have trouble connecting to openstack because it cannot checks the certificate.
It then provide various ways to overcome the problem.
These ones are used to provide the certificate manually
`Excon.defaults[:ssl_ca_path] = path_to_certs`,
`ENV['SSL_CERT_DIR'] = path_to_certs`,
`Excon.defaults[:ssl_ca_file] = path_to_file`,
`ENV['SSL_CERT_FILE'] = path_to_file`,
The other two bypass the standart verification by respectively manually check it and ignore it.
`Excon.defaults[:ssl_verify_callback] = callback` (see OpenSSL::SSL::SSLContext#verify_callback),
or `Excon.defaults[:ssl_verify_peer] = false` (less secure). (Excon::Errors::CertificateError)
OVH's Openstack cloud used valid certificats. Ensure your server have common ca-certificat list installed. And update openssl library.

“error:23076071:PKCS12 routines:PKCS12_parse:mac verify failure” when generating self signed certificate for Identity Server 4

We're developing a microservices app on Kubernetes. One of the microservices is IdentityServer instance. Initially, I want to test the solution locally on Docker to make sure it works. For this purpose, I want to copy the certificate to appsettings.json. Eventually this value will be replaced by a Kubernetes secret. In my startup class this is how I'm trying to load my certificate:
services.AddIdentityServer()
.AddSigningCredential(GetIdentityServerCertificate())
.AddConfigurationStore(...
private X509Certificate2 GetIdentityServerCertificate()
{
var clientSecret = Configuration["Certificate"];
var pfxBytes = Convert.FromBase64String(clientSecret);
var certificate = new X509Certificate2(pfxBytes, "PasswordHere");
return certificate;
}
The certificate is generated by me using openssl:
openssl req –newkey rsa:2048 –nodes –keyout XXXXX.key –x509 –days 365 –out XXXXX.cer
openssl pkcs12 –export –in XXXX.cer –inkey XXXX.key –out XXXX.pfx
Then I get the certificate by using:
$pfxFilePath = 'C:\XXXX.pfx'
$pwd = 'PasswordHere'
$flag = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable
$collection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
$collection.Import($pfxFilePath, $pwd, $flag)
$pkcs12ContentType = [System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12
$clearBytes = $collection.Export($pkcs12ContentType)
$fileContentEncoded = [System.Convert]::ToBase64String($clearBytes)
I grab the $fileContentEncoded value and paste it into appsettings.json.
When i debug it, the result is: error:23076071:PKCS12 routines:PKCS12_parse:mac verify failure when i'm trying to create X509Certificate2 object using the method above.
The error mac verify failure happens when the password is wrong. Check the password for key with
openssl pkcs12 -in XXXX.pfx

Resources