简体   繁体   中英

How to securely connect to MySQL database on another server?

I'm attempting to link my Discord bot with a MySQL database that is on another server. However, this example is apparently insecure:

const mysql = require('mysql');
const connection = mysql.createConnection({
  host     : 'hostname',
  port     : 'portnum',
  user     : 'db_user',
  password : 'db_user_password',
  database : 'db_name',
  charset  : 'utf8mb4'
});

How would I go about establishing a (more) secure connection?

If its a hosted database server and you have the secured endpoint URL (meaning https:// host) then just use that as the hostname host: 'hostname' and that should be enough.

If it's a private server that you own and you have the SSL certificates then you can use the following:

const fs = require('fs');
const mysql = require('mysql');

var connection = mysql.createConnection({
    host: '127.0.0.1',
    port: '3306',
    user: 'root',
    password: 'passw0rd',
    database: 'test',
    ssl: {
        ca: fs.readFileSync(__dirname + '/certs/ca.pem'),
        key: fs.readFileSync(__dirname + '/certs/client-key.pem'),
        cert: fs.readFileSync(__dirname + '/certs/client-cert.pem')
    }
});

connection.connect();

You can connect using SSL using something like this:

const fs = require('fs');
const mysql = require('mysql');
const connection = mysql.createConnection({
  host     : 'hostname',
  port     : 'portnum',
  user     : 'db_user',
  password : 'db_user_password',
  database : 'db_name',
  charset  : 'utf8mb4',
  ssl: {
      ca: fs.readFileSync(__dirname + '/certs/ca.pem'),
      key: fs.readFileSync(__dirname + '/certs/client-key.pem'),
      cert: fs.readFileSync(__dirname + '/certs/client-cert.pem')
  }
});

You must also enable SSL on the MySql server. There are some tutorials online showing how to, but you would need root access to do this.

It's not really insecure. You have a couple of options. First, are the servers on a private network behind a firewall? Or are they only able to connect with each other over public ip address? If the former is true, you are fine. I would however add firewall rules on the server so that it only allows connections from the other machine. If they are connecting on public IP addresses, you'll need to do the same and also use a non-standard port for MySQL. You can also add another NIC and bind the MySQL service to that. This way if hackers discover your server, it will appear to have all ports closed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM