Reputation: 113
I'm tryng to find a solution for upload data on a remote mysql database using a python daemon.
My base script use a simple query "INSERT INTO...." but in top of the script there are in clear the credentials to connect on database:
conn = MySQLdb.connect(host="192.168.1.123", user="root", passwd="Pa$$w0rd", db="mydb")
I do not want anyone reading the python script can access the database directly.
Upvotes: 0
Views: 1230
Reputation: 10403
Several ways
Mysql cnf files is a config file storing MySQL credentials, if this server or client executing the script has one, you can use it like:
db=_mysql.connect(host="outhouse",db="thangs",read_default_file="~/.my.cnf")
Credentials are not in your Python script anymore, but they are clear in cnf file anyway and you must have this file in the same place everywhere you want to use your script.
source: http://mysql-python.sourceforge.net/MySQLdb.html
You can parse command line arguments to get credentials from it like:
import sys
user = sys.argv[1]
password = sys.argv[2]
conn = MySQLdb.connect(host="192.168.1.123", user=user, passwd=password, db="mydb")
And so execute your script with:
python myscript "root" "pa$$w0rd"
With this method credentials can't be found in any config file, but you have to execute it with arguments, if it's a deamon it can be ok, but if you want to use it as cron (by example), you will have to write credentials in crontab, so not so safe.
Another way is to use environment variables
import os
conn = MySQLdb.connect(host="192.168.1.123", user=os.environ['MYSQL_USER'], passwd=os.environ['MYSQL_PASSWORD'], db="mydb")
But you will have to set these variables somewhere. In ~/.bash_profile
, /etc/profile
or by command line. So if somebody access to user that can execute script, he can read password.
Encoding seems to be a good way to hide password, but in fact you can not really hide from someone who can access to the right user in the right server.
Encoded string without salt is easy to decode, some encoding methods are easy to spot and can be decoded by anyone.
Using a salt will make work more harder, but if somebody can access to you code, it will be easy to locate salt phrase (no matter if salt is stored in environment var, in a file or directly in code).
Using .pyc
files can be an idea too, but first, it's not recommended and anybody can read content by creating a python script importing this pyc
file and print what stored in.
Encoding credentials still is still a good thing, but encoded string can always be decoded, if your code can, somebody with access to it can too. A simple print password
added in your code and regardless of the used method the password will be accessible.
So you have to secure your python code, but Unix users & groups too and mysql config too.
Upvotes: 2