Showing posts with label ssl. Show all posts
Showing posts with label ssl. Show all posts

Friday, September 7, 2018

Node.js 10 HTTPS server is rejecting connections

Leave a Comment

I have simple Node.js HTTPS server

const https = require('https'); const fs = require('fs');  const config = {   key: fs.readFileSync('cert/server-key.pem'),   cert: fs.readFileSync('cert/server-crt.pem'),   ca: fs.readFileSync('cert/ca-crt.pem'), };  const server = https.createServer(config, ((req, res) => {   console.log('Got request');    res.end(); }));  server.listen(3333); 

I use curl on embedded system.

# curl -V curl 7.52.1 (arm-unknown-linux-gnu) libcurl/7.52.1 wolfSSL/3.9.8 Protocols: file ftp ftps http https smtp smtps telnet tftp  Features: IPv6 Largefile SSL UnixSockets   

When I use Node.js other then version 10 - everything works nicely.

HTTPS server running on Node.js v8.2.1

# curl -k -v "https://10.43.11.128:3333/" *   Trying 10.43.11.128... * TCP_NODELAY set * Connected to 10.43.11.128 (10.43.11.128) port 3333 (#0) * SSL connected > GET / HTTP/1.1 > Host: 10.43.11.128:3333 > User-Agent: curl/7.52.1 > Accept: */* 

HTTPS server running on Node.js v10.1.0

# curl -k -v "https://10.43.11.128:3333/" *   Trying 10.43.11.128... * TCP_NODELAY set * Connected to 10.43.11.128 (10.43.11.128) port 3333 (#0) * SSL_connect failed with error -313: revcd alert fatal error * Curl_http_done: called premature == 1 * Closing connection 0 curl: (35) SSL_connect failed with error -313: revcd alert fatal error 

What has changed in Node.js 10 with regards to HTTPS? I suspect I'll have to change SSL settings but I am to sure how.


UPDATES:

Trying to access HTTP (Node.js v10.1.0)

# curl --insecure -v "10.43.11.128:3333/" *   Trying 10.43.11.128... * TCP_NODELAY set * Connected to 10.43.11.128 (10.43.11.128) port 3333 (#0) > GET / HTTP/1.1 > Host: 10.43.11.128:3333 > User-Agent: curl/7.52.1 > Accept: */* >  * Curl_http_done: called premature == 0 * Empty reply from server * Connection #0 to host 10.43.11.128 left intact curl: (52) Empty reply from server 

Wireshark captured pcap file.

2 Answers

Answers 1

Validate which headers curl sends, you can use the -v argument for that.

curl -vIX "https://10.43.11.128:3333/"

also In node,

just console.log(req._headers) after req.end() and compare your header to further solve the problem.Also i request to try wireshark (http://www.wireshark.org/) for ssl connection testing.

As it's working by --insecure but you need to know the reason.

--insecure

  • (SSL) This option explicitly allows curl to perform "insecure" SSL connections and transfers. All SSL connections are attempted to be made secure by using the CA certificate bundle installed by default. This makes all connections considered "insecure" fail unless -k, --insecure is used.

Also can you please try this

const https = require("https"),   fs = require("fs");  const options = {   key: fs.readFileSync("/cert/server-key.pem"),   cert: fs.readFileSync("/cert/server-cert.pem") };  const app = express();  app.use((req, res) => {   res.writeHead(200);   res.end("hello world\n"); });  app.listen(8000);  https.createServer(options, app).listen(8080); 

Answers 2

Problem is that the client is not broadcasting support for a cipher suite or extension that the server requires.

Some common solutions to this problem may be: - If using ECC, the server requires the Supported Curves Extension to be enabled. Compile wolfSSL with "--enable-supported curves" to resolve. - wolfSSL has static key cipher suites disabled by default for security. Please see note at the top of the README for instructions on re-enabling static-key cipher suites if your server requires them.

Here is the Thread which discuses the error which you have received . Hope this fixes you issue

Read More

Thursday, August 16, 2018

SSL Secure Renegotiation with .NET SslStream

Leave a Comment

I'm trying to do secure renegotiation with .NET SslStream, but I'm not sure how to achieve it, or if it is even possible. My goal is to renew the shared secret, using the same certificate for the server.

I set up a server using OpenSSL :

s_server -accept 443 -key privkey.pem 

Here's my client code :

    public static void RunClient()     {         TcpClient client = new TcpClient("localhost", 443);         Console.WriteLine("Client connected.");         SslStream sslStream = new SslStream(innerStream: client.GetStream(), leaveInnerStreamOpen: true, userCertificateValidationCallback: (a,b,c,d) => true, userCertificateSelectionCallback: null);         sslStream.AuthenticateAsClient("localhost");         byte[] message = Encoding.UTF8.GetBytes("Hello from the client.");         sslStream.Write(message);         sslStream.Dispose();         // if code below is commented, there's no error.         sslStream = new SslStream(innerStream: client.GetStream(), leaveInnerStreamOpen: true, userCertificateValidationCallback: (a, b, c, d) => true, userCertificateSelectionCallback: null);         message = Encoding.UTF8.GetBytes("Hello from the client again, renegotiated.");         sslStream.AuthenticateAsClient("localhost");         sslStream.Write(message);         //         client.Close();         Console.WriteLine("Client closed.");     }     public static int Main(string[] args)     {         RunClient();         return 0;     } 

The second call to AuthenticateAsClient, on the new SslStream fails with "A call to SSPI failed, see inner exception.". The inner exception is "Win32Exception: The message received was unexpected or badly formatted".

On the server side, I get an error too :

CIPHER is ECDHE-RSA-AES256-GCM-SHA384 Secure Renegotiation IS supported Hello from the client.ERROR 8404:error:1408F119:SSL routines:ssl3_get_record:decryption failed or bad record mac:ssl\record\ssl3_record.c:469: shutting down SSL CONNECTION CLOSED ACCEPT 

Do you know what's wrong here, or if my use case is even supported with SslStream ?

0 Answers

Read More

Sunday, July 8, 2018

Fail to pull docker image using LCOW via SSL

Leave a Comment

I use docker engine 18.05.0-ce-win67 (18263). On my macOS I have succeeded in pulling images from my company's private docker registry. then I

  • copied the files client.cert, client.key and ca.crt to my Windows 10 into:

    • C:\ProgramData\Docker\certs.d\docker.company.net\
    • C:\Users\<user>\.docker\certs.d\docker.company.net\
  • imported the certificates into my Windows global certificates store and user certificates store.

Sadly, I still get this:

> docker pull <company.docker.url>/<some image> Error response from daemon: Get https://<company.docker.url>/v2/: remote error: tls: handshake failure 

Two more things to notice:

  • If I switch to Windows Containers, I can successfully login or pull images, only fails with LCOW.
  • My private cert is signed by an intermediate cert, and the intermediate cert is contained in my client.cert.

Some references I have read:

2 Answers

Answers 1

I would try two things:

  • Did you tried: docker login first before to pull the images?
  • Restart the client and repeat.

Answers 2

I had this error on windows, too. In my case, restarting the docker daemon helped.

Read More

Wednesday, May 30, 2018

How can my library with built in ssl certificate also allow use with default certs

Leave a Comment

I am distributing a library jar for internal clients, and the library includes a certificate which it uses to call a service that is also internal to our network.

The trust manager is set up as follows

    TrustManagerFactory trustManagerFactory =        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());     KeyStore keystore = KeyStore.getInstance("JKS");     InputStream keystoreStream =        clazz.getClassLoader().getResourceAsStream("certs.keystore"); // (on classpath)     keystore.load(keystoreStream, "pa55w0rd".toCharArray());     trustManagerFactory.init(keystore);     TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();     SSLContext context = SSLContext.getInstance("SSL");     context.init(null, trustManagers, null);      SSLSocketFactory socketFact = context.getSocketFactory();     connection.setSSLSocketFactory(socketFact); 

All of this works fine except in cases where users need other certificates or the default certificate.

I tried this Registering multiple keystores in JVM with no luck (I am having trouble generalizing it for my case)

How can I use my cert and still allow user libraries to use their own certs as well?

2 Answers

Answers 1

You are configuring a connection with a custom keystore acting as a truststore ( a certificate of your server that you trust). You are not overriding the default JVM behaviour, so the rest of the connection that other applications that include your library can make will not be affected.

Therefore you do not need a multiple keystore manager, in fact, your code works perfectly.

I've attached a full example below using a keystore google.jks which includes Google's root CA, and a connection using the default JVM truststore. This is the output

request("https://www.google.com/", "test/google.jks", "pa55w0rd"); //OK  request("https://www.aragon.es/", "test/google.jks", "pa55w0rd");  // FAIL sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target request("https://www.aragon.es/", null, null); //OK 

The problem is not in the code you have attached, so check the following in your code:

  • The truststore certs.keystore is really found in your classpath

  • Truststore settings are not set at JVM level using -Djavax.net.ssl.trustStore

  • The errors found (please include it in your question) are really related to the SSL connection


package test;  import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.security.KeyStore;  import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory;   public class HTTPSCustomTruststore {      public final static void main (String argv[]) throws Exception{         request("https://www.google.com/", "test/google.jks", "pa55w0rd"); //Expected OK          request("https://www.aragon.es/","test/google.jks","pa55w0rd");  // Expected  FAIL         request("https://www.aragon.es/",null,null); //using default truststore. OK      }      public static void configureCustom(HttpsURLConnection connection, String truststore, String pwd)throws Exception{         TrustManagerFactory trustManagerFactory =                  TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());         KeyStore keystore = KeyStore.getInstance("JKS");         InputStream keystoreStream = HTTPSCustomTruststore.class.getClassLoader().getResourceAsStream(truststore);         keystore.load(keystoreStream, pwd.toCharArray());         trustManagerFactory.init(keystore);         TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();         SSLContext context = SSLContext.getInstance("SSL");         context.init(null, trustManagers,  new java.security.SecureRandom());          SSLSocketFactory socketFact = context.getSocketFactory();         connection.setSSLSocketFactory(socketFact);     }       public static void request(String urlS, String truststore, String pwd) {         try {             URL url = new URL(urlS);             HttpURLConnection conn = (HttpURLConnection) url.openConnection();             conn.setRequestMethod("GET");             if (truststore != null) {                 configureCustom((HttpsURLConnection) conn, truststore, pwd);             }                conn.connect();              int statusCode = conn.getResponseCode();             if (statusCode != 200) {                 System.out.println(urlS + " FAIL");             } else {                 System.out.println(urlS + " OK");             }         } catch (Exception e) {             System.out.println(urlS + " FAIL " + e.getMessage());         }     } } 

Answers 2

You could import the default certificates into your custom store to have a combined custom store and use that.

Read More

Wednesday, May 23, 2018

Disabling TLS 1.0 breaks ASP.NET application

Leave a Comment

Running on Windows Server 2012R2

I am trying to disable TLS 1.0 on IIS because client has a site scanner which highlights that as a security problem.

I have a clean test server set up and App is running fine until I disable TLS 1.0.

I updated all the appropriate settings:

Windows Registry Editor Version 5.00  [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v2.0.50727] "SchUseStrongCrypto"=dword:00000001  [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319] "SchUseStrongCrypto"=dword:00000001  [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v2.0.50727] "SchUseStrongCrypto"=dword:00000001  [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319] "SchUseStrongCrypto"=dword:00000001  [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0]  [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Client] "Enabled"=dword:00000000 "DisabledByDefault"=dword:00000001  [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Server] "Enabled"=dword:00000000 "DisabledByDefault"=dword:00000001  [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1]  [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client] "Enabled"=dword:ffffffff "DisabledByDefault"=dword:00000000  [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server] "Enabled"=dword:ffffffff "DisabledByDefault"=dword:00000000  [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2]  [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client] "Enabled"=dword:ffffffff "DisabledByDefault"=dword:00000000  [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server] "Enabled"=dword:ffffffff "DisabledByDefault"=dword:00000000 

In the event viewer, I get:

A fatal alert was generated and sent to the remote endpoint. This may result in termination of the connection. The TLS protocol defined fatal error code is 70. The Windows SChannel error state is 105.

If I revert the registry settings just for TLS 1.0 (Enabled, not DisabledByDefault), everything is fine again.

Using in system.web:

<httpRuntime targetFramework="4.7.2" /> 

What am I missing?

3 Answers

Answers 1

The application itself must be updated to support TLS 1.2 handshakes, so it's not something you can necessarily change if you only have access to configuration. If the underlying code does not support it, it will not work.

If the code targets .NET 4.6, I believe, TLS 1.2 will work natively. In 4.5, a line of code must be put in place such that it is executed before any networking occurs. The code:

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12 

Answers 2

Have you tried to enable schannel logging to get more info?

https://support.microsoft.com/en-us/help/260729/how-to-enable-schannel-event-logging-in-iis

Hope that will reveal the missing piece.

Answers 3

Your site could be communicating with something over SSL that doesn't support TLS 1.1+

Read More

Thursday, May 10, 2018

CouchDB won't work over SSL

Leave a Comment

I am running the CouchDB Docker container, V.2.1.1. Everything is working at this point except for SSL. I am following the CouchDB documentation on SSL setup. The container has OpenSSL 1.0.1t.

As shown in the documentation, I am using a self-signed certificate. When I try to connect to the SSL page on port 6984:

Chrome tells me

"ERR_CONNECTION_CLOSED". 

curl gives me

curl -k https://localhost:6984

curl: (35) LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to localhost:6984 

In the server log, I get a whole lot of this.

hello terminated with reason: no function clause matching ssl_cipher:hash_algorithm 

A search on this last error turns up information indicating that the Erlang version has an issue. However, I believe the CouchDB container has an already patched version. I did try and upgrade with:

apt-get install Erlang 

This made no difference. Search results also point to the version of OpenSSL having a problem. I upgraded to OpenSSL 1.1.1 from source, Recreated the certificates, and still, the issue persists.

As requested, here is the output from a few more commands.

openssl s_client -connect localhost:6984

CONNECTED(00000005) 140736008328136:error:140790E5:SSL routines:SSL23_WRITE:ssl handshake failure:/BuildRoot/Library/Caches/com.apple.xbs/Sources/libressl/libressl-22.50.2/libressl/ssl/s23_lib.c:124: --- no peer certificate available --- No client certificate CA names sent --- SSL handshake has read 0 bytes and written 318 bytes --- New, (NONE), Cipher is (NONE) Secure Renegotiation IS NOT supported Compression: NONE Expansion: NONE No ALPN negotiated --- 

curl --version

curl 7.54.0 (x86_64-apple-darwin17.0) libcurl/7.54.0 LibreSSL/2.0.20 zlib/1.2.11 nghttp2/1.24.0 Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smb smbs smtp smtps telnet tftp Features: AsynchDNS IPv6 Largefile GSS-API Kerberos SPNEGO NTLM NTLM_WB SSL libz HTTP2 UnixSockets HTTPS-proxy 

curl -k -v https://localhost:6984

* Rebuilt URL to: https://localhost:6984/ *   Trying ::1... * TCP_NODELAY set * Connected to localhost (::1) port 6984 (#0) * ALPN, offering h2 * ALPN, offering http/1.1 * Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH * successfully set certificate verify locations: *   CAfile: /etc/ssl/cert.pem   CApath: none * TLSv1.2 (OUT), TLS handshake, Client hello (1): * LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to localhost:6984 * stopped the pause stream! * Closing connection 0 curl: (35) LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to localhost:6984 

curl -k --ciphers DEFAULT https://localhost:6984

curl: (35) LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to localhost:6984 

curl -k --ciphers ECDHE-RSA-AES256-GCM-SHA384 https://localhost:6984

curl: (35) LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to localhost:6984 

The output from the following three commands is very similar. I will just show the differences. However, it seems that a handshake is now taking place with all of these commands.

$ openssl s_client -tls1 -connect localhost:6984

CONNECTED(00000005) SSL handshake has read 1762 bytes and written 400 bytes New, TLSv1/SSLv3, Cipher is DHE-RSA-AES256-SHA Compression: NONE Expansion: NONE SSL-Session:     Protocol  : TLSv1     Cipher    : DHE-RSA-AES256-SHA     Session-ID: 18C5DF9DCA1B8AA0DBD33258BCD253053F8D1D91B524B0561A1C0FAB8CFB5146     Master-Key: FD0C57E4E8FB992C0323D43930C104D82B69C4200F42E03EDB51E38A47448D62FDCB6E813583E2177A339B74B4D0CC4A     Start Time: 1525593658     Timeout   : 7200 (sec) 

$ path/to/brew/version/of/openssl s_client -connect localhost:6984

CONNECTED(00000003) Peer signing digest: SHA512 Server Temp Key: DH, 1024 bits SSL handshake has read 1796 bytes and written 537 bytes New, TLSv1/SSLv3, Cipher is DHE-RSA-AES256-SHA256 SSL-Session:     Protocol  : TLSv1.2     Cipher    : DHE-RSA-AES256-SHA256     Session-ID: A19D67CBE634843181859DB2C3C4D1A3416C9F7DAA85CF470D412FE723AD49B4     Master-Key: 61B711B9BEDB651868607527439D01B421780C7D584FCE68C4754A7A7F3563923409C03F4B68BB7914397B48A92FC756     Key-Arg   : None     PSK identity: None     PSK identity hint: None     SRP username: None     Start Time: 1525593604     Timeout   : 300 (sec) 

$ path/to/brew/version/of/openssl s_client -tls1 -connect localhost:6984

SSL handshake has read 1762 bytes and written 397 bytes New, TLSv1/SSLv3, Cipher is DHE-RSA-AES256-SHA SSL-Session:     Protocol  : TLSv1     Cipher    : DHE-RSA-AES256-SHA     Session-ID: 6CC7FFE1C7CE258F105C7ADD5D8A9C0DFFB26A5A9555EB218EE48E519D361208     Master-Key: 2D6DFAC01544F6FF5F4138D877A4105485D5A2F77B58B4796822625E2E602455C38E3EEB2CBACE07FA03D207B07C715E     Start Time: 1525593717     Timeout   : 7200 (sec) 

$ curl -k --tlsv1 https://localhost:6984

curl: (35) LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to localhost:6984 

$ curl -k --tlsv1.0 https://localhost:6984

{"couchdb":"Welcome","version":"2.1.1","features":["scheduler"],"vendor":{"name":"The Apache Software Foundation"}} 

So I am guessing there is a problem with the built-in version of LibreSSL? The next question is what can be done about it?

2 Answers

Answers 1

If your SSL certificate is self-signed:


You didn't show your curl command, but I guess you are not using the -k option, but you should:

-k, --insecure               (TLS) By default, every SSL connection curl makes is verified to be secure. This option allows curl to proceed and operate even  for               server connections otherwise considered insecure. 

Answers 2

In order to dig deeper, can you post the output of the following commands?

$ openssl s_client -connect localhost:6984  $ curl --version  $ curl -k -v https://localhost:6984  $ curl -k --ciphers DEFAULT https://localhost:6984  $ curl -k --ciphers ECDHE-RSA-AES256-GCM-SHA384 https://localhost:6984 

By the way, I notice that your curl is using LibreSSL not OpenSSL as indicated in the error message you're getting:

curl: (35) LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to localhost:6984


When you try openssl:

$ openssl s_client -connect localhost:6984 

You are getting this error:

CONNECTED(00000005) 140736008328136:error:140790E5:SSL routines:SSL23_WRITE:ssl handshake failure:/BuildRoot/Library/Caches/com.apple.xbs/Sources/libressl/libressl-22.50.2/libressl/ssl/s23_lib.c:124:

Can you please report the output of this command:

$ openssl s_client -tls1 -connect localhost:6984 

Also, it might be inferred that the cause of the problem is your macOS default version of LibreSSL/OpenSSL. To fix the problem, try to install the brew version OpenSSL and run this command again, and please report the output:

$ path/to/brew/version/of/openssl s_client -connect localhost:6984 

Also please post the output of this too:

$ path/to/brew/version/of/openssl s_client -tls1 -connect localhost:6984 

Based on your reported outputs, please try the following command and see if it works:

$ curl -k --tlsv1 https://localhost:6984 
Read More

Thursday, April 19, 2018

URI::InvalidComponentError (bad component(expected scheme component): : https):

Leave a Comment

I'm working on a Ruby on Rails web app and I'm using Devise for user/password and OmniAuth for authentication using social media accounts. And I'm also using Nginx.

Authentication with username/password worked perfectly. But when I added ssl certificate to Nginx. I'm now able to login. But when I logout I get the error message in the title URI::InvalidComponentError (bad component(expected scheme component): : https): and telling that I have an exception generated from:

def check_scheme(v)   if v && parser.regexp[:SCHEME] !~ v     raise InvalidComponentError,       "bad component(expected scheme component): #{v}"   end 

How can I fix this problem in order for all types of authentications to work?

UPDATE

It throws the same exception after almost every redirect withing the web app. But redirects anyway, event user login. But it never logs out

*UPDATE 2 *

This question has more detailed description of my issue

This other question is another try to fix the issue

UPDATE 3

When I tried adding config.force_ssl = true to my environment .rb file, I get "page not found" and the following in ssl.error.log

2018/04/13 05:05:14 [error] 7317#0: *553 connect() failed (111: Connection refused) while connecting to upstream, client: <my laptop ip>, server: vps37181, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:3000/", host: "<domain name>" 2018/04/13 05:05:14 [error] 7317#0: *553 open() "/var/www/<app-name>/public/50x.html" failed (2: No such file or directory), client: <my laptop ip>, server: vps37181, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:3000/", host: "<domain name>" 

UPDATE 4

My current nginx configuration at /etc/nginx/conf.d/ssl.conf is:

server {     listen 443 ssl;     server_name <server-name>;      client_max_body_size 15M;     ssl                  on;     ssl_certificate      <.pem file path>;     ssl_certificate_key  <.key file path>;     ...     root <"public" directory inside my app directory>;     access_log <ssl.access.log path>;     error_log  <ssl.error.log path>;      include /etc/nginx/default.d/*.conf;      location / {         proxy_pass http://127.0.0.1:3000;          proxy_set_header X-Real-IP  $remote_addr;         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;         proxy_set_header Host $http_host;         proxy_set_header X-NginX-Proxy true;         proxy_set_header X-Forwarded-Proto: $scheme;  } 

UPDATE 5

After every request redirected from Nginx to the app, I get the following in the app console:

Cannot render console from <my laptop ip>! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255  URI::InvalidComponentError (bad component(expected scheme component): : https):  /home/tamer/.rvm/rubies/ruby-2.5.0/lib/ruby/2.5.0/uri/generic.rb:322:in `check_scheme' /home/tamer/.rvm/rubies/ruby-2.5.0/lib/ruby/2.5.0/uri/generic.rb:363:in `scheme=' actionpack (5.1.5) lib/action_dispatch/routing/redirection.rb:35:in `serve' actionpack (5.1.5) lib/action_dispatch/routing/redirection.rb:21:in `call' actionpack (5.1.5) lib/action_dispatch/routing/mapper.rb:17:in `block in <class:Constraints>' actionpack (5.1.5) lib/action_dispatch/routing/mapper.rb:46:in `serve' actionpack (5.1.5) lib/action_dispatch/journey/router.rb:50:in `block in serve' actionpack (5.1.5) lib/action_dispatch/journey/router.rb:33:in `each' actionpack (5.1.5) lib/action_dispatch/journey/router.rb:33:in `serve' actionpack (5.1.5) lib/action_dispatch/routing/route_set.rb:844:in `call' omniauth (1.8.1) lib/omniauth/strategy.rb:190:in `call!' omniauth (1.8.1) lib/omniauth/strategy.rb:168:in `call' omniauth (1.8.1) lib/omniauth/strategy.rb:190:in `call!' omniauth (1.8.1) lib/omniauth/strategy.rb:168:in `call' omniauth (1.8.1) lib/omniauth/strategy.rb:190:in `call!' omniauth (1.8.1) lib/omniauth/strategy.rb:168:in `call' omniauth (1.8.1) lib/omniauth/strategy.rb:190:in `call!' omniauth (1.8.1) lib/omniauth/strategy.rb:168:in `call' omniauth (1.8.1) lib/omniauth/strategy.rb:190:in `call!' omniauth (1.8.1) lib/omniauth/strategy.rb:168:in `call' omniauth (1.8.1) lib/omniauth/builder.rb:63:in `call' warden (1.2.7) lib/warden/manager.rb:36:in `block in call' warden (1.2.7) lib/warden/manager.rb:35:in `catch' warden (1.2.7) lib/warden/manager.rb:35:in `call' rack (2.0.4) lib/rack/etag.rb:25:in `call' rack (2.0.4) lib/rack/conditional_get.rb:25:in `call' rack (2.0.4) lib/rack/head.rb:12:in `call' rack (2.0.4) lib/rack/session/abstract/id.rb:232:in `context' rack (2.0.4) lib/rack/session/abstract/id.rb:226:in `call' actionpack (5.1.5) lib/action_dispatch/middleware/cookies.rb:613:in `call' activerecord (5.1.5) lib/active_record/migration.rb:556:in `call' actionpack (5.1.5) lib/action_dispatch/middleware/callbacks.rb:26:in `block in call' activesupport (5.1.5) lib/active_support/callbacks.rb:97:in `run_callbacks' actionpack (5.1.5) lib/action_dispatch/middleware/callbacks.rb:24:in `call' actionpack (5.1.5) lib/action_dispatch/middleware/executor.rb:12:in `call' actionpack (5.1.5) lib/action_dispatch/middleware/debug_exceptions.rb:59:in `call' web-console (3.5.1) lib/web_console/middleware.rb:135:in `call_app' web-console (3.5.1) lib/web_console/middleware.rb:20:in `block in call' web-console (3.5.1) lib/web_console/middleware.rb:18:in `catch' web-console (3.5.1) lib/web_console/middleware.rb:18:in `call' actionpack (5.1.5) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call' railties (5.1.5) lib/rails/rack/logger.rb:36:in `call_app' railties (5.1.5) lib/rails/rack/logger.rb:24:in `block in call' activesupport (5.1.5) lib/active_support/tagged_logging.rb:69:in `block in tagged' activesupport (5.1.5) lib/active_support/tagged_logging.rb:26:in `tagged' activesupport (5.1.5) lib/active_support/tagged_logging.rb:69:in `tagged' railties (5.1.5) lib/rails/rack/logger.rb:24:in `call' sprockets-rails (3.2.1) lib/sprockets/rails/quiet_assets.rb:13:in `call' actionpack (5.1.5) lib/action_dispatch/middleware/remote_ip.rb:79:in `call' request_store (1.4.0) lib/request_store/middleware.rb:19:in `call' actionpack (5.1.5) lib/action_dispatch/middleware/request_id.rb:25:in `call' rack (2.0.4) lib/rack/method_override.rb:22:in `call' rack (2.0.4) lib/rack/runtime.rb:22:in `call' activesupport (5.1.5) lib/active_support/cache/strategy/local_cache_middleware.rb:27:in `call' actionpack (5.1.5) lib/action_dispatch/middleware/executor.rb:12:in `call' actionpack (5.1.5) lib/action_dispatch/middleware/static.rb:125:in `call' rack (2.0.4) lib/rack/sendfile.rb:111:in `call' railties (5.1.5) lib/rails/engine.rb:522:in `call' puma (3.11.2) lib/puma/configuration.rb:225:in `call' puma (3.11.2) lib/puma/server.rb:624:in `handle_request' puma (3.11.2) lib/puma/server.rb:438:in `process_client' puma (3.11.2) lib/puma/server.rb:302:in `block in run' puma (3.11.2) lib/puma/thread_pool.rb:120:in `block in spawn_thread' 

This message doesn't prevent the website from loading. But when user logs out (I'm using Devise for username/password user authentication). the website throws in the browser the error I mentioned earlier:

URI::InvalidComponentError bad component(expected scheme component): : https Extracted source (around line #322):  def check_scheme(v)   if v && parser.regexp[:SCHEME] !~ v     raise InvalidComponentError, # line 322       "bad component(expected scheme component): #{v}"   end 

and I get the console error message twice.

UPDATE 7

I'm running my server in development.

I dug deeper and I found that :

URI::InvalidComponentError (bad component(expected scheme component): : https) 

means that what was expected was : https while received https.

I tried modifying parser.regexp[:SCHEME] in check_shceme in /home/tamer/.rvm/rubies/ruby-2.5.0/lib/ruby/2.5.0/uri/generic.rb in which it approves : https also. But now, on logout, which supposed to send a request to

https://<my domain name>/users/log_out 

now redirectes to :

https://<my domain name>/users/:%20https://<my domain name>/:%20https://<my domain name>/:%20https://<my domain name>/:%20https://<my domain name>/:%20https://<my domain name>/:%20https://<my domain name>/:%20https://<my domain name>/:%20https://<my domain name>/:%20https://<my domain name>/:%20https://<my domain name>/:%20https://<my domain name>/:%20https://<my domain name>/:%20https://<my domain name>/:%20https://<my domain name>/:%20https://<my domain name>/:%20https://<my domain name>/:%20https://<my domain name>/:%20https://<my domain name>/:%20https://<my domain name>/:%20https://<my domain name>/ 

in which :%20 means whitespace.

0 Answers

Read More

Saturday, April 7, 2018

Spring Boot - enable and configure SSL certificate

Leave a Comment

I have this certificates / files in order to enable SSL for my application:

certificates

I found out that this properties are needed for Spring Boot to enable HTTPS:

server.port=8089 server.ssl.enabled=true server.ssl.key-store=src/main/resources/keystore.p12 server.ssl.key-store-password=**** server.ssl.keyStoreType=PKCS12 server.ssl.keyAlias=tomcat 

but this does not work. My question now would be what do I have to do in order to get it work? https://abc.lehr.co.at should be the URL.

[EDIT]

I have created my own keystore - with this I get the following exception:

java.io.IOException: Alias name tomcat does not identify a key entry at org.apache.tomcat.util.net.jsse.JSSESocketFactory.getKeyManagers(JSSESocketFactory.java:596) at org.apache.tomcat.util.net.jsse.JSSESocketFactory.getKeyManagers(JSSESocketFactory.java:534) at org.apache.tomcat.util.net.NioEndpoint.bind(NioEndpoint.java:363) at org.apache.tomcat.util.net.AbstractEndpoint.start(AbstractEndpoint.java:739) at org.apache.coyote.AbstractProtocol.start(AbstractProtocol.java:472) at org.apache.coyote.http11.Http11NioProtocol.start(Http11NioProtocol.java:81) at org.apache.catalina.connector.Connector.startInternal(Connector.java:986) 

My keystore looks like this:

Keystore

Actually I don't know what to import into keystore for embedded tomcat (Spring Boot).

3 Answers

Answers 1

To enable SSL, you must provide a private key, and not a trusted certificate.

In your keystore, 'tomcat' should be listed as an alias for a privatekeyentry and not a trustedcertentry.

Answers 2

You have to pack your private keys to PFX file or P12 with specifiyng aliases. So, it will be picked up accordingly from the keyStore after loading materials.

Use this tool to figure out what alias are:

keytool -list -storetype pkcs12 -keystore my_debug_keystore.p12 -storepass debug 

Answers 3

I'd suggest you create your KeyStore in JKS format:

 keytool -genkey -keyalg RSA -alias my_alias -keystore keystore.jks -storepass password -validity 360 -keysize 2048 

then add the configuration:

server.port=8089 server.ssl.enabled=true server.ssl.key-store=src/main/resources/keystore.jks server.ssl.key-store-password=**** server.ssl.keyStoreType=JKS server.ssl.keyAlias=my_alias 
Read More

Thursday, April 5, 2018

How to get SSL working with Rails, AWS Elastic Beanstalk and Cloudflare

Leave a Comment

I have a site hosted on Elastic Beanstalk built with Ruby on Rails. I set up Cloudflare to configure the DNS and provide a CDN. Cloudflare also provides an SSL.

I can't get the SSL working with my app.

With Cloudflare's SSL set at "Flexible" I can load my main page but when I try to log in, I get these errors (edited for brevity):

INFO -- :  Started POST "/users/sign_in" for xxx.xxx.146.132 at 2018-03-19 16:45:24 +0000 INFO -- :  Processing by Users::SessionsController#create as HTML INFO -- :    Parameters: {"utf8"=>"✓", "authenticity_token"=>"f92CTIe5qlp7C624DZzZM2oWdFMcq6PhyfOJI16saV32yugMmJlenL/F3gTeBBsAjaAw92P1vncWBzI+JnK8wA==", "user"=>{"email"=>"test@test.com", "password"=>"[FILTERED]"}, "commit"=>"Log in"} WARN -- :  HTTP Origin header (https://[MY_URL].com) didn't match request.base_url (http://[MY_URL].com) INFO -- :  Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms)   FATAL -- :  ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken): 

If I set Cloudflare's SSL to "Full" I get a 502 error with a Cloudflare-generated page (see image).

enter image description here

I came across this site (http://til.obiefernandez.com/posts/875a2a69af-cloudflare-flexible-ssl-mode-breaks-rails-5-csrf) which seems to have the exact same issue but setting to "full" didn't help me.

I've tried setting config.force_ssl = true in /config/environments/production.rb. That setting would not allow any access to the site. Just shows the same 502 error page from Cloudflare and nothing in my production or nginx logs.

I've tried messing around with custom nginx config's but haven't gotten anywhere. Here is my latest nginx confix attempt:

user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /var/run/nginx.pid;  events {     worker_connections 1024; }  http {     log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '                       '$status $body_bytes_sent "$http_referer" '                       '"$http_user_agent" "$http_x_forwarded_for"';      access_log  /var/log/nginx/access.log  main;      sendfile            on;     tcp_nopush          on;     tcp_nodelay         on;     keepalive_timeout   65;     types_hash_max_size 2048;      include             /etc/nginx/mime.types;     default_type        application/octet-stream;      include /etc/nginx/conf.d/*.conf;      index   index.html index.htm;      server {         listen       80 ;         listen       [::]:80 ;         server_name  localhost;         root         /usr/share/nginx/html;          # Load configuration files for the default server block.         include /etc/nginx/default.d/*.conf;           location / {           proxy_pass        http://localhost;           proxy_set_header  Host $host;           proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;           proxy_set_header  X-Forwarded-Proto $scheme;           proxy_set_header  X-Forwarded-Ssl on; # Optional           proxy_set_header  X-Forwarded-Port $server_port;           proxy_set_header  X-Forwarded-Host $host;         }         error_page 404 /404.html;             location = /40x.html {         }          # redirect server error pages to the static page /50x.html         #         error_page 500 502 503 504 /50x.html;             location = /50x.html {         }     } } 

Can anyone help? I'm sure I'm missing something obvious here.

1 Answers

Answers 1

502 Error: This error says that the Cloudfare server is unable to read the response your rails server sends, basically when you select the Full SSL the Cloudflare expects the response to be in SSL but here the rails app send a NON-SSL (HTTP) response which Cloudflare is unable to read.

I read the article you shared, looks like rails do not allow flexible SSL for security reasons.

Flexible SSL In flexible SSL you don't need to secure your rails app with SSL Certificate(HTTPS) but your visitors still see the site as being HTTPS enabled.

enter image description here

Flexible SSL: secure connection between your visitor and Cloudflare, but no secure connection between Cloudflare and your web server. You don't need to have an SSL certificate on your web server, but your visitors still see the site as being HTTPS enabled.

Full SSL
As mentioned in the article if you enable Full SSL, then you need to configure rails config.force_ssl = true to use a Self-signed SSL certificate or you can get a certificate from letsencrypt for free, once you did that you need change your Nginx to run on HTTPS port 443. This should fix the 502 error.

Here is a tutorial on Using HTTPs with Ruby on Rails

enter image description here

Full SSL: secure connection between your visitor and Cloudflare, and secure connection (but not authenticated) between Cloudflare and your web server. You will need to have your server configured to answer HTTPS connections, with a self-signed certificate at least.

Image Source

Read More

Friday, March 16, 2018

Error on Let's encrypt auto renewal (Nginx)

Leave a Comment

I am trying to set up greenlock-express to run behind nginx proxy.

Here is my nginx config

... # redirect server {     listen 80;     listen [::]:80;     server_name mydomain.com;      location / {         return 301 https://$server_name$request_uri;     } }  # serve server {     listen 443 ssl http2;     listen [::]:443 ssl http2;     server_name mydomain.com;      # SSL settings     ssl on;     ssl_certificate C:/path/to/mydomain.com/fullchain.pem;     ssl_certificate_key C:/path/to/mydomain.com/privkey.pem;      # enable session resumption to improve https performance     ssl_session_cache shared:SSL:50m;     ssl_session_timeout 1d;     ssl_session_tickets off;      # enables server-side protection from BEAST attacks     ssl_prefer_server_ciphers on;     # disable SSLv3(enabled by default since nginx 0.8.19) since it's less secure then TLS     ssl_protocols TLSv1 TLSv1.1 TLSv1.2;      # ciphers chosen for forward secrecy and compatibility     ssl_ciphers 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS';      # enable OCSP stapling (mechanism by which a site can convey certificate revocation information to visitors in a privacy-preserving, scalable manner)     resolver 8.8.8.8 8.8.4.4;     ssl_stapling on;     ssl_stapling_verify on;     ssl_trusted_certificate C:/path/to/mydomain.com/chain.pem;      # config to enable HSTS(HTTP Strict Transport Security) https://developer.mozilla.org/en-US/docs/Security/HTTP_Strict_Transport_Security     add_header Strict-Transport-Security "max-age=31536000; includeSubdomains; preload";      # added to make handshake take less resources     keepalive_timeout 70;      location / {         proxy_set_header X-Real-IP $remote_addr;         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;         proxy_set_header Host $http_host;         proxy_set_header X-NginX-Proxy true;         proxy_pass https://127.0.0.1:3001/;         proxy_redirect off;         proxy_set_header Upgrade $http_upgrade;         proxy_set_header Connection "upgrade";     } } ... 

I have node server running on port 3000 (http) and port 3001 (https). Everything else seems to be working, but certificates do not update and expire after 3 months.

If I closed nginx and ran node server on port 80 (http) and port 443 (https), then it updates certs.

I made sure that .well-known/acme-challenge is forwarded to node server, i.e when I go to url http(s)://mydomain.com/.well-known/acme-challenge/randomstr I get following response:

{    "error": {      "message": "Error: These aren't the tokens you're looking for. Move along."    }  } 

2 Answers

Answers 1

The easy way to separate the webroot for ACME authentication.

Create a webroot directory for ACME authentication.

C:\www\letsencrypt\.well-known 

In the nginx configuration, set the webroot for ACME authentication to the previously created directory.

http://example.com/.well-known/acme-challenge/token -> C:/www/letsencrypt/.well-known/acme-challenge/token

server {     listen 80;     listen [::]:80;     server_name mydomain.com;      location ^~ /.well-known/acme-challenge/ {         default_type "text/plain";         root C:/www/letsencrypt;     }      location / {         return 301 https://$server_name$request_uri;     } } 

Restart nginx.

You can change your webroot in certbot to get authentication again.

certbot certonly --webroot -w C:\www\letsencrypt\ -d exapmle.com --dry-run 

First, test it by adding the --dry-run option. Otherwise, you may experience issues limiting the number of authentication attempts.

Answers 2

The error you are seeing is that when a token is placed in your

webroot/.well-known/acme-challenge/token

Then Let’s Encrypt tries to verify that from the internet. going to http://yourdomain/.well-known/acme-challenge/token it gets a 404 error - page not found. Exactly why it get’s a 404 I can’t be certain. If you place a file there yourself, is it reachable from the internet ?.

If you are wondering there are a couple of automatic ways to renew your SSL's without restarting your nginx. The one most nginx users seem to prefer is the webroot plugin: first, obtain a new cert using something like:

certbot certonly --webroot -w /path/to/your/webroot -d example.com --post-hook="service nginx reload" 

Then set up a cron job to run certbot renew once or twice a day; it will only run the post-hook when it actually renews the certificate. You can also use --pre-hook flag if you prefer to stop nginx to run certbot in standalone mode.

There’s also a full nginx plugin, which you can activate with --nginx. It’s still being tested, so experiment at your own risk and report any bugs.

Note: post-hookFlag will take care of reloading nginx upload renewal of your certs

Read More

Monday, March 5, 2018

Alert(Level: Fatal, Description: Decode Error) - Forwarding Proxy

Leave a Comment

I'm trying to make a forwarding proxy but I keep getting an

Alert(Level: Fatal, Description: Decode Error) 

after the Client sends...

Client Key Exchange, Change Cipher Spec, Encrypted Handshake Message 

enter image description here

enter image description here

Any ideas as to what I'm doing wrong?

I can't seem to get a grasp on what the error even means. Does it mean the initial encrypted packet by the client fails to be decrypted by the server? If so, then why?

UPDATE 1

I just was looking at the packets and I noticed a significant difference between using my proxy, and not using the proxy.

The DFE key isn't being interpereted with my proxy.

enter image description here

enter image description here

1 Answers

Answers 1

Any ideas as to what I'm doing wrong?

You're not forwarding the exact amount of data that the proxy is supposed to forward.

But I see you're going further now than at the beginning of your question (good !)

You are implementing a proxy which forwards every single byte which it receives, in both ways, and either it sends too much to the server, or not enough. Check your code again for any conditions when you stop reading the input data to forward, be sure you're forwarding exactly everything. Nothing more, nothing less.

RFC 5246, about Decode Error :

decode_error A message could not be decoded because some field was out of the specified range or the length of the message was incorrect. This message is always fatal and should never be observed in communication between proper implementations (except when messages were corrupted in the network).

Read More

Monday, February 5, 2018

How to configure https support in 443 for apache AND node?

Leave a Comment

Actual state:

http://www.example.com/mypage apache http: OK!
https://www.example.com/mypage apache https: OK!

http://www.example.com:8000 node http: OK!
https://www.example.com:8000 node https: Not working (still)

I've tried to modify node program to be

var express = require('express'); var app = express(); var https = require('https'); var fs = require('fs');  var server = http.createServer(app);  https.createServer({          key: fs.readFileSync("/etc/letsencrypt/live/www.example.com/privkey.pem"),         cert: fs.readFileSync("/etc/letsencrypt/live/www.example.com/fullchain.pem"),         ca: fs.readFileSync("/etc/letsencrypt/live/www.example.com/chain.pem") }, app).listen(443); 

The obvious problem here is that apache is ALREADY listenning to port 443, then

Error: listen EADDRINUSE :::443 

Is there a way to use Apache 443 to serve SSL for node?

2 Answers

Answers 1

You can only bind one process to a given port on your server.

That said, the correct way to do this is to have Apache listen on 443, then use mod_proxy to forward the traffic to nodejs either on an HTTP port (not w/ SSL, but you're only talking across localhost) or on a unix socket.

A good example of how to do that with port 80/HTTP is here: http://blog.podrezo.com/making-node-js-work-with-apache/

<VirtualHost *:80>   ServerName pastebin.mydomain.com   ServerAlias www.pastebin.mydomain.com   DocumentRoot /var/www/pastebinjs/   Options -Indexes   ErrorDocument 503 /maintenance.html    ProxyRequests on   ProxyPass /maintenance.html !   ProxyPass / http://localhost:8000/ </VirtualHost> 

But the theory is the same if you add the Proxy* lines to your existing HTTPS endpoint.

Answers 2

Your node HTTPS server can run on any port - let's say 9090 instead of the 443 you have set. Use Apache to redirect any traffic that comes in https://example.com to your node https server listening on 9090.

Check out apache reverse-proxy for more information on how to set this up :)

Read More

Thursday, February 1, 2018

Force Heroku PHP app to use https for both www and non-www versions

Leave a Comment

I have a PHP app on Heroku with an SSL certificate for the www version of the domain name. I need all requests (to both www and non-www) to go to via https, and I have added .htaccess to that affect. However, there are still circumstances where it's possible for a user to access the http version and I don't understand why.

Here is my .htaccess:

RewriteEngine on  RewriteCond %{HTTPS}::%{HTTP_HOST} ^off::(?:www\.)?(.+)$ RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R] 

My understanding is that this should force all users to access via https://www, but that doesn't always happen. For example, Google sometimes provides search results without the https and the links open insecure http instead.

Any ideas about what I'm doing wrong?

2 Answers

Answers 1

first redirect to the same host-name on :443, then redirect to www.. ordinary www. is just an alias in DNS, while most use the shorter non-www hostname for websites. you might have to extend the certificate, because it requires both host-names explicitly added, unless it's wild-carded.

one does not have to filter for the host-name:

RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] 

also see this answer here, concerning robots.txt with enforced SSL.

Answers 2

Try the following rules and let me know if it works or not these rule will use https request instead of http or www and non-www version. The following rule will now redirect the user to the something like this.

https://www.example.com/

RewriteEngine On  RewriteCond %{HTTP_HOST} !^www\. [NC,OR] RewriteCond %{HTTPS} !on RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC] RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE] 

Hope this will help to achieve what you wanted

Read More

Tuesday, January 23, 2018

ruby open ssl api for encrypted key (without nodes option)

Leave a Comment

On a linux machine with openssl lib installed, when you perform “openssl pkcs12” with “-nodes” option then you get output with unencrypted private key but if you skip the –nodes option then output will have encrypted private key.

     e.g.              openssl pkcs12 -in test.pfx -out test.pem  

You should see private key encrypted like below

-----BEGIN ENCRYPTED PRIVATE KEY-----
MIIFDjBABgkqhkiGG7s=
-----END ENCRYPTED PRIVATE KEY-----

How do I achive the above using ruby's open ssl library?

This is how I am generating the private key with ruby:

    @private_key = OpenSSL::PKey::RSA.new 2048     @private_key.to_pem.to_s 

EDIT:

I guess my question how does this command encrypt the private key:

openssl pkcs12 -in test.pfx -out test.pem

whereas:

“openssl pkcs12 -nodes -in test.pfx -out test.pem"

does not. How do i get the same results using ruby?

1 Answers

Answers 1

There must be something more to this. Perhaps the question needs refined. From what I can tell, you want to print a private key in PEM format. I'm not a ruby programmer but I got this working in about 3 minutes by reading the on ruby-docs.org:

$ cat ssl.rb  require 'openssl' key = OpenSSL::PKey::RSA.new 2048 cipher = OpenSSL::Cipher.new 'AES-128-CBC' pass_phrase = 'my secure pass phrase goes here' key_secure = key.export cipher, pass_phrase puts key_secure 

Choose your cipher and your passphrase and voila, you have encrypted a key with a symmetric cipher:

$ ruby ssl.rb -----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: AES-128-CBC,D8062F93C8854E593602D503E1FAC309  UsNQt/Bq7QBldOBU7NW6miCDuC+ODpeplaWQ9BvJW4Wg7j0AbKgMZAn7juegAbjG JVkpdDNzhs37UVWmqwg64yYP6KEBGg4zCog2a993UHRvFTQb6tyugKHc+uFeyY+D ... -----END RSA PRIVATE KEY----- 

Is there something more you're trying to do?

--

EDIT: The Asker has clarified that the question is about which encryption is used by openssl pkcs12 when not using the -nodes option.

The -nodes option turns off DES encryption. This page shows that the default encryption for private key creation is triple DES, but I don't see the detail there about which DES option. This is also referred to in the manual for man pkcs12. In any case, it's not yet clear to me if you need to know exactly which cipher is used by openssl or if your question is now answered.

You can list ruby's available ciphers like this:

puts OpenSSL::Cipher.cipher  

(as specified in the docs)

On my system, quite a few DES ciphers are available with varying parameters:

des des-cbc des-cfb des-cfb1 des-cfb8 des-ecb des-ede des-ede-cbc des-ede-cfb des-ede-ofb des-ede3 des-ede3-cbc des-ede3-cfb des-ede3-cfb1 des-ede3-cfb8 des-ede3-ofb des-ofb des3 desx desx-cbc 

I'm not sure if the PKCS12 spec says which DES cipher should be used or if openssl just has a default. Are you trying to figure out which DES cipher is used by OpenSSL?

I looked a bit further through the openssl wiki and I found references to DES in CBC mode, so I'm guessing that the cipher you are looking for is DES-EDE3-CBC.

Sorry, I guess it's still not completely clear exactly what question you're trying to answer. If what you're trying to do is to find out exactly how openssl is encoding the private key when you don't use -nodes you can see that by cating the file into openssl asn1parse. Maybe this helps: you can start with your rsa private key in plain text as you got it from your ruby program:

$ cat key.pem -----BEGIN RSA PRIVATE KEY----- MIIEpA.... -----END RSA PRIVATE KEY $ cat key.pem | openssl asn1parse     0:d=0  hl=4 l=1188 cons: SEQUENCE           4:d=1  hl=2 l=   1 prim: INTEGER           :00 7:d=1  hl=4 l= 257 prim: INTEGER       ... 

You'll see that this is encoded as an ASN1 SEQUENCE of long integers.

But if you put your key through a roundtrip of pkcs12:

$ openssl pkcs12 -inkey key.pem -out key.pfx -export -nocerts -nodes (choose a password) $ openssl pkcs12 -in key.pfx -out outkey.pem -nodes (enter password) 

You'll find your key now wrapped in a new structure, which you can cat to asn1parse:

cat keyout.pem | openssl asn1parse     0:d=0  hl=4 l=1214 cons: SEQUENCE               4:d=1  hl=2 l=   1 prim: INTEGER           :00     7:d=1  hl=2 l=  13 cons: SEQUENCE               9:d=2  hl=2 l=   9 prim: OBJECT            :rsaEncryption 

You now have an ASN1 rsaEncryption Object with a payload of a large octet string.

Is this what you were trying to learn about? How these values are encapsulated in ASN1?

Read More

Saturday, December 23, 2017

Accessing Gmail (or a secure website) without getting a PKIX certification path error

Leave a Comment

Sending an e-mail via gmail resulted in getting a PKIX certification path error. The same applied to sending an e-mail from Tomcat.

After solving the issue, I hope you find this post useful. This post provides you with a step by step diagnosis for these kinds of errors.

Step 1: I tried to solve the problem using this post and another post, but that did not help me. In most cases this will be sufficient. You can use the keytool to list the certificates via 'keytool -list -keystore "%JAVA_HOME%/jre/lib/security/cacerts"'

I added the certificate by clicking the lock-icon of the gmail URL and exporting/importing the certificate to the cacert file of my used JDK version. I could see with keytool -list that the certificate was added. This process is described well in the (linked) posts.

Step 2A: Was I using the right truststore? I added the JVM arguments to direct the certificate search, like -Djavax.net.ssl.trustStore="..../jre/lib/security/cacerts" -Djavax.net.ssl.trustStorePassword="changeit".

Step 2B: When I change the value of the cacerts file to cacertsXYZ I get the error. So, this proofed that the 'cacert' was used.

Caused by: javax.mail.MessagingException: Can't send command to SMTP host; nested exception is: javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty

Step 2C: Was this also the case for my Tomcat webserver? I verified that in the cacerts of my JRE_HOME that the certificate was there. In Tomcat my JRE_HOME is "C:\Program Files\Java\jdk1.8.0_144\jre". My JAVA_HOME = C:\Program Files\Java\jdk1.8.0_144.

Step 3: I tried with publicly available 'SSLPoke' Java class to see whether I could connect with Google and or smtp.gmail.com. The results are in the listing: I could connect with SSL to google.com AND mail.google.com via port 443.

try {             SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();             // **Fail** TLS - SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket("smtp.gmail.com", 587);             // **Fail** SSL - SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket("smtp.gmail.com", 465);             // **OK**             SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket("google.com", 443);             // OK             SSLSocket sslsocket2 = (SSLSocket) sslsocketfactory.createSocket("mail.google.com", 443);              InputStream in = sslsocket.getInputStream();             OutputStream out = sslsocket.getOutputStream();             out.write(1); // write test byte to get reaction.             while (in.available() > 0) {                 System.out.print(in.read());             }             System.out.println("Successfully connected");         } catch (Exception exception) {             exception.printStackTrace();         } 

Step 4: The trusted store could be corrupt? I installed a newer version of the JDK1.8 being v152. I restarted the application without any success. Had this to do with the difference between JDK and JRE? Only the JRE has a lib\security\cacerts file. I tried both the SSL (465) and TLS (587) ports. Nope.

Step 5: Running openssl (with s_client -connect smtp.gmail.com:587 -starttls smtp) showed that my virus scanner (Avast) was prohibiting the sending of secure mail. So, for a moment I disabled this email-shield. That gave the following error:

java.lang.RuntimeException: javax.mail.AuthenticationFailedException

Step 6: After releasing the virusscanner web shield, using the openssl gave the following error: CN = Google Internet Authority G3 verify error:num=20:unable to get local issuer certificate.

OpenSSL> s_client -connect smtp.gmail.com:587 -starttls smtp CONNECTED(00000280) depth=1 C = US, O = Google Trust Services, CN = Google Internet Authority G3 verify error:num=20:unable to get local issuer certificate ....

Allowing the 'gmail account to be accessable from weakly authenticated apps', a setting in your google account, that finally yielded in correctly sending the e-mail. This is the link to the security settings of your Google account.

Step 7: Sending e-mail from another server may be a problem. Authentication errors are (still) the result. To overcome these errors, you can do:

Notice: The mkyong example is the base of my simple test application.

1 Answers

Answers 1

Finally I found the answer.

1 - Of course the google/gmail certifcates were ok ;-) Step 1 was performing these kinds of checks. Trying to add the certificate CA by hand, etc. See above.

2 - Step 2 was checking whether the known 'SSLPoke' Java class Java class could get contact with the secure website.

3 - After checking all above checks, executing 'openssl' showed that my virus scanner email-shield blocked the traffic. Stopping this defence for some time was step 3.

4 - Then I got the 'not authenticated' error from Gmail. Allowing the 'gmail account accessable from weakly authenticated apps', that finally gave a correctly sent e-mail. This is an Google account security setting

Read More

Saturday, December 16, 2017

Apache Forward Proxy With SSL Termination

Leave a Comment

I'm trying to set up an Apache Forward Proxy that terminates the SSL connection. The reason I'm trying to do this is to run Apache filters (specifically mod_pagespeed) on the returned code. Before I deal with mod_pagespeed, I'm testing this POC by trying to insert a header into the response (which will prove that I can edit the response), but I'm having issues with SSL proxying (non-SSL proxying works fine).

Note that I'm not concerned about any certificate errors or the like -- this is purely for internal testing.

I've got the server set up and see the X-MSCProxy Header on a non-SSL page:

jshannon-macbookpro:pagespeed_proxy jshannon$ curl -vv --proxy pagespeed_proxy:3ja82ad9@localhost:8080 -D - -o /dev/null http://www.slate.com  * TCP_NODELAY set * Connected to localhost (::1) port 8080 (#0) * Proxy auth using Basic with user 'pagespeed_proxy' > GET http://www.slate.com/ HTTP/1.1 > Host: www.slate.com ... >  < HTTP/1.1 200 OK HTTP/1.1 200 OK < Date: Mon, 30 Oct 2017 18:10:40 GMT Date: Mon, 30 Oct 2017 18:10:40 GMT < Server: Apache/2.2.29 (Amazon) Server: Apache/2.2.29 (Amazon) ... < Content-Length: 187051 Content-Length: 187051 ... < X-Instart-Request-ID: 8286987369135064135:FWP01-NPPRY22:1509387040:0 X-Instart-Request-ID: 8286987369135064135:FWP01-NPPRY22:1509387040:0 < Via: 1.1 172.17.0.2:8080 Via: 1.1 172.17.0.2:8080 < X-MSCProxy: SansPS X-MSCProxy: SansPS 

But when I make the same request to Slate's SSL page I don't see my proxy:

jshannon-macbookpro:pagespeed_proxy jshannon$ curl -vv --proxy pagespeed_proxy:3ja82ad9@localhost:8080 -D - -o /dev/null https://www.slate.com  * Connected to localhost (::1) port 8080 (#0) * Establish HTTP proxy tunnel to www.slate.com:443 * Proxy auth using Basic with user 'pagespeed_proxy' > CONNECT www.slate.com:443 HTTP/1.1 > Host: www.slate.com:443  < HTTP/1.0 200 Connection Established HTTP/1.0 200 Connection Established < Proxy-agent: Apache/2.4.25 (Debian) Proxy-agent: Apache/2.4.25 (Debian) <   * Proxy replied OK to CONNECT request * TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 * Server certificate: ssl004.insnw.net * Server certificate: GlobalSign CloudSSL CA - SHA256 - G3 * Server certificate: GlobalSign Root CA > GET / HTTP/1.1 > Host: www.slate.com > User-Agent: curl/7.54.0 > Accept: */* >   < Content-Length: 187044 Content-Length: 187044 < Connection: keep-alive Connection: keep-alive < Server: Apache/2.2.29 (Amazon) Server: Apache/2.2.29 (Amazon) < X-Instart-Request-ID: 762420041708891440:FWP01-NPPRY21:1509387251:0 X-Instart-Request-ID: 762420041708891440:FWP01-NPPRY21:1509387251:0 

I've found a lot of posts that say this is possible (and, technically, it should be) with various httpd.conf suggestions, but nothing I've tried has worked. Right now my httpd.conf looks like:

<VirtualHost *:8080>   ProxyRequests On   ProxyVia On    Header set X-MSCProxy SansPS    #SSLEngine On   # suggestion that this allows termination   ProxyPreserveHost On    SSLProxyEngine on   SSLProxyCheckPeerCN Off   SSLProxyCheckPeerExpire Off   SSLProxyCheckPeerName Off    SSLCertificateFile /etc/apache2/ssl/localhost.crt   SSLCertificateKeyFile /etc/apache2/ssl/localhost.key    ModPagespeed Off </VirtualHost> 

FWIW, when I enable SSLEngine on this proxy (as has been suggested) then the request simply doesn't work with this error from Apache:

[Mon Oct 30 18:20:20.705047 2017] [ssl:info] [pid 372:tid 140147985901312] [client 172.17.0.1:34012] AH01996: SSL handshake failed: HTTP spoken on HTTPS port; trying to send HTML error page [Mon Oct 30 18:20:20.705107 2017] [ssl:info] [pid 372:tid 140147985901312] SSL Library Error: error:1407609C:SSL routines:SSL23_GET_CLIENT_HELLO:http request -- speaking HTTP to HTTPS port!? 

Which I guess makes sense as the proxy protocol isn't expecting an HTTPS connection directly to the proxy.

1 Answers

Answers 1

I would try to use the output filter feautre fom apache.

https://www.modpagespeed.com/doc/configuration#apache_specific

AddOutputFilterByType MOD_PAGESPEED_OUTPUT_FILTER text/html

Read More

Saturday, December 2, 2017

How do I have Apache2 httpd use the ubuntu's CA cert for outbound SSL connections from Apache?

Leave a Comment

Note this is not a question about having apache accept inbound SSL connections.

I have an apache module that needs to make outbound SSL connections. When it attempts to, it gets this error:

Failed to send events: The OpenSSL library reported an error: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed:s3_clnt.c:1269:

This is indicating the SSL library that apache is using doesn't know about the (valid) certificate of the server that my module is trying to connect to.

The CA cert on my ubuntu system where this is running is fine, knows about this downstream cert, openssl s_client tells me everything is ok.

How do I tell Apache2 to use ubuntu's system CA cert to make outbound connections work?

update - I did an strace -e open httpd -X to see where it was trying to load certificates from. I see apache opening libssl.so, but then I don't see it even trying to open up the usual ssl.cnf or any certificates file.

snipped useless strace output

update2: As to how I'm creating the https request - I'm making the request from inside my custom apache module. My module .so is written in Rust, so the connection code looks basically like:

in mod_mine.so:

use hyper::Client; use hyper_tls::HttpsConnector; use tokio_core::reactor::Core;  let mut core = Core::new()?; let handle = core.handle(); let client = Client::configure()     .connector(HttpsConnector::new(4, &handle)?)     .build(&handle);  //actually a POST, but this gets the same error let request = client.get("https://saas.mycompany.io".parse()?); let result = core.run(request)?; ...  //process result 

1 Answers

Answers 1

I found a solution that works, though I'm not sure it is optimal.

openSSL takes the environment variable SSL_CERT_FILE. I can set this in my apache module source code.

use std::env; let cert_file = figure_out_cert_path();  //on ubuntu:  /etc/ssl/certs/ca-certificates.crt env::set_var("SSL_CERT_FILE", cert_file); 
Read More

Monday, November 20, 2017

In SSL/TLS communication with IIS, Certificate Request does not contain my client cert

Leave a Comment

One of my clients java/Cold Fusion application is trying to access my WCF web service endpoint using client certificate mutual authentication. We moved our wcf service to windows 2008 R2/IIS 7 machine and generated new certificate using 3rd party CA. After the change, client is getting 403.13 error. On investigation, I found that the Certificate Request does not include the new certificate in the distinguished names list. How can I configure IIS to include the client certificate in the trusted certificate list? enter image description here

1 Answers

Answers 1

You can't add trusted certificates, it's done on machine level. If you open MMC and add the certificate plugin you should be able to add it to the Trusted Root Certification Authorities on the server.

Read More

Monday, October 23, 2017

PrincipalContext LDAPS Self-Signed Certificate

Leave a Comment

We have an application that authenticates against a remote AD using LDAP, by IP address, over a VPN tunnel, using the following code:

using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, ldap.Host, ldap.Path.Replace("/", ""), ContextOptions.Negotiate, UserName, Password)) {     using (UserPrincipal user = UserPrincipal.FindByIdentity(pc, domainAndUsername))     {         if (user != null)         {             SAMAccountName = user.SamAccountName;             retVal = true;         }     } } 

This works great for normal, non-SSL LDAP. However, we've encountered a situation where we need to be connecting to LDAPS, via SSL, and it doesn't work. I've tried a ton of variations on the PrincipalContext constructor, but everything we do results in a failed connection, with this error:

System.DirectoryServices.AccountManagement.PrincipalServerDownException: The server could not be contacted. ---> System.DirectoryServices.Protocols.LdapException: The LDAP server is unavailable.    at System.DirectoryServices.Protocols.LdapConnection.Connect()    at System.DirectoryServices.Protocols.LdapConnection.SendRequestHelper(DirectoryRequest request, Int32& messageID)    at System.DirectoryServices.Protocols.LdapConnection.SendRequest(DirectoryRequest request, TimeSpan requestTimeout)    at System.DirectoryServices.AccountManagement.PrincipalContext.ReadServerConfig(String serverName, ServerProperties& properties)    --- End of inner exception stack trace ---    at System.DirectoryServices.AccountManagement.PrincipalContext.ReadServerConfig(String serverName, ServerProperties& properties)    at System.DirectoryServices.AccountManagement.PrincipalContext.DoServerVerifyAndPropRetrieval()    at System.DirectoryServices.AccountManagement.PrincipalContext..ctor(ContextType contextType, String name, String container, ContextOptions options, String userName, String password) 

We know it's not the LDAP server itself, as trying by the method discussed here connects without errors. I'm not really comfortable with using try...catch for logic flow, and I've read of some other issues with this method (like not properly respecting certificates and such), so I'm trying to make this work with PrincipalContext.

Could anybody offer me some guidance here? I'm going crazy on this one.

EDIT: Upon some further research, it looks like this may be a problem with self-signed certificates.

EDIT 2: After breaking it down into X509 chain calls, I'm getting this specific error:

PartialChain A certificate chain could not be built to a trusted root authority.

Looking at that, you'd think it's just a matter of adding the CA as a trusted root, but that didn't seem to fix the problem.

1 Answers

Answers 1

Check this answer by Gabriel Luci

Are you sure it supports SSL and that the firewall is open to allow that connection?

LDAP uses port 389. LDAPS uses port 636.

If you have the telnet client installed, you can use it to check the connectivity:

telnet yourdomain.com 636 If you get a blank screen, it worked. If it can't connect, it will tell you.

If that is open and it still does not work, it could be using a self-signed SSL certificate. Check the Windows event log for certificate-related errors.

I've also used Chrome to check the certificate. You have to run chrome like this:

chrome.exe --explicitly-allowed-ports=636 Then browse to https://yourdomain.com:636 and see if it gives you any certificate errors. Then you can actually see the certificate. If that's the problem, you may be able to import the certificate and explicitly trust it.

Read More

Monday, October 16, 2017

Tomcat webservice configuration

Leave a Comment

I have made a webservice (XML-RPC) built on Tomcat 8.5.16 it makes digital signiture of the data sent to it and saves them in MySQL (or MariaDB). It runns fine on windows (without security). Now I want to deploy it on CentOS (with SSL security). always makes errors addressed in: Failed to initialize end point associated with ProtocolHandler and: Tomcat mariadb connection configuration

To understand the problem:

  1. I have made a simple XML-RPC web service (summ of 2 nummbers) and it runns correctly.
  2. I have made a java application that accesses the database and it runns correctly.

I couldnt define the problem of the main app. could you please help me?

1 Answers

Answers 1

It look like your tomcat cannot open network sockets due to permission problems. Could be firewall and / or SELINUX.

You are using CENTOS. Did you opened your firewall :

firewall-cmd --permanent --zone=public --add-service=http firewall-cmd --permanent --zone=public --add-service=https firewall-cmd --reload 

Also try to turn of SELINUX security for a moment with

setenforce=0 

When this changes are made, restart tomcat.

I also suggest you to create a virtual CentOS image and try there first.

Read More