Node crypto and Ruby Open SSL - ruby-on-rails-3

im encrypting data on a ruby app and decrypting on a node server, but im getting some errors, I replicate the ruby code on my node server and notice that this 2 lib are working different
# Node crypto
var cipher = crypto.createCipher("aes256", key);
var key = crypto.createHash("sha512").update("foo", "utf8").digest("hex");
var crypt = cipher.update("bar", "utf8", "base64");
crypt += cipher.final("base64");
return crypt;
Result: BTK+S8ogCW7cK7NlA5RUJw==
# Ruby OpenSSL
cipher = OpenSSL::Cipher::Cipher.new('aes256').encrypt
cipher.key = Digest::SHA512.hexdigest("foo")
encrypted = cipher.update("bar".to_s)
encrypted += cipher.final
return Base64.encode64(encrypted)
Result: fnRH+EczVbJWwrPSITkhuw==
how can i fix this

Related

The client is unable to verify that the server is Elasticsearch due to an unsuccessful product check call

I Use ElasticSearch 8.1.2
and Nest 17.7.1
var settings = new ConnectionSettings(new Uri("http://localhost:9200/"))
.CertificateFingerprint("A5:8B:07:2D:A9:E8:53:CE:GB:C0:15:CE:6E:DF:9C:65:89:A3:AC:D2:94:2C:46:BD:85:23:20:6B:F2:69:B3:88")
.BasicAuthentication("elastic", "-L-uXRg5=iOXGFgebP68")
.DeadTimeout(TimeSpan.FromSeconds(300))
.DefaultIndex("people");
var client = new ElasticClient(settings);
var person = new Person
{
Id = 1,
FirstName = "Martijn",
LastName = "Laarman"
};
var asyncIndexResponse = await client.IndexDocumentAsync(person);
return Task.CompletedTask;
But I have Error
enter image description here
error message:
Message = "The client is unable to verify that the server is Elasticsearch due to an unsuccessful product check call. Some functionality may not be compatible if the server is running an unsupported product. Call: Status code unknown from: GET /"
Enable the compatibility header in the connection settings:
settings.EnableApiVersioningHeader(); // enable ES 7.x compatibility on ES 8.x servers
Docu here under Enabling Compatibility Mode

Indy TLS Server "No shared cipher" using ECDH Keys

Hoping someone out there can help me with this one. Simple TIdHTTPServer with OpenSSL support used to decode TLS traffic from a client using ECDH-based keys.
Server key created with the following command:
openssl ecparam -name secp256k1 -genkey -noout -out key.pem
Server debug logs:
23:33:14.878 SSL status: "before/accept initialization"
23:33:14.886 SSL status: "SSLv3 read client hello C"
23:33:14.886 SSL status: "error"
23:33:14.887 Connection from: 192.168.12.1:23727 Closed
23:33:14.887 EXCEPTION: Error accepting connection with SSL.
error:1408A0C1:SSL routines:ssl3_get_client_hello:no shared cipher
From this question, it seems like I need to call SSL_CTX_set_ecdh_auto(ctx,1)
SSL Server Initialization:
ServerIOHandler = new TIdServerIOHandlerSSLOpenSSL();
ServerIOHandler->SSLOptions->CertFile = CertPath;
ServerIOHandler->SSLOptions->KeyFile = KeyPath;
ServerIOHandler->SSLOptions->RootCertFile = RootCertPath;
ServerIOHandler->SSLOptions->Method = sslvTLSv1_2;
ServerIOHandler->SSLOptions->Mode = sslmServer;
//ServerIOHandler->SSLOptions->CipherList = "";
ServerIOHandler->SSLOptions->VerifyDepth = 1;
ServerIOHandler->OnGetPassword = OnGetServerPassword;
ServerIOHandler->OnStatusInfo = SSL_Status;
TLSServer->Bindings->Add();
TLSServer->Bindings->Items[0]->IP = TLSServerInfo.AdapterIP;
TLSServer->Bindings->Items[0]->Port = TLSServerInfo.LocalPort;
TLSServer->DefaultPort = TLSServerInfo.LocalPort;
TLSServer->IOHandler = ServerIOHandler;
try {
PanelServer->Active = true;
}
catch (Exception &Ex) {
Msg = String(L"SSL Server Bound Exception: ") + Ex.Message;
}
I have followed these instructions to add SSL_CTX_set_ecdh_auto() to my IdSSLOpenSSLHeaders.pas file, but if I try to add an entry to call SSL_CTX_set_ecdh_auto() from my code, I get a "Call to undefined function 'SSL_CTX_set_ecdh_auto'" error.
I am running Indy 10.6.2.

