Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to securely connect to MySQL database

I have my MySQL database on a Raspberry Pi. I set it up like this:

sudo mariadb -u root -p

CREATE DATABASE Login;
CREATE USER RaspberryPi@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON Login.* TO RaspberryPi@'%';
SELECT Login;
CREATE TABLE Users;

I have this python code:

import mysql.connector
mydb = mysql.connector.connect(host="addr_of_pi", user="RaspberryPi", passwd="password", database="Login")
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM Users")
print(mycursor)

The problem is, that I want to give this script to a person as an .exe file but I don’t want to give him the account credentials to my database. I tried using PyProtect but the .exe script can still be read in some way. I also tried using os.gentenv(...) but then you have to create a .env file with the credentials that also can be read. So is there an other way?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try stored procedures.

Exe files can easily be decompiled. Often you can just open the file in a text editor and see the strings, so your approach is not safe.

You should instead:

  1. Create a stored procedure which does the select:
    CREATE DEFINER=root@'%' PROCEDURE SelectUsers()
        READS SQL DATA
    BEGIN
      SELECT
        *
      FROM Users;
    END
  1. Only grant permissions to execute the procedure to the user. Since the procedure is defined with DEFINER=root@'%' the RaspberryPi user will get the data on behalf of the root user, therefore there is no need to grant access to the table itself:
    GRANT EXECUTE ON PROCEDURE Login.SelectUsers TO 'RaspberryPi'@'%';
  1. Hand out your script like this:
    import mysql.connector
    mydb = mysql.connector.connect(host="addr_of_pi", user="RaspberryPi", passwd="password", database="Login")
    mycursor = mydb.cursor()
    mycursor.execute("CALL SelectUsers()")
    print(mycursor)

With this approach your RaspberryPi user will have no access to any table in your database, it can just CALL the stored procedure you granted execute permission. So, no need to "exe" your Python script.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading