Home > Software design >  CLient authentication does not work properly (with certificate)
CLient authentication does not work properly (with certificate)

Time:01-08

I want to check (dynamically via config file) a client certificate, but this does not work properly.

If I don't have a certificate I can still access the site sometimes.

this is my code

Server:

const { createServer } = require("https")

// config.ssl.client_crt = true or false

createServer({
      cert: readFileSync(config.ssl.crt_file),
      key: readFileSync(config.ssl.key_file),
      requestCert: config.ssl.client_crt,
      rejectUnauthorized: false,
      ca: readFileSync(config.ssl.ca_file),
},app).listen(config.port)

app.get("/", (req, res) => {
    authenticator.req_check(req, config.ssl.client_crt, function(ok) {
        if (! ok) {
            return res.send("nope")
        }

        return res.send("ok")
    })
});

authenticator:

module.exports = {
    req_check(req, client_crt, cb) {
        if (client_crt && req.client.authorized == false) { // <-- Pay attention!
            return cb(false)

        } else {
            return cb(true)
        }
    }
}

This works, but when I write it this way the value of req.client.authorized is sometimes ignored

if (client_crt && ! req.client.authorized) {
    return cb(false)
}

in my opinion it is the same, or am i wrong?

of course i don't want anyone to access the site without a certificate, so i need your help to make the check absolutely reliable

CodePudding user response:

If you want authorization by client certificate to be enforced, you must set rejectUnauthorized: true.

Also, certificates should be checked already when an HTTPS connection is set up, even before the first HTTPS request goes over that connection:

var server = https.createServer({
  cert: readFileSync(config.ssl.crt_file),
  key: readFileSync(config.ssl.key_file),
  requestCert: config.ssl.client_crt,
  rejectUnauthorized: true,
  ca: readFileSync(config.ssl.ca_file),
}, app)
.listen(config.port, function() {
  server.on("secureConnection", function(socket) {
    var now = new Date().getTime();
    var cert = socket.getPeerCertificate();
    if (!socket.authorized ||
        now < new Date(cert.valid_from).getTime() ||
        now > new Date(cert.valid_to).getTime())
      socket.end();
 });
});
  • Related