LWP with SSL and client certificates

Debian 10. I try to connect to a remote server with certificate. However connection fails with 500 error. DEBUG: .../IO/Socket/SSL.pm:2593: global error: Failed to load certificate from file (no PEM, DER or PKCS12) error:0D0680A8:asn1 encoding routines:asn1_check_tlen:wrong tag.
Same code with same certificate works fine with several Debian 9. I have tried different versions with Debian 10 - of IO-Socket_SSL (ex. 2.044 - 2.060), LWP-Protocol-https (ex. 6.05 - 6.07) with no luck.
For clear experiment I took fresh from provider debian images with 9 & 10. It works with basic perl modules with ver 9 and fails with ver 10.
I need a piece of help & advise , cause I'm loosing hope :(
use LWP;
use LWP::UserAgent;
use LWP::Protocol::https;
use LWP::Debug qw(+);
use Net::SSL;
use IO::Socket::SSL qw(debug4);
$ENV{HTTPS_CERT_FILE} = "cert.crt";
$ENV{HTTPS_KEY_FILE} = "private.key";
$ENV{PERL_LWP_SSL_VERIFY_HOSTNAME} = 0;
$ENV{HTTPS_DEBUG} = 1;
my $ua = LWP::UserAgent->new;
$ua->ssl_opts(
SSL_verify_mode => 0,
verify_hostname => 0,
SSL_cert_file => "cert.crt",
SSL_key_file => "private.key"
);
my $req = HTTP::Request->new(POST => "https://server:775/api");
$req->header('content-type' => 'application/soap+xml; charset=utf-8; action="http://tempuri.org/ICodeRequestOnline/GetProtocolVersion"');
my $txt= qq{<?xml version="1.0" encoding="UTF-8"?><soap:Envelope>...</soap:Envelope>};
$req->content($txt);
my $resp = $ua->request($req);
print $resp->as_string;

SSL issue on Android 9 Google Pixel One

