Can nodejs generate SSL certificates? - node.js

I'm writing a proxy support HTTPS-HTTPS proxy. Before i use Python as the main programming language, but i'm interested in node.js now, so i prepare to migrate.
The largest problem i'm facing is that i don't know how to generate CA and other server certificates in node.js. In Python, there is pyOpenSSL which is awesome. I don't find something similar in node.js until now.
Maybe i should use openssl-fork method? But how to handle the interactive operation in openssl.
Thank you.

Use shell for certificate:
openssl genrsa -out server-key.pem 1024
openssl req -new -key server-key.pem -out server-csr.pem
openssl x509 -req -in server-csr.pem -signkey server-key.pem -out server-cert.pem
Then use them in node.js
var https = require('https');
https.createServer({
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem')
},
function (req,res) {
...
})
EDIT:
You can also give a try to this project in NPM :
https://npmjs.org/package/openssl-wrapper
I found it searching the NPM repo : https://npmjs.org/search?q=openssl
I did not tried or checked it myself, but it looks like a way to generate the certificate using node, which is the original question.
var openssl = require('openssl-wrapper');
var password = 'github';
return openssl.exec('genrsa', {des3: true, passout: 'pass:' + password, '2048': false}, function(err, buffer) {
console.log(buffer.toString());
});
I'd be interested by a feedback. ;)

In case somebody does want to programatically create CSRs from node.js, I have created a nodejs module which uses openssl to create a private key and a CSR.
Edit: Use pem instead. It is much more complete and probably more reliable.
Edit2: Actually, pem is also just a simple wrapper over openssh. For a pure js implementation, look into forge

node-forge allow that. Nothing to say more. DOES NOT use openssl shell command internally.
https://github.com/digitalbazaar/forge#x509

there is a pure javascript library called "Jsrsasign" to generate CSR certificates.
const r = require("jsrsasign");
const kp = r.KEYUTIL.generateKeypair("RSA", 2048);
const csr = r.KJUR.asn1.csr.CSRUtil.newCSRPEM({
subject: {},
sbjpubkey: kp.pubKeyObj,
sigalg: "SHA256withRSA",
sbjprvkey: kp.prvKeyObj,
});
const privateKey = r.KEYUTIL.getPEM(kp.prvKeyObj, "PKCS1PRV");
for more docs visit http://kjur.github.io/jsrsasign/

None of the node libraries seem to support the options I need, so I use the openssl executable.
import { execSync } from 'child_process'
import fs from 'fs'
import tempy from 'tempy'
const extHeader = `authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = #alt_names
[alt_names]
`
const shell = cmd => execSync(cmd, { stdio: 'pipe' })
const writeCert = (extFile, outfile) => {
const cmd = [
`openssl`,
`x509`,
`-req`,
`-in ssl/my.csr`,
`-CA ssl/root-ca.pem`,
`-CAkey ssl/root-ca.key`,
`-CAserial ssl/root-ca.srl`,
`-out ssl/${outfile}`,
`-days 1825`,
`-sha256`,
`-extfile ${extFile}`,
`-passin pass:mypassphrase`
]
shell(cmd.join(' '))
}
const createCert = domains => {
const sans = domains.map((d, i) => `DNS.${i + 1} = ${d}`)
const ext = extHeader + sans.join('\n')
const extFile = tempy.file()
fs.writeFileSync(extFile, ext, 'utf-8')
writeCert(extFile, 'out.crt')
}
Dependencies:
openssl executable
yarn add tempy

Related

How can i pass the base64 string as a input certificate for Openssl?

I have a certificate which i am getting in string . I just want that string to be directly pass as -in in the openssl command.
But i don't see any method in openssl , can you help.
my code
const { exec } = require('child_process');
exec('openssl x509 -noout -issuer -in '+certificateString , (err, stdout, stderr) => {
if (err) {
console.log(err);
}else{
console.log(studout);
}
});
If i directly pass certificate file url it works, like this
openssl x509 -noout -issuer -in certificate.pem
this work
but how can i pass the certificate string directly in openssl ?
Any help?
First, do you have base64 or PEM? Those are not the same thing; although PEM includes base64, it is not only base64. If you have a file that works with openssl x509 -in file then it is PEM, NOT only base64. People seem to look at PEM, see more than 40 base64 characters, and their brains shut down and become unable to see the dashes-BEGIN line, the dashes-END line, and the line breaks, all of which are REQUIRED.
Second, certificate.pem is a filename or pathname, not a URL. A filename or pathname is not a URL, and a URL is not a filename or pathname, although some URL schemes (and particularly the only ones most people notice) include some elements in common with pathnames.
The certificate input to openssl x509 must be either a (named) file, or standard input (commonly abbreviated stdin). If you don't want to supply it as a named file, nodejs can provide data to a child's stdin, but not with the higher-level exec* methods, only the more basic spawn:
const{ spawn } = require('child_process');
const pem = `-----BEGIN CERTIFICATE-----
MIIDUzCCAjugAwIBAgIJANK2Ysp8bp+6MA0GCSqGSIb3DQEBCwUAMEAxCzAJBgNV
BAYTAlVTMQswCQYDVQQIDAJDQTETMBEGA1UEBwwKVGluc2VsdG93bjEPMA0GA1UE
CgwGRGlzbmV5MB4XDTE5MDUwOTA5MTQ0NVoXDTIwMDUwODA5MTQ0NVowQDELMAkG
A1UEBhMCVVMxCzAJBgNVBAgMAkNBMRMwEQYDVQQHDApUaW5zZWx0b3duMQ8wDQYD
VQQKDAZEaXNuZXkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCuKNJI
oBJ6acFSqMlG6e6WS44jC0RP+2y0q+02P4xc9BIuPjKV6/Lkg3bnYenAzktemvc7
EVFOUS/Ema4UIc+aDtSpjAegWnZNrzX+K76Xxzw+RnZalXB1Z++CpTdtsgSmkrmR
wJ7ZZpclAK+Yt6Ggx9ea3/d8WJ85V30ezcG7hPf5BrCSxzjSPsxG3heDPh1/X0zk
H7PD0JB+IW08yOikLmQNZeTZXaIAaSXoIPj5L9Ax7kyDEiDcSBIcQbPGMfIG6CPO
hKOM4yZKWni0mO9jwgfYNU6Bxei35/KTVwBWXHck9N7DdEtoST9THYO7ZFqqvTdk
mLfBpsPXorFT+vAVAgMBAAGjUDBOMB0GA1UdDgQWBBQyXFJDoapFe4JaZBD1xVYE
ImDj7DAfBgNVHSMEGDAWgBQyXFJDoapFe4JaZBD1xVYEImDj7DAMBgNVHRMEBTAD
AQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAwFXI13uxhGz+fem7N03r0+dnNaXZQQ9CR
owTHVVOjsfrsbFPhKdZIKMKeqpc1AksqynhbV2zY5VjINMab8ADw165gTCgy8/0S
X3QQsy2P5RNx/YuRMvs6hP7ZhZQlabLVbBnCWqAevT2qEZ7Gmi+m9A9sdK2Hsrkj
0lxGCozscme7E3ZfR/3GQVzyfZVppRLsgIth9F2y6SyLXwi+v39C+a9vdZjMS3Uy
HuRD9Sk8xydWywI8wKBlfnX4KGMBjKpSDpMeb6723eXuPC+soUBafuUoP+fWqjg4
LFgYg1TtyzfdrkkWZ9/KxS47OxkF6BAQtFGVF2nNgcpdXxToK7pP
-----END CERTIFICATE-----
`;
const p = spawn("/path/to/openssl", ["x509","-noout","-issuer"]);
// options.stdio defaults to ['pipe','pipe','pipe']
p.stdout.on('data',(data)=> {console.log(data.toString())} );
p.stderr.on('data',(data)=> {console.log("ERROR:"+data.toString())} );
p.on('close',()=> {} );
p.stdin.write(pem); p.stdin.end();
However, you don't need to run an external program to parse a certificate; there are lots of JS libraries to do it. For example, with the second one npmjs finds for me:
const { Certificate } = require('#fidm/x509');
const { ASN1 } = require('#fidm/asn1');
var iss = Certificate.fromPEM(pem).issuer.attributes;
var s = ""; for(var a of iss){ s += "/" + a.shortName + "=" + a.value; }
console.log(s);
If you actually did have base64 and not PEM, replace the third line with
const bin = Buffer.from(b64,'base64');
var iss = new Certificate(ASN1.fromDER(bin)).issuer.attributes;

Using node.js to verify a X509 certificate with CA cert

I am looking for a node.js way to verify a client certificate in X509 format with a CA certificate which was given to me (none of those are created/managed by me, my software only has to verify what is beeing sent to it).
I have found several modules for this job, however I am having issues with each of them:
X509 is able to do it using x509.verify(cert, CABundlePath, cb), however it needs to read the certificates from FS, and I am having them in memory already. This is cumbersome as it will be done with each web request which reaches my app.
It seems like PKI.js is able to do it, however their examples don't work for me but complain about missing files, so I can't even try it out.
I tried node-forge, but while I am unsure if I use it correctly (they don't have any API documentation) its throwing a forge.pki.BadCertificate error from forge.pki.verifyCertificateChain(caStore, [ cer ], cb).
When trying pem, using a simple pem.verifySigningChain(cer, [ ca ], cb) would throw some error complaining about loading a file from /var/.... Even if it would work, I would avoid using this lib as its relying on the openssl command line tool, which I would like to avoid
Now I feel pretty stupid because I failed to get this simple task done with any of the above modules. Could someone point me to a simple solution which will allow me to verify the signature/validity of a X509 certificate using a given CA certificate? :s
[edit] Basically I would need openssl verify -verbose -CAfile ca-crt.pem client1-crt.pem in Node.js but without dependencies to the openssl command line tool and without temporarily saving the certs to disk.
[edit2] Would it be possible to just use https://nodejs.org/api/crypto.html#crypto_verify_verify_object_signature_signatureformat?
I finally managed to do it using node-forge. Heres a working code example:
let pki = require('node-forge').pki;
let fs = require('fs');
let caCert;
let caStore;
try {
caCert = fs.readFileSync('path/to/ca-cert.pem').toString();
caStore = pki.createCaStore([ caCert ]);
} catch (e) {
log.error('Failed to load CA certificate (' + e + ')');
return....;
}
try {
pki.verifyCertificateChain(caStore, [ cert ]);
} catch (e) {
return handleResponse(new Error('Failed to verify certificate (' + e.message || e + ')'));
}
Both certificates shall be given in base64 encoded PEM format/js string.
verifyCertificateChain checks the certifitate validity (notBefore/notAfter) as well as verifies the given CA chain.
I am not 100% sure if this is the best approach, or if this library is doing a good job, since their source code of verifyCertificateChain is full of #TODOs, so maybe this is not ready for production?
But at least I have a somewhat working solution. Probably it would be better to create a node module which wraps the libssl c calls, but thats just a lot of effort for this small task.
You can also do like this if you want to check the using the client certificates from the http request directly :
// retrieve certificates from the request ( in der format )
clientCert = req.connection.getPeerCertificate(true).raw.toString('base64'))
Method to convert the der certificate to pem and verify against the castore.
const caCert = fs....
const ca = pki.certificateFromPem(caCert)
const caStore = pki.createCaStore([ ca ])
const verify = (clientCert, next) => {
try {
const derKey = forge.util.decode64(clientCert)
const asnObj = forge.asn1.fromDer(derKey)
const asn1Cert = pki.certificateFromAsn1(asnObj)
const pemCert = pki.certificateToPem(asn1Cert)
const client = pki.certificateFromPem(pemCert)
return pki.verifyCertificateChain(caStore, [ client ], cb)
} catch (err) {
next(new Error(err))
}
}
I did not find a better way to verify the client "der" certificate from the request.
fas3r
This works for me:
const fs = require('fs'), pki = require('node-forge').pki
var ca = pki.certificateFromPem(fs.readFileSync('ca.pem', 'ascii'))
var client = pki.certificateFromPem(fs.readFileSync('client.pem', 'ascii'))
try {
if (!ca.verify(client)) throw 'verify failed'
} catch (err) {
console.log(err)
}
try/catch was required, because .verify threw an error (instead of returning false) in my case.

How to accept self-signed certificates with LWP::UserAgent

I am attempting to set up a node.js server that uses HTTPS. I will then write a scripts in Perl to make a HTTPS request to the server and measure latency of the round trip.
Here is my node.js:
var express = require('express');
var https = require('https');
var fs = require('fs');
var key = fs.readFileSync('encrypt/rootCA.key');
var cert = fs.readFileSync('encrypt/rootCA.pem');
// This line is from the Node.js HTTPS documentation.
var options = {
key: key,
cert: cert
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world - https\n");
}).listen(8088);
Key/cert generation was done as follows:
openssl genrsa -out rootCA.key 2048
openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.pem
This is my Perl script:
#!/usr/bin/perl
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new(GET => 'https://127.0.0.1:8080');
my $res = $ua->request($req);
if ($res->is_success) {
print $res->as_string;
} else {
print "Failed: ", $res->status_line, "\n";
}
Returning the error:
Failed: 500 Can't verify SSL peers without knowing which Certificate Authorities to trust
The node.js documentation describes how to set up an HTTPS server but it is vague about generating primary cert and intermediate cert.
https://medium.com/netscape/everything-about-creating-an-https-server-using-node-js-2fc5c48a8d4e
To make LWP::UserAgent ignore server certificate use the following configuration:
my $ua = LWP::UserAgent->new;
$ua->ssl_opts(
SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_NONE,
verify_hostname => 0
);
The typical answer to such question is to disable certificate validation at all. But, this is totally insecure and essentially disables most of the protection offered by HTTPS. If validation is disabled completely a man in the middle attacker just can use an arbitrary certificate to intercept the connection and sniff and modify the data. Thus, don't do it.
The correct way to deal with such certificates is to add these certificates as trusted. This can be done with the SSL_ca_file argument:
my $ua = LWP::UserAgent->new;
$ua->ssl_opts(SSL_ca_file => 'rootCA.pem');
$ua->get('https://127.0.0.1:8080');
By explicitly trusting the self-signed server certificate as CA it will no longer throw "certificate verify failed".
But, unless your server certificate is actually issued to "127.0.0.1" you will now get "hostname verification failed" since the subject of the certificate does not match the domain of the URL. This can be fixed by setting the expected hostname:
my $ua = LWP::UserAgent->new;
$ua->ssl_opts(
SSL_ca_file => 'rootCA.pem',
SSL_verifycn_name => 'www.example.com',
);
$ua->get('https://127.0.0.1:8080');
Note that SSL_ca_file needs the self-signed certificate to have the CA flag set to true, i.e. that the certificate is a CA certificate which can be used to issue other certificates. If this is not the case with your certificate or if you just want to accept a specific certificate no matter if it is expired, revoked, does not match the hostname etc you can do the validation by using the fingerprint of the certificate.
my $ua = LWP::UserAgent->new;
$ua->ssl_opts(SSL_fingerprint => 'sha1$9AA5CFED857445259D90FE1B56B9F003C0187BFF')
$ua->get('https://127.0.0.1:8080');
The fingerprint here is the same you get with openssl x509 -noout -in rootCA.pem -fingerprint -sha1, only the algorithm added in front (sha1$...) and the colons removed.

Programmatically create certificate and certificate key in Node

Using node.js, I'd like to write code to programmatically do the equivalent of the following:
openssl genrsa -des3 -passout pass:x -out server.pass.key 2048
openssl rsa -passin pass:x -in server.pass.key -out server.key
rm server.pass.key
openssl req -new -key server.key -out server.csr
openssl x509 -req -sha256 -days 365 -in server.csr -signkey server.key -out server.crt
When complete, I need the RSA key server.key and the self-signed SSL certificate server.crt.
forge looks the most promising, but so far I haven't figured out how to get it to work. I have the following code:
var pki = forge.pki;
var keys = pki.rsa.generateKeyPair(2048);
var privKey = forge.pki.privateKeyToPem(keys.privateKey);
var pubKey = forge.pki.publicKeyToPem(keys.publicKey);
But when I write the pubKey to a file, I've noticed it starts with ...
-----BEGIN PUBLIC KEY-----
MIIB...
-----END PUBLIC KEY-----
... and isn't recognized, whereas using openssl above it starts with:
-----BEGIN CERTIFICATE-----
MIID...
-----END CERTIFICATE-----
Since the original link went dead, I've made my own code that generates a self-signed certificate using node-forge (which it looks like they already have based on the original question), so I thought I'd put it here for someone who wants it
Simply creating a public and private key pair isn't enough to work as a certificate, you have to put in attributes, node-forge is incredibly useful this way, as its pki submodule is designed for this.
First, you need to create a certificate via pki.createCertificate(), this is where you'll assign all of your certificate attributes.
You need to set the certificate public key, serial number, and the valid from date and valid to date. In this example, the public key is set to the generated public key from before, the serial number is randomly generated, and the valid from and to dates are set to one day ago and one year in the future.
You then need to assign a subject, and extensions to your certificate, this is a very basic example, so the subject is just a name you can define (or let it default to 'Testing CA - DO NOT TRUST'), and the extensions are just a single 'Basic Constraints' extension, with certificate authority set to true.
We then set the issuer to itself, as all certificates need an issuer, and we don't have one.
Then we tell the certificate to sign itself, with the private key (corresponding to its public key we've assigned) that we generated earlier, this part is important when signing certificates (or child certificates), they need to be signed with the private key of its parent (this prevents you from making fake certificates with a trusted certificate parent, as you don't have that trusted parent's private key)
Then we return the new certificate in a PEM-encoded format, you could save this to a file or convert it to a buffer and use it for a https server.
const forge = require('node-forge')
const crypto = require('crypto')
const pki = forge.pki
//using a blank options is perfectly fine here
async function genCACert(options = {}) {
options = {...{
commonName: 'Testing CA - DO NOT TRUST',
bits: 2048
}, ...options}
let keyPair = await new Promise((res, rej) => {
pki.rsa.generateKeyPair({ bits: options.bits }, (error, pair) => {
if (error) rej(error);
else res(pair)
})
})
let cert = pki.createCertificate()
cert.publicKey = keyPair.publicKey
cert.serialNumber = crypto.randomUUID().replace(/-/g, '')
cert.validity.notBefore = new Date()
cert.validity.notBefore.setDate(cert.validity.notBefore.getDate() - 1)
cert.validity.notAfter = new Date()
cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1)
cert.setSubject([{name: 'commonName', value: options.commonName}])
cert.setExtensions([{ name: 'basicConstraints', cA: true }])
cert.setIssuer(cert.subject.attributes)
cert.sign(keyPair.privateKey, forge.md.sha256.create())
return {
ca: {
key: pki.privateKeyToPem(keyPair.privateKey),
cert: pki.certificateToPem(cert)
},
fingerprint: forge.util.encode64(
pki.getPublicKeyFingerprint(keyPair.publicKey, {
type: 'SubjectPublicKeyInfo',
md: forge.md.sha256.create(),
encoding: 'binary'
})
)
}
}
//you need to put the output from genCACert() through this if you want to use it for a https server
/* e.g
let cert = await genCACert();
let buffers = caToBuffer(cert.ca);
let options = {};
options.key = buffers.key;
options.cert = buffers.cert;
let server = https.createServer(options, <listener here>);
*/
function caToBuffer(ca) {
return {
key: Buffer.from(ca.key),
cert: Buffer.from(ca.cert)
}
}
Do with this what you will.
Okay, as you probably realized, I wasn't generating a certificate. It required quite a bit more work, which you can find here.
Essentially, after a bunch of setup, I had to create, sign, and convert the certificate to Pem:
cert.sign(keys.privateKey);
var pubKey = pki.certificateToPem(cert);
Hope this helps someone else!

Alamofire ServerTrustPolicy always invalidates ServerTrust

I'm using Alamofire on Swift 2.0 and implemented the ServerTrustPolicy for my local server as you can see here:
let defaultManager: Alamofire.Manager = {
let serverTrustPolicies: [String: ServerTrustPolicy] = [
// "localhost": .PinCertificates(
// certificates: ServerTrustPolicy.certificatesInBundle(),
// validateCertificateChain: false,
// validateHost: false
// )
"localhost": .DisableEvaluation
]
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Alamofire.Manager.defaultHTTPHeaders
return Alamofire.Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
)
}()
The problem is when I do a request I always get the same error no matter if I use .PinCertificates or .DisableEvaluation:
Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made."
UserInfo={
NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x60c00004d980>,
NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?,
_kCFStreamErrorDomainKey=3,
_kCFStreamErrorCodeKey=-9802,
NSErrorPeerCertificateChainKey=<CFArray 0x6060001498a0 [0x10bb3c7b0]>{
type = immutable, count = 1, values = (
0 : <cert(0x61600006ed80) s: localhost i: localhost>
)},
NSUnderlyingError=0x6040000ad750 {
Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)"
UserInfo={
_kCFStreamPropertySSLClientCertificateState=0,
kCFStreamPropertySSLPeerTrust=<SecTrustRef: 0x60c00004d980>,
_kCFNetworkCFStreamSSLErrorOriginalValue=-9802,
_kCFStreamErrorDomainKey=3,
_kCFStreamErrorCodeKey=-9802,
kCFStreamPropertySSLPeerCertificates=<CFArray 0x6060001498a0 [0x10bb3c7b0]>{
type = immutable, count = 1, values = (
0 : <cert(0x61600006ed80) s: localhost i: localhost>
)}
}
},
NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made.,
NSErrorFailingURLKey=https://localhost:3000/auth/requestToken?auth_appId=d018ccd505db2cb1d5aacabb03fc2f3a,
NSErrorFailingURLStringKey=https://localhost:3000/auth/requestToken?auth_appId=d018ccd505db2cb1d5aacabb03fc2f3a,
NSErrorClientCertificateStateKey=0
}
I tried using
curl --cacert ./ca.pem https://localhost:3000
which throws works just fine
I use a self signed certificate which I generated like this:
Create Root CA private key
openssl genrsa -out ca.key.pem 2048
Self sign my Root CA
openssl req -x509 -new -nodes -key ca.key.pem -days 1024 -out ca.crt.pem
Create the server certificate by generating the key, then csr, then signing it with the CA
openssl genrsa -out server.key.pem 2048
openssl req -new -key server.key.pem -out server.csr.pem
openssl x509 -req -in server.csr.pem -CA ca.crt.pem -CAkey ca.key.pem -CAcreateserial -out server.crt.pem -days 500
I use nodejs's https module as my web server which I configure like this:
require('ssl-root-cas')
.inject()
.addFile('./ca.crt.pem');
var privateKey = fs.readFileSync('./server.key.pem');
var certificate = fs.readFileSync('./server.crt.pem');
var credentials = { key: privateKey, cert: certificate };
var server = https.createServer(credentials, app);
server.listen(port);
I had a look into the Alamofire source code and found out that in the delegate method:
public func URLSession(
session: NSURLSession,
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
{
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
if let sessionDidReceiveChallenge = sessionDidReceiveChallenge {
(disposition, credential) = sessionDidReceiveChallenge(session, challenge)
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let host = challenge.protectionSpace.host
if let
serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host),
serverTrust = challenge.protectionSpace.serverTrust
{
if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) {
disposition = .UseCredential
credential = NSURLCredential(forTrust: serverTrust)
} else {
disposition = .CancelAuthenticationChallenge
}
}
}
completionHandler(disposition, credential)
}
The call to serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) actually returns true. This means that the error is probably is happening somwhere in the completionHandler code, right?
Am I doing something terribly wrong at handling the certificate stuff?
PS: defaultManager is not beeing deallocated :)
First off, make sure your defaultManager isn't being deallocated. You'll always get the -999 if it is. With that said, if you use .DisableEvaluation then I would assume you have some bigger issues with your SSL configuration server-side.
Are you able to cURL your web service successfully?
I'll update my answer accordingly as you provide more info.

Resources