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

Monday, July 9, 2018

Kibana container to elasticsearch cloud auth err

Leave a Comment

I have a production instance of elasticsearch 5.6.9 deployed on elastic.cloud.

WIth an http elastic all is OK but I would run a localhost kibana connected to that https instance!

I have tried:

docker run --name kibana-prod-user       -e ELASTICSEARCH_URL=https://####.eu-west-1.aws.found.io:9243       -e ELASTICSEARCH_PASSWORD=####       -v /host/workspace/cert:/usr/share/elasticsearch/config/certificates       -p 3501:5601 --b kibana 

but i get:

auth err

In my mount dir I have put the cert.cer of elastic cloud.

Any ideas?

Thank you very much

1 Answers

Answers 1

I have find the solution, after understand that the error wasn't a certificate problem.

The right script for kibana 5.6.10 is:

docker run --name kibana-prod-provider -v "$(pwd)":/etc/kibana/ -p 3502:5601 --rm kibana 

because the ELASTICSEARCH_PASSWORD envvar is not managed by the docker file, only le URL is.

Then in the $(pwd) directory I have put this kibana.yml file:

server.host: '0' elasticsearch.url: 'https://###.eu-west-1.aws.found.io:9243' elasticsearch.username: elastic elasticsearch.password: ### 
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

Tuesday, January 2, 2018

Using certificates.cer with NodeJs HTTPS

Leave a Comment

I have generated a .cer file for IOS push notifications and I would ike to use it with NodeJS HTTPS module.

The only examples I found for HTTPS module work with .pem and .sfx files, not .cer :

var options = {   key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),   cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') };  or   var options = {   pfx: fs.readFileSync('server.pfx') }  https.createServer(options, function (req, res) {   res.writeHead(200);   res.end("hello world\n"); }).listen(8000); 

Any solution ?

4 Answers

Answers 1

A .cer file can be encoded using two different formats: PEM and DER.

If your file is encoded using the PEM format, you could just use it like any other .pem file (more info on that can be found in the Node.js documentation):

const https = require("https");  const options = {     key: fs.readFileSync("key.pem", "utf8"),     cert: fs.readFileSync("cert.cer", "utf8") };  https.createServer(options, (req, res) => {     res.writeHead(200);     res.end("Hello world"); }).listen(8000); 

If your file's encoded using the DER format, you first need convert it to a .pem file using OpenSSL (the command was taken from here):

openssl x509 -inform der -in cert.cer -out cert.pem 

and then can use the above code with the cert filename being cert.pem instead of cert.cer:

const https = require("https");  const options = {     key: fs.readFileSync("key.pem", "utf8"),     cert: fs.readFileSync("cert.pem", "utf8") };  https.createServer(options, (req, res) => {     res.writeHead(200);     res.end("Hello world"); }).listen(8000); 

In case you have the the key of the certificate authority that matches your cert.cer file, you can include it in the options argument of https.createServer as following (the code example assumes the file is name ca.pem and that it is encoded using the PEM format):

const https = require("https");  const options = {     ca: fs.readFileSync("ca.pem", "utf8"),     key: fs.readFileSync("key.pem", "utf8"),     cert: fs.readFileSync("cert.pem", "utf8") };  https.createServer(options, (req, res) => {     res.writeHead(200);     res.end("Hello world"); }).listen(8000); 

For more information about https.createServer and its arguments, check out the documentation.

Note: all of the options above assume that you also have a public key encoded in the PEM format named key.pem and that the .cer file is named cert.cer. If you don't have a public key, please comment or add it to the question itself and I will update my answer accordingly.

If you're unsure which format your file's encoded in, you could try both options see which one works out for you.

Answers 2

This is an example using crt, you can convert a cer to crt in case it doesn't work:

var express  = require('express'); var app      = express(); var fs       = require('fs'); var https    = require('https');  var credentials = {     ca: fs.readFileSync(__dirname+"/ssl/certificate.ca-crt", 'utf8'), //certificate concatenation or intermediate certificates     key: fs.readFileSync(__dirname+"/ssl/mydomain.com.key", 'utf8'), //SSL key     cert: fs.readFileSync(__dirname+"/ssl/certificate.crt", 'utf8') //the certificate };  app.configure(function() {      // set up your express application  });  var httpsServer = https.createServer(credentials, app); httpsServer.listen(443); 

Taken from here (in spanish): salvatorelab.es
You can also see examples of what those files (crt, ca-crt...) contain or look like.

Answers 3

@Mohit, You can convert your cer to pem using command below.

openssl x509 -inform der -in certificate.cer -out certificate.pem 

Source

Answers 4

HTTPS/TLS encryption is asymmetric, there are two parts to make it work, a public key and a private key.

The .cer file you get from Apple Push Notification Services (APNS) after you have uploaded the certificate signing request (CSR) is the signed public key.

The location of the private key depends on how you generated it.

If you're on a mac and using the Apple Keychain application, these two links, [1] and [2], suggest that you import the .cer public key back into Keychain.

Then use the Export option to get a single password protected .p12 file (in PKCS12 format) that will contain both the private and public keys.

In your node.js application, the exported .p12 file and password can be used as the pfx and passphrase options to https.createServer, e.g:

var options = {   pfx: fs.readFileSync('./exported-cert.p12'),   passphrase: 'password-that-was-set-on-export' };  https.createServer(options, ...); 
Read More

Saturday, November 4, 2017

Why am I getting SSLError in google-analytics in iOS 9.3.2 and 10.0.1?

Leave a Comment

I have integrated Google Analytics 3.15. It is working fine for all other iOS versions than iOS 9.3.2 and 10.0.1. I am getting following error in to this.

NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802) Dispatch error: Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x1701157b0>, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, NSErrorPeerCertificateChainKey=( "<cert(0x1018ed200) s: *.google-analytics.com i: Google Internet Authority G2>", "<cert(0x1018efa00) s: Google Internet Authority G2 i: GeoTrust Global CA>", "<cert(0x1018f0200) s: GeoTrust Global CA i: Equifax Secure Certificate Authority>" 

I have setup Info.plist on the basis of following analysis. On Terminal I have hit following command:

/usr/bin/nscurl --ats-diagnostics --verbose https://ssl.google-analytics.com 

enter image description here

I have got one more information by hitting following command.

curl -kvI https://ssl.google-analytics.com 

Output of the above command: enter image description here

Please find my info.plist for ATS: enter image description here I have tried with following links:

Please help me to understand what is the mistake I am doing here.

0 Answers

Read More

Thursday, August 24, 2017

Usage difference between SSL_add0_chain_cert and SSL_add1_chain_cert?

Leave a Comment

In OpenSSL documentation it says:

All these functions are implemented as macros. Those containing a 1 increment the reference count of the supplied certificate or chain so it must be freed at some point after the operation. Those containing a 0 do not increment reference counts and the supplied certificate or chain MUST NOT be freed after the operation.

But when I tried to look at examples of cases about which one should be used where I'm confused.

First OpenSSL:

It uses SSL_add0_chain_cert itself in the SSL_CTX_use_certificate_chain_file function of ssl_rsa.c. Here is the source:

static int use_certificate_chain_file(SSL_CTX *ctx, SSL *ssl, const char *file) {     if (ctx)         ret = SSL_CTX_use_certificate(ctx, x);     else         ret = SSL_use_certificate(ssl, x);     ......     while ((ca = PEM_read_bio_X509(in, NULL, passwd_callback,                                    passwd_callback_userdata))            != NULL) {         if (ctx)             r = SSL_CTX_add0_chain_cert(ctx, ca);         else             r = SSL_add0_chain_cert(ssl, ca);     ...... } 

Second usage I see is OpenResty Lua:

It uses SSL_add0_chain_cert in one way of setting certificate (ngx_http_lua_ffi_ssl_set_der_certificate), see here:

int ngx_http_lua_ffi_ssl_set_der_certificate(ngx_http_request_t *r, const char *data, size_t len, char **err) {     ......     if (SSL_use_certificate(ssl_conn, x509) == 0) {         *err = "SSL_use_certificate() failed";         goto failed;     }     ......     while (!BIO_eof(bio)) {          x509 = d2i_X509_bio(bio, NULL);         if (x509 == NULL) {             *err = "d2i_X509_bio() failed";             goto failed;         }          if (SSL_add0_chain_cert(ssl_conn, x509) == 0) {             *err = "SSL_add0_chain_cert() failed";             goto failed;         }     }      BIO_free(bio);      *err = NULL;     return NGX_OK; failed:     ....... } 

Yet uses SSL_add1_chain_cert in another way (ngx_http_lua_ffi_set_cert), see here:

int ngx_http_lua_ffi_set_cert(ngx_http_request_t *r,     void *cdata, char **err) {     ......     if (SSL_use_certificate(ssl_conn, x509) == 0) {         *err = "SSL_use_certificate() failed";         goto failed;     }      x509 = NULL;      /* read rest of the chain */      for (i = 1; i < sk_X509_num(chain); i++) {          x509 = sk_X509_value(chain, i);         if (x509 == NULL) {             *err = "sk_X509_value() failed";             goto failed;         }          if (SSL_add1_chain_cert(ssl_conn, x509) == 0) {             *err = "SSL_add1_chain_cert() failed";             goto failed;         }     }      *err = NULL;     return NGX_OK; /* No free of x509 here */  failed: ...... } 

Yet I don't see a clear difference of what changes when calling these two in Lua, and it doesn't seem like the cert X509, when set successfully, gets freed in either case. According to my understanding of the OpenSSL doc, I should expect X509_free(x509) gets called somewhere after SSL_add1_chain_cert called on that x509. Is that the correct understanding?

Last, the Openssl implementation of ssl_cert_add1_chain_cert (what boils down from SSL_add1_chain_cert macro) does indeed show it's just a wrapper of ssl_cert_add0_chain_cert with reference count incremented on the cert, but how should that be reflected in the calling process?

int ssl_cert_add1_chain_cert(SSL *s, SSL_CTX *ctx, X509 *x) {     if (!ssl_cert_add0_chain_cert(s, ctx, x))         return 0;     X509_up_ref(x);     return 1; } 

Now Nginx only deals with another function SSL_CTX_add_extra_chain_cert which leaves the burden of such choice behind, as it does not deal with switching cert per SSL connection basis. In my case I need to patch Nginx with this capability, switching cert per connection (but without using Lua).

So I'm not sure which one I should be using, SSL_add0_chain_cert or SSL_add1_chain_cert? And what's the freeing practice here?

0 Answers

Read More

Friday, June 9, 2017

R: download data securely using TLS/SSL

Leave a Comment

Official Statements

In the past the base R download.file() was unable to work with HTTPS protocols and it was necessary to use RCurl. Since R 3.3.0:

All builds have support for https: URLs in the default methods for download.file(), url() and code making use of them. Unfortunately that cannot guarantee that any particular https: URL can be accessed. ... Different access methods may allow different protocols or use private certificate bundles ...

The download.file() help still says:

Contributed package 'RCurl' provides more comprehensive facilities to download from URLs.

which (by the way includes cookies and headers management).

Based on RCurl FAQ (look for "When I try to interact with a URL via https, I get an error"), HTTPS URLs can be managed with:

getURL(url, cainfo="CA bundle") 

where CA bundle is the path to a certificate authority bundle file. One such a bundle is available from the curl site itself:
https://curl.haxx.se/ca/cacert.pem

Current status

For many HTTPS websites download.file() works as stated:

download.file(url="https://www.google.com", destfile="google.html") download.file(url="https://curl.haxx.se/ca/cacert.pem", destfile="cacert.pem") 

As regards RCurl, using the cacert.pem bundle, downloaded above, one might get an error:

library(RCurl) getURL("https://www.google.com", cainfo = "cacert.pem")     # Error in function (type, msg, asError = TRUE)  :  #   SSL certificate problem: unable to get local issuer certificate 

In this instance, simply removing the reference to the certificate bundle solves the problem:

getURL("https://www.google.com")                      # works getURL("https://www.google.com", ssl.verifypeer=TRUE) # works 

ssl.verifypeer = TRUE is used to be sure that success is no due to getURL() suppressing security. The argument is documented in RCurl FAQ.

However, in other instances, the connection fails:

getURL("https://curl.haxx.se/ca/cacert.pem") # Error in function (type, msg, asError = TRUE)  :  #  error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version 

And similarly, using the previously downloaded bundle:

getURL("https://curl.haxx.se/ca/cacert.pem", cainfo = "cacert.pem") # Error in function (type, msg, asError = TRUE)  :  #   error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version 

The same error happens even when suppressing the security:

getURL("https://curl.haxx.se/ca/cacert.pem", ssl.verifypeer=FALSE) # same error as above 

Questions

  1. How to use HTTPS properly in RCurl?
  2. As regards mere file downloads (no headers, cookies, etc.), is there any benefit in using RCurl instead of download.file()?
  3. Is RCurl become obsolete and should we opt for curl?

0 Answers

Read More

Saturday, May 20, 2017

Subject Alternative Name Missing & ERR_SSL_VERSION_OR_CIPHER_MISMATCH

Leave a Comment

I followed this answer to make https://localhost:3000/ work in Chrome & Mac. Today, it suddenly does not work anymore.

https://localhost:3000 gives Not Secure:

Subject Alternative Name Missing The certificate for this site does not contain a Subject Alternative Name extension containing a domain name or IP address. 

I re-trusted this certificate by following the previous steps, it did not help. Then, I saw this answer, I need to remake ssl keys.

I make v3.ext:

authorityKeyIdentifier=keyid,issuer basicConstraints=CA:FALSE keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment subjectAltName = @alt_names  [alt_names] DNS.1 = localhost 

Then,

openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -sha256 -extfile v3.ext 

However, it returns

unknown option -extfile req [options] <infile >outfile where options  are  -inform arg    input format - DER or PEM  -outform arg   output format - DER or PEM  ... ... 

Does anyone know what's wrong with my openssl command?

Otherwise, does anyone know how to fix this Subject Alternative Name Missing or NET::ERR_CERT_COMMON_NAME_INVALID error?

enter image description here

Edit 1: I tried to follow this answer and here is my example-com.conf:

[ req ] default_bits        = 2048 default_keyfile     = server-key.pem distinguished_name  = subject req_extensions      = req_ext x509_extensions     = x509_ext string_mask         = utf8only  # The Subject DN can be formed using X501 or RFC 4514 (see RFC 4519 for a description). #   Its sort of a mashup. For example, RFC 4514 does not provide emailAddress. [ subject ] countryName         = Country Name (2 letter code) countryName_default     = US  stateOrProvinceName     = State or Province Name (full name) stateOrProvinceName_default = NY  localityName            = Locality Name (eg, city) localityName_default        = New York  organizationName         = Organization Name (eg, company) organizationName_default    = Example, LLC  # Use a friendly name here because its presented to the user. The server's DNS #   names are placed in Subject Alternate Names. Plus, DNS names here is deprecated #   by both IETF and CA/Browser Forums. If you place a DNS name here, then you #   must include the DNS name in the SAN too (otherwise, Chrome and others that #   strictly follow the CA/Browser Baseline Requirements will fail). commonName          = Common Name (e.g. server FQDN or YOUR name) commonName_default      = Example Company  emailAddress            = Email Address emailAddress_default        = test@example.com  # Section x509_ext is used when generating a self-signed certificate. I.e., openssl req -x509 ... [ x509_ext ]  subjectKeyIdentifier        = hash authorityKeyIdentifier  = keyid,issuer  # You only need digitalSignature below. *If* you don't allow #   RSA Key transport (i.e., you use ephemeral cipher suites), then #   omit keyEncipherment because that's key transport. basicConstraints        = CA:FALSE keyUsage            = digitalSignature, keyEncipherment subjectAltName          = @alternate_names nsComment           = "OpenSSL Generated Certificate"  # RFC 5280, Section 4.2.1.12 makes EKU optional #   CA/Browser Baseline Requirements, Appendix (B)(3)(G) makes me confused #   In either case, you probably only need serverAuth. # extendedKeyUsage  = serverAuth, clientAuth  # Section req_ext is used when generating a certificate signing request. I.e., openssl req ... [ req_ext ]  subjectKeyIdentifier        = hash  basicConstraints        = CA:FALSE keyUsage            = digitalSignature, keyEncipherment subjectAltName          = @alternate_names nsComment           = "OpenSSL Generated Certificate"  # RFC 5280, Section 4.2.1.12 makes EKU optional #   CA/Browser Baseline Requirements, Appendix (B)(3)(G) makes me confused #   In either case, you probably only need serverAuth. # extendedKeyUsage  = serverAuth, clientAuth  [ alternate_names ]  DNS.1       = localhost  # IPv4 localhost IP.1       = 127.0.0.1  # IPv6 localhost IP.2     = ::1 

Then, I did

openssl req -config example-com.conf -new -x509 -sha256 -newkey rsa:2048 -nodes -keyout example-com.key.pem -days 365 -out example-com.cert.pem 

Reopen https://localhost:3000 in Chrome gives me

localhost uses an unsupported protocol. ERR_SSL_VERSION_OR_CIPHER_MISMATCH 

Could anyone help?

1 Answers

Answers 1

I suggest the following solution: create self-signed CA certificate and the web server certificate signed by this CA. When you install this small chain to your web server it will work with Chrome.

Create configuration file for your CA MyCompanyCA.cnf with contents (you can change it to your needs):

[ req ] distinguished_name  = req_distinguished_name x509_extensions     = root_ca  [ req_distinguished_name ] countryName             = Country Name (2 letter code) countryName_min         = 2 countryName_max         = 2 stateOrProvinceName     = State or Province Name (full name) localityName            = Locality Name (eg, city) 0.organizationName      = Organization Name (eg, company) organizationalUnitName  = Organizational Unit Name (eg, section) commonName              = Common Name (eg, fully qualified host name) commonName_max          = 64 emailAddress            = Email Address emailAddress_max        = 64  [ root_ca ] basicConstraints            = critical, CA:true 

Create the extensions configuration file MyCompanyLocalhost.ext for your web server certificate:

subjectAltName = @alt_names extendedKeyUsage = serverAuth  [alt_names] DNS.1   = localhost DNS.2   = mypc.mycompany.com 

Then execute the following commands:

openssl req -x509 -newkey rsa:2048 -out MyCompanyCA.cer -outform PEM -keyout MyCompanyCA.pvk -days 10000 -verbose -config MyCompanyCA.cnf -nodes -sha256 -subj "/CN=MyCompany CA"  openssl req -newkey rsa:2048 -keyout MyCompanyLocalhost.pvk -out MyCompanyLocalhost.req -subj /CN=localhost -sha256 -nodes openssl x509 -req -CA MyCompanyCA.cer -CAkey MyCompanyCA.pvk -in MyCompanyLocalhost.req -out MyCompanyLocalhost.cer -days 10000 -extfile MyCompanyLocalhost.ext -sha256 -set_serial 0x1111 

As result you will get MyCompanyCA.cer, MyCompanyLocalhost.cer and MyCompanyLocalhost.pvk files that you can install to the web server.

How to check that it works with Chrome before installing certificates to the web server. Execute the following command on your local PC to run web server simulator:

openssl s_server -accept 15000 -cert MyCompanyLocalhost.cer -key MyCompanyLocalhost.pvk -CAfile MyCompanyCA.cer -WWW 

Then you can access this page at https://localhost:15000/ You will see an error that MyCompanyLocalhost.cer is not trusted, if you want to eliminate this error also - then install MyCompanyCA.cer to the certificate trusted list of your OS.

Read More

Tuesday, May 9, 2017

Ember fastboot works with at http api host but not an https one

Leave a Comment
import DS from 'ember-data';  export default DS.JSONAPIAdapter.extend({   host: 'http://api.theapothecaryshoppe.com',   // host: 'https://api.theapothecaryshoppe.com' }); 

The regular host works, but when I use https I get this error:

Error: The adapter operation was aborted at EmberError.AdapterError (/home/nick/the-apothecary-shoppe/portal-ember/tmp/broccoli_merge_trees-output_path-j1H7NK9S.tmp/fastboot/vendor.js:85927:16) at EmberError.ErrorClass (/home/nick/the-apothecary-shoppe/portal-ember/tmp/broccoli_merge_trees-output_path-j1H7NK9S.tmp/fastboot/vendor.js:85952:24) at ajaxError (/home/nick/the-apothecary-shoppe/portal-ember/tmp/broccoli_merge_trees-output_path-j1H7NK9S.tmp/fastboot/vendor.js:87597:15) at Object.hash.error (/home/nick/the-apothecary-shoppe/portal-ember/tmp/broccoli_merge_trees-output_path-j1H7NK9S.tmp/fastboot/vendor.js:87269:23) at fire (/home/nick/the-apothecary-shoppe/portal-ember/node_modules/jquery-deferred/lib/jquery-callbacks.js:78:30) at Object.fireWith (/home/nick/the-apothecary-shoppe/portal-ember/node_modules/jquery-deferred/lib/jquery-callbacks.js:188:7) at Object.fire [as reject] (/home/nick/the-apothecary-shoppe/portal-ember/node_modules/jquery-deferred/lib/jquery-callbacks.js:195:10) at ClientRequest.onError (/home/nick/the-apothecary-shoppe/portal-ember/node_modules/najax/lib/najax.js:208:9) at emitOne (events.js:96:13) at ClientRequest.emit (events.js:188:7) at TLSSocket.socketErrorListener (_http_client.js:309:9) at emitOne (events.js:96:13) at TLSSocket.emit (events.js:188:7) at emitErrorNT (net.js:1281:8) at _combinedTickCallback (internal/process/next_tick.js:80:11) at process._tickCallback (internal/process/next_tick.js:104:9) 

Any thoughts why? this is seriously befuddling me.

1 Answers

Answers 1

Your issue seems to be related to your SSL configuration and more specifically that the certificate you are using is not correctly validated by the CA.

To be sure that this is the case, you can try setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable to 0. This is only temporary and for debugging purposes, you shouldn't use it in production!

If that fixes it, I would recommend looking into your certificate validity. You can now even create one for free using LetsEncrypt and you won't get any CA problem.

Read More

Saturday, June 25, 2016

certificate problems trying to send email with libcurl

Leave a Comment

This is my libcurl code. I am trying to send email to my own email domain in linux.

This is my sample libcurl code.

curl_easy_setopt(curl, CURLOPT_USERNAME, "username@mydomain.com");     curl_easy_setopt(curl, CURLOPT_PASSWORD, "mypassword");     curl_easy_setopt(curl, CURLOPT_URL, "smtp://mail.mydomain.com:25");     curl_easy_setopt(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL);     curl_easy_setopt(curl, CURLOPT_MAIL_FROM, FROM);     recipients = curl_slist_append(recipients, TO);     curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);     curl_easy_setopt(curl, CURLOPT_INFILESIZE, file_size);     curl_easy_setopt(curl, CURLOPT_READFUNCTION, fileBuf_source);     curl_easy_setopt(curl, CURLOPT_READDATA, &file_upload_ctx);     curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);     curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); //Dont display Curl Connection data Change 1L to 0      res = curl_easy_perform(curl); 

When I run this code, I am getting the below error.

* Rebuilt URL to: smtp://mail.mydomain.com:25/ * Hostname was NOT found in DNS cache *   Trying <My mail domain Ip address>... * Connected to mail.mydomain.com (<My mail domain Ip address>) port 25 (#0) < 220 mail.mydomain.com ESMTP > EHLO client6 < 250-mail.mydomain.com < 250-PIPELINING < 250-SIZE 20480000 < 250-VRFY < 250-ETRN < 250-STARTTLS < 250-AUTH PLAIN LOGIN < 250-ENHANCEDSTATUSCODES < 250-8BITMIME < 250 DSN > STARTTLS < 220 2.0.0 Ready to start TLS * successfully set certificate verify locations: *   CAfile: none   CApath: /etc/ssl/certs * SSL certificate problem: self signed certificate * Closing connection 0 curl_easy_perform() failed: Peer certificate cannot be authenticated with given CA certificates 

1 Answers

Answers 1

Your issue is that your server is providing a self-signed certificate so curl is not able to verify its provenance. You have several options:

  • The best option is to get a server certificate that is signed by a well-known certificate authority. Some CAs will issue a certificate you can use for free; search for "free ssl certificate". You will need to be able to provide some proof that you control the domain.

  • You can install your self-signed certificate to the list of trusted CAs on the computer(s) that run your libcurl code. The procedure to do this depends on your OS (even different distributions of Linux may do this differently). This link is a decent starting point for Linux.

  • Your program can tell libcurl to verify with the self-signed certificate. See Adding self-signed SSL certificate for libcurl.

  • You can create your own certificate authority and use either of the previous two approaches. The advantage of this over self-signing is it decouples the signing and the signed certificates. If you want to change the server certificate (e.g. if it expires or the host name changes) you don't necessarily need to reconfigure all the clients.

  • For completeness, you could disable verification by setting CURLOPT_SSL_VERIFYPEER to 0. This is highly discouraged, however, as it makes the access insecure. You should only do this for testing purposes, or in the rare case that the network between client and server is guaranteed to be secure.

Read More

Saturday, June 11, 2016

Loading Azure certificate when NOT using custom domain names

1 comment

As I understand if someone doesn't want to use a custom domain name and instead plans on using *.azurewebsite.net domain assigned to the website by Azure, then HTTPS is already enabled with a certificate from Microsoft(I know this is not as secure as using a custom domain name). How would be I able to load this certificate programmatically. Currently I use the following method to load a certificate from local machine or Azure :

public static X509Certificate2 LoadFromStore(string certificateThumbprint,bool hostedOnAzure) {     var s = certificateThumbprint;      var thumbprint = Regex.Replace(s, @"[^\da-zA-z]", string.Empty).ToUpper();      var store = hostedOnAzure ? new X509Store(StoreName.My, StoreLocation.CurrentUser) : new X509Store(StoreName.Root, StoreLocation.LocalMachine);       try     {         store.Open(OpenFlags.ReadOnly);          var certCollection = store.Certificates;          var signingCert = certCollection.Find(X509FindType.FindByThumbprint, thumbprint, false);          if (signingCert.Count == 0)         {             throw new FileNotFoundException(string.Format("Cert with thumbprint: '{0}' not found in certificate store. Also number of certificates in the sotre was {1}", thumbprint, store.Certificates.Count));         }          return signingCert[0];     }     finally     {         store.Close();     } } 

I assume the culprit is the following line of code :

new X509Store(StoreName.My, StoreLocation.CurrentUser)  

because when I get an exception it tells me there is no certificate in the store although I pass the correct certificate Thumbprint(I grab the thumbprint from Chrome manually).

1 Answers

Answers 1

You will not be able to access this certificate programmatically in your WebApp as this certificate is not really installed on the Azure WebApp. Azure WebApps have a front-end server which does a "kind of" SSL Offloading so the WebApp actually never has access to this particular certificate. Why exactly you want to read this certificate though ?

Typically if there is a need for certificates in WebApps, you would install client certificates and pass them to services for Authentication as mentioned in https://azure.microsoft.com/en-us/blog/using-certificates-in-azure-websites-applications/ and those certificates you can access programmatically (code snippet mentioned in the same article)

But I am not sure what exactly you want to achieve by reading the server certificate

Read More

Wednesday, April 20, 2016

Check in the onReceivedSslError() method of a WebViewClient if a certificate is signed from a specific self-signed CA

Leave a Comment

I would like to override the onReceivedSslError() of a WebViewClient. Here I want to check if the error.getCertificate() certificate is signed from a self-signed CA and, only in this case, call the handler.proceed(). In pseudo-code:

@Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {     SslCertificate serverCertificate = error.getCertificate();      if (/* signed from my self-signed CA */) {         handler.proceed();     }     else {         super.onReceivedSslError(view, handler, error);     } } 

The public key of my CA is saved in a BouncyCastle resource called rootca.bks. How can I do?

3 Answers

Answers 1

based on documentation:

Have you tried using the method getIssuedBy().getDName() of class SslCertificate. This method returns a String representing "The entity that issued this certificate".

Take a look here: http://developer.android.com/reference/android/net/http/SslCertificate.html#getIssuedBy()

Then you just need to know wich string is returned when it is self signed.

EDIT: I think that if it is selfsigned, that should return empty string, and if not, it would return the entity

Regards

Answers 2

I think this should work (SSL_IDMISMATCH means "Hostname mismatch").

@Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {     SslCertificate serverCertificate = error.getCertificate();      if (error.hasError(SSL_UNTRUSTED)) {         // Check if Cert-Domain equals the Uri-Domain         String certDomain = serverCertificate.getIssuedTo().getCName();         if(certDomain.equals(new URL(error.getUrl()).getHost())) {           handler.proceed();         }     }     else {         super.onReceivedSslError(view, handler, error);     } } 

If "hasError()" is not working, try error.getPrimaryError() == SSL_IDMISMATCH

Check Documentation of SslError for all error-types.

EDIT: I tested the function on my own self-cert server (its a Xampp), and I got Error #3. That means you have to check for error.hasError(SslError.SSL_UNTRUSTED) for a self-signed cert.

Answers 3

i think you can get help from here http://developer.android.com/training/articles/security-ssl.html

Read More

Sunday, March 27, 2016

How to provision a CloudFront distribution with an ACM Certificate using Cloud Formation

Leave a Comment
This summary is not available. Please click here to view the post.
Read More