I am trying to perform HTTPS requests to a host 10.10.10.1 from Android host with 10.10.10.2 in network without Internet connection - only WiFi 2 peers AP and Android 9 Google Pixel One device.
I've created network_security_config.xml with my cert that is self-signed and has CN=10.10.10.1 and SAN= DNS: 10.10.10.1 PI: 10.10.10.1.
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
<certificates src="user" />
<certificates src="#raw/zone"/>
</trust-anchors>
</base-config>
</network-security-config>
I don't receive verification error and observe successful requests incoming to server - data are HTTP request, decrypted and shown on the server log. But the server can't send data back! It sends, but for some reason these data are not being accepted by the Android phone - just ignored.
I see packets are going from the server to the phone and the server repeatedly retries to shutdown SSL socket until error or success (I made such behavior intentionally during surveying) - here is Wireshark dump from WiFi air:
Here is my request from AsyncTask
protected String doInBackground(String... params) {
StringBuilder result = new StringBuilder();
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = new BufferedInputStream(MainActivity.this.getResources().openRawResource(R.raw.zone));
Certificate ca = cf.generateCertificate(caInput);
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, tmf.getTrustManagers(), null);
URL url = new URL("https://10.10.10.1/connect");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ctx.getSocketFactory());
conn.setRequestProperty("param1", params[0]);
conn.setRequestProperty("param2", params[1]);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
mInputStream = conn.getInputStream();
byte[] buffer = new byte[1024];
ByteArrayOutputStream _buf = new ByteArrayOutputStream();
int l;
BufferedInputStream bufin = new BufferedInputStream(mInputStream);
while ((l = bufin.read(buffer,0,1024)) != -1) {
_buf.write(buffer, 0, l);
String rec = _buf.toString("UTF-8");
Log.d("MAIN", "Read: " + rec);
result.append(rec);
}
Log.d("MAIN", "Read finished: " + result.toString());
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}
I suspect that Android 9 Network Security does block traffic somehow. I tried to use SSLSockets, change port from 443 to e.g. 1234 - no luck.
In fact my app is being created with Qt and firstly I used Qt stuff, but having no luck - I made fallback to Android Java code within my MainActivity, that I call via JNI from Qt code. Result is the same and I have no ideas more...
Where to dig?
UPD1
When the self-signed certificate is generated with SAN containing DNS:10.10.10.1 only (without IP:10.10.10.1) SSL fails with warnings:
W System.err: javax.net.ssl.SSLPeerUnverifiedException: Hostname 10.10.10.1 not verified:
W System.err: certificate: sha1/gyr2GOhy5lA+ZAHEzh0E2SBEgx0=
W System.err: DN: CN=10.10.10.1,O=Some ltd.,L=Knoxville,ST=TN,C=US
W System.err: subjectAltNames: [10.10.10.1]
W System.err: at com.android.okhttp.internal.io.RealConnection.connectTls(RealConnection.java:201)
W System.err: at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:149)
W ...
And conversely, with SAN IP:10.10.10.1 (without DNS: 10.10.10.1) - works as before - session established, data transferred to server and decrypted, but responses from server to client just ignored by client.
UPD2
I've also tried to use domain name some.device for the 10.10.10.1 device and issued certificate with CN and SAN DNS = some.device. It's resolved by Android 9 client, data is being sent successfully but response is still not being accepting.
Looks like Android bug.
After making additional surveying:
1. Some set of Android devices (builds), including Pixel 1, does not accept TCP session that was not finalized by mutual [FIN,ACK] and received data is not delivered to upper level of stack. Also data may not be accepted if TCP stream was not solid, with many retransmissions and Seq changing.
2. In case of using Qt - Android Network Security Configuration does not affect on communications.
3. This is not TLS related issue.

SSL options in gocql

In my Cassandra config I have enabled user authentication and connect with cqlsh over ssl.
I'm having trouble implementing the same with gocql, following is my code:
cluster := gocql.NewCluster("127.0.0.1")
cluster.Authenticator = gocql.PasswordAuthenticator{
Username: "myuser",
Password: "mypassword",
}
cluster.SslOpts = &gocql.SslOptions {
CertPath: "/path/to/cert.pem",
}
When I try to connect I get following error:
gocql: unable to create session: connectionpool: unable to load X509 key pair: open : no such file or directory
In python I can do this with something like:
from cassandra.cluster import Cluster
from cassandra.auth import PlainTextAuthProvider
USER = 'username'
PASS = 'password'
ssl_opts = {'ca_certs': '/path/to/cert.pem',
'ssl_version': PROTOCOL_TLSv1
}
credentials = PlainTextAuthProvider(username = USER, password = PASS)
# define host, port, cqlsh protocaol version
cluster = Cluster(contact_points= HOST, protocol_version= CQLSH_PROTOCOL_VERSION, auth_provider = credentials, port = CASSANDRA_PORT)
I checked the gocql and TLS documentation here and here but I'm unsure about how to set ssl options.
You're adding a cert without a private key, which is where the "no such file or directory" error is coming from.
Your python code is adding a CA; you should do the same with the Go code:
gocql.SslOptions {
CaPath: "/path/to/cert.pem",
}