Giving Node.js access to certificate/private key

2019-02-17 15:05发布

问题:

I am trying to use HTTPS on my Node.js app, just as it is already enabled for anything else. I have the keys and certificates already installed, but I get a Error: EACCES, permission denied when I tried to point to them on the app.

Both the key and the certificate are in subfolder of /etc/pki/tls, and I attempted pointing to them like this:

var privateKey = fs.readFileSync('/etc/pki/tls/private/serverKey.key').toString(),
    certificate = fs.readFileSync('/etc/pki/tls/certs/2_mikewarren.me.crt').toString();

var options = {
    key: privateKey,
    cert: certificate
}

Do I need to adjust the permissions of the keys and certificates (via chown)? If so, is it safe to do?

回答1:

I got my code access.

What I did

  1. created new user group called certAccess
  2. added myself to certAccess by saying sudo useradd ec2-user -G certAccess
  3. added root user (who was the only user with access to those files) to certAccess
  4. changed the owner of the private key: sudo chown ec2-user.certAccess /etc/pki/tls/private/serverKey.key

Testing...

To test, I simply print options to the console, right after using it. Indeed, I saw the contents of private key and certificate (try it yourself). I also restart httpd server, and requested static files. I saw them, protected with TLS, without fault.



回答2:

The problem is that these certificates are only readable by root (and maybe an other user).

You could use chmod to give read access to all users, but that means… that all users would have access to it. So, bad idea.

An other solution would be to either chown these files to the user running node.js, but if there is already a user with an application using these, it will break it. In that case, create a new group that owns the file, give read permissions to that group, and add the users that should access the files in that group.



标签: node.js ssl