技术控

    今日:0| 主题:63445
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Encrypt your –defaults-file

[复制链接]
活在當下 发表于 2016-10-13 00:30:15
141 4

Encrypt your –defaults-file

Encrypt your –defaults-file
      Encrypt your credentials using GPG      This blog post will look how to use encryption to secure your database credentials.
   In the recent blog post Use MySQL Shell Securely from Bash , there are some good examples of how you might avoid using a ~/.my.cnf – but you still need to put that password down on disk in the script. MySQL 5.6.6 and later introduced the   –login-path option, which is a handy way to store per-connection entries and keep the credentials in an encrypted format. This is a great improvement, but as shown in Get MySQL Passwords in Plain Text from .mylogin.cnf , it is pretty easy to get that information back out.
   Let’s fix this with gpg-agent , mkfifo and a few servings of Bash foo…
   If you want to keep prying eyes away from your super secret database credentials, then you really need to encrypt it. Nowadays most people are familiar with GPG ( GNU Privacy Guard ), but for those of you that aren’t it is a free implementation of the OpenPGP standard that allows you to encrypt and sign your data and communication.
  First steps…

  Before we can go on to use GPG to encrypt our credentials, we need to get it working. GnuPG comes with almost every *nix operating system, but for this post we’ll be using Ubuntu 16.04 LTS and we’ll presume that it isn’t yet installed.
  1. $ sudoapt-get installgnupggnupg-agentpinentry-curses
复制代码
Once the packages are installed, there is a little configuration required to make things simpler. We’ll go with some minimal settings just to get you going. First of all, we’ll create our main key:
  1. $ gpg --gen-key
  2. gpg (GnuPG) 1.4.12; Copyright (C) 2012 FreeSoftwareFoundation, Inc.
  3. This is freesoftware: youarefreeto changeand redistributeit.
  4. Thereis NOWARRANTY, to theextentpermittedbylaw.
  5. Pleaseselectwhat kindofkeyyouwant:
  6. (1) RSAand RSA (default)
  7. (2) DSAand Elgamal
  8. (3) DSA (signonly)
  9. (4) RSA (signonly)
  10. Yourselection? 1
  11. RSAkeysmaybebetween 1024 and 4096 bitslong.
  12. What keysizedo youwant? (4096)
  13. Requestedkeysizeis 4096 bits
  14. Pleasespecifyhowlong thekeyshouldbevalid.
  15. 0 = keydoesnot expire
  16. <n> = keyexpiresin n days
  17. <n>w = keyexpiresin n weeks
  18. <n>m = keyexpiresin n months
  19. <n>y = keyexpiresin n years
  20. Keyis validfor? (5y)
  21. Keyexpiresat Tue 05 Oct 2021 23:59:00 BST
  22. Is this correct? (y/N) y
  23. Youneed a userID to identifyyourkey; thesoftwareconstructstheuserID
  24. fromtheRealName, Commentand EmailAddressin this form:
  25. "Heinrich Heine (Der Dichter) <[email protected]>"
  26. Realname: CeriWilliams
  27. Emailaddress: [email protected]
  28. Comment: Encryptedcredentialsfor MySQL
  29. Youselectedthis USER-ID:
  30. "Ceri Williams (Encrypted credentials for MySQL) <[email protected]>"
  31. Change (N)ame, (C)omment, (E)mailor (O)kay/(Q)uit? O
  32. Youneed a Passphraseto protectyoursecretkey.
复制代码
After typing a password and gaining sufficient entropy you will have your first key! You can show your private keys as follows:
  1. $ gpg --list-secret-keys
  2. /home/ceri/.gnupg/secring.gpg
  3. -----------------------------
  4. sec 4096R/C38C02B0 2016-10-06 [expires: 2021-10-05]
  5. uidCeriWilliams (Encryptedcredentialsfor MySQL) <[email protected]>
复制代码
We’ll now create our “gpg.conf” in which to keep a few settings. This sets the key that is used by default when encrypting, enables the gpg-agent and removes the copyright message.
  1. $ cat <<EOF > ~/.gnupg/gpg.conf
  2. default-keyC38C02B0
  3. use-agent
  4. no-greeting
  5. EOF
复制代码
Now we’ll add a few settings for “gpg-agent” and allow the key to be saved for one day to reduce the number of times you need to enter a password. Also, as this post concentrates on command line programs, we’ve enabled the ncurses pinentry to specify the password when requested.
  1. $ cat <<EOF > ~/.gnupg/gpg-agent.conf
  2. pinentry-program /usr/bin/pinentry-curses
  3. default-cache-ttl 86400
  4. max-cache-ttl 86400
  5. EOF
复制代码
  You can find more information about setting up and using GPG in the GNU Privacy Handbook .
  Encrypt your credentials

  If all has gone well so far, you should be able to encrypt your first message. Here is a simple example to create armored (ASCII) output for a recipient with key “C38C02B0”:
  1. $ echo hello | gpg -e --armor -r C38C02B0
  2. -----BEGINPGPMESSAGE-----
  3. Version: GnuPGv1
  4. hQIMA/T3pqGixN5nAQ/+IxmmgoHNVY2IXp7OAQUZZtCw0ayZu/rFotsJBiQcNG4W
  5. J9JZmG78fgPfyF2FD4oVsXDBW7yDzfDSxCcX7LL9z4p33bzUAYOwofRP9+8qJGq/
  6. qob1SclNN4fdFc/PtI7XKYBFYcHlfFeTIH44w9GEGdZlyfDfej+qGTJX+UHrKTo3
  7. DaE2qpb7GvohEnDPX5WM0Pts3cATi3PcH4C9OZ5dgYizmlPB58R2DZl1ioERy2jE
  8. WSIhkZ8ZPW9ezWYDCtFbgFSpgynzYeFRVv1rel8cxZCSYgHOHrUgQM6WdtVFmEjL
  9. ONaRiEA9IcXZXDXaeFezKr2F8PJyaVfmheZDdRTdw54e4R6kPunDeWtD2aCJE4EF
  10. ztyWLgQZ0wNE8UY0PepSu5p0FAENk08xd9xNMCSiCuwmBAorafaO9Q8EnJjHS/w5
  11. aKLJzNzad+8zKq3zgBxHGj1liHmx873Epz5izsH/lK9Jwy6H5qGVB71XuNuRMzNr
  12. ghgHFWNX7Wy8wnBnV6MrenASgtCUY6cGdT7YpPe6pLr8Qj/3QRLdzHDlMi9gGxoS
  13. 26emhTi8sIUzQRtQxFKKXyZ43sldtRewHE/k4/ZRXz5N6ST2cSFAcsMyjScS4p2a
  14. JvPvHt4xhn8uRhgiauqd7IqCCSWFrAR4J50AdARmVeucWsbRzIJIEnKW4G/XikvS
  15. QQFOvcdalGWKMpH+mRBkHRjbOgGpB0GeRbuKzhdDvVT+EhhIOG8DphumgI0yDyTo
  16. Ote5sANgTRpr0KunJPgz5pER
  17. =HsSu
  18. -----END PGPMESSAGE-----
复制代码
Now that we have GPG working, we can secure our credentials and encrypt them to use later on. One of the default files MySQL reads is “~/.my.cnf”, which is where you can store your user credentials for easy command line access.
  1. $ cat <<EOF | gpg --encrypt --armor -r C38C02B0 -o ~/.my.cnf.asc
  2. [client]
  3. user = ceri
  4. password = mysecretpassword
  5. [mysql]
  6. skip-auto-rehash
  7. prompt = "smysql d> "
  8. EOF
复制代码
There you go, everything is nice and secure! But wait, how can anything use this?
  Bash foo brings MySQL data to you

  Most MySQL and Percona tools will accept the “–defaults-file” argument, which tells the program where to look to find what configuration to run. This will allow us to use our encrypted config.
  The following script carries out the following actions:
  
       
  • Creates a temporary file on disk and then removes it   
  • Creates a FIFO (a socket-like communication channel that requires both ends to be connected)   
  • Decrypts the config to the FIFO in the background   
  • Launches the “mysql” client and reads from the FIFO  
  1. #!/bin/bash
  2. set -e
  3. declare -raARGS=( "${@}" )
  4. declare -riARGV=${#ARGS[@]}
  5. declare -r SEC_MYCNF=$(test -f ${1:-undef} && echo $_ || echo '.my.cnf.asc')
  6. declare -r SEC_FIFO=$(mktemp)
  7. declare -a PASSTHRU=( "${ARGS[@]}" )
  8. test ${ARGV} -gt 0 &&
  9. test -f "${ARGS[0]}" &&
  10. PASSTHRU=( "${ARGS[@]:1}" )
  11. set -u
  12. function cleanup {
  13.   test -e ${SEC_FIFO} && rm -f $_
  14.   return $?
  15. }
  16. function decrypt {
  17.   set +e
  18.   $(whichgpg) --batch --yes -o ${SEC_FIFO} -d ${SEC_MYCNF} >debug.log 2>&1
  19.   test $? -eq 0 || $(whichgpg) --yes -o ${SEC_FIFO} -d ${SEC_MYCNF} >debug.log 2>&1
  20.   set -e
  21. }
  22. function exec_cmd {
  23.   local -r cmd=${1}
  24.   set +u
  25.   ${cmd} --defaults-pold=${SEC_FIFO} "${PASSTHRU[@]}"
  26.   set -u
  27. }
  28. trap cleanup EXIT
  29. test -e ${SEC_MYCNF} || exit 1
  30. cleanup && mkfifo ${SEC_FIFO} && decrypt &
  31. exec_cmd /usr/bin/mysql
复制代码
You can use this script as you would normally with the “mysql” client, and pass your desired arguments. You can also optionally pass a specific encrypted config as the first argument:
  1. $ ./smysql.sh .my.test.asc
  2. Welcometo theMySQLmonitor. Commandsend with ; or g.
  3. YourMySQLconnectionid is 56
  4. Serverversion: 5.7.14-8 PerconaServer (GPL), Release '8', Revision '1f84ccd'
  5. Copyright (c) 2009-2016 PerconaLLCand/or itsaffiliates
  6. Copyright (c) 2000, 2016, Oracleand/or itsaffiliates. Allrightsreserved.
  7. Oracleis a registeredtrademarkofOracleCorporationand/or its
  8. affiliates. Othernamesmaybetrademarksoftheirrespective
  9. owners.
  10. Type 'help;' or 'h' for help. Type 'c' to clear thecurrentinputstatement.
  11. smysql (none)>
复制代码
There we go, MySQL access via an encrypted “–defaults-file” – and as long as your key is unlocked in the agent you do not need to enter the password.
   But wait . . . what about all of the other tools that you might want to use? Well, with a slight tweak you can make the script a little fancier and get other tools to use the config, too (tools such as mysqladmin , mysqldump , pt-show-grants ,pt-table-checksum, etc.). The key part of the next script is the specification of accepted commands (“ALIASES”) and the use of symbolic links to alias the script:
  1. #!
  2. /bin/bash set -e declare -raARGS=( "${@}" ) declare -riARGV=${#ARGS[@]} declare -rAALIASES=( [smysql]=mysql [smysqldump]=mysqldump [smysqladmin]=mysqladmin [spt-show-grants]=pt-show-grants [spt-table-checksum]=pt-table-checksum [spt-table-sync]=pt-table-sync [spt-query-digest]=pt-query-digest ) declare -r PROGNAME=$(basename ${0}) declare -r SEC_MYCNF=$(test -f ${1:-undef} && echo $_ || echo '.my.gpg') declare -r SEC_FIFO=$(mktemp) declare -a PASSTHRU=( "${ARGS[@]}" ) test ${ARGV} -gt 0 && test -f "${ARGS[0]}" && PASSTHRU=( "${ARGS[@]:1}" ) set -u function cleanup { test -e ${SEC_FIFO} && rm -f $_ return $? } function decrypt { set +e $(whichgpg) --batch --yes -o ${SEC_FIFO} -d ${SEC_MYCNF} >debug.log 2>&1 test $? -eq 0 || $(whichgpg) --yes -o ${SEC_FIFO} -d ${SEC_MYCNF} >debug.log 2>&1 set -e } function check_cmd { local k localcmd=${1} for k in "${!ALIASES[@]}"; do test "${cmd}" = ${k} && test -x "$(which ${ALIASES[${k}]})" && echo $_ && return 0 done return 1 } function exec_cmd { local -r cmd=${1} set +u ${cmd} --defaults-file=${SEC_FIFO} "${PASSTHRU[@]}" set -u } function usage { localrealfn=$(realpath ${0}) cat < USAGE: $(basename ${0}) enc_file.gpg [--arg=val] use a GPG-encryptedmy.cnf (default: ${SEC_MYCNF}) currentlysupports: ${ALIASES[@]} create a symlinkto matchthealias (realappprefixedwith 's') e.g. sudo ln -s ${realfn} /usr/local/bin/smysql sudo ln -s ${realfn} /usr/local/bin/spt-show-grantsEOS } trap cleanup EXIT test -e ${SEC_MYCNF} || { usage; exit 1; } cmd=$(check_cmd ${PROGNAME}) test $? -eq 0 || { echo ${ALIASES[${PROGNAME}]} is not available; exit 3; } cleanup && mkfifo ${SEC_FIFO} && decrypt & exec_cmd ${cmd}
复制代码
Now we can set up some symlinks so that the script can be called in a way that the correct application is chosen:
  1. $ gpg --gen-key
  2. gpg (GnuPG) 1.4.12; Copyright (C) 2012 FreeSoftwareFoundation, Inc.
  3. This is freesoftware: youarefreeto changeand redistributeit.
  4. Thereis NOWARRANTY, to theextentpermittedbylaw.
  5. Pleaseselectwhat kindofkeyyouwant:
  6. (1) RSAand RSA (default)
  7. (2) DSAand Elgamal
  8. (3) DSA (signonly)
  9. (4) RSA (signonly)
  10. Yourselection? 1
  11. RSAkeysmaybebetween 1024 and 4096 bitslong.
  12. What keysizedo youwant? (4096)
  13. Requestedkeysizeis 4096 bits
  14. Pleasespecifyhowlong thekeyshouldbevalid.
  15. 0 = keydoesnot expire
  16. <n> = keyexpiresin n days
  17. <n>w = keyexpiresin n weeks
  18. <n>m = keyexpiresin n months
  19. <n>y = keyexpiresin n years
  20. Keyis validfor? (5y)
  21. Keyexpiresat Tue 05 Oct 2021 23:59:00 BST
  22. Is this correct? (y/N) y
  23. Youneed a userID to identifyyourkey; thesoftwareconstructstheuserID
  24. fromtheRealName, Commentand EmailAddressin this form:
  25. "Heinrich Heine (Der Dichter) <[email protected]>"
  26. Realname: CeriWilliams
  27. Emailaddress: [email protected]
  28. Comment: Encryptedcredentialsfor MySQL
  29. Youselectedthis USER-ID:
  30. "Ceri Williams (Encrypted credentials for MySQL) <[email protected]>"
  31. Change (N)ame, (C)omment, (E)mailor (O)kay/(Q)uit? O
  32. Youneed a Passphraseto protectyoursecretkey.
  33. 0
复制代码
Examples

  With some symlinks now in place we can try out some of the tools that we have enabled:
  1. $ gpg --gen-key
  2. gpg (GnuPG) 1.4.12; Copyright (C) 2012 FreeSoftwareFoundation, Inc.
  3. This is freesoftware: youarefreeto changeand redistributeit.
  4. Thereis NOWARRANTY, to theextentpermittedbylaw.
  5. Pleaseselectwhat kindofkeyyouwant:
  6. (1) RSAand RSA (default)
  7. (2) DSAand Elgamal
  8. (3) DSA (signonly)
  9. (4) RSA (signonly)
  10. Yourselection? 1
  11. RSAkeysmaybebetween 1024 and 4096 bitslong.
  12. What keysizedo youwant? (4096)
  13. Requestedkeysizeis 4096 bits
  14. Pleasespecifyhowlong thekeyshouldbevalid.
  15. 0 = keydoesnot expire
  16. <n> = keyexpiresin n days
  17. <n>w = keyexpiresin n weeks
  18. <n>m = keyexpiresin n months
  19. <n>y = keyexpiresin n years
  20. Keyis validfor? (5y)
  21. Keyexpiresat Tue 05 Oct 2021 23:59:00 BST
  22. Is this correct? (y/N) y
  23. Youneed a userID to identifyyourkey; thesoftwareconstructstheuserID
  24. fromtheRealName, Commentand EmailAddressin this form:
  25. "Heinrich Heine (Der Dichter) <[email protected]>"
  26. Realname: CeriWilliams
  27. Emailaddress: [email protected]
  28. Comment: Encryptedcredentialsfor MySQL
  29. Youselectedthis USER-ID:
  30. "Ceri Williams (Encrypted credentials for MySQL) <[email protected]>"
  31. Change (N)ame, (C)omment, (E)mailor (O)kay/(Q)uit? O
  32. Youneed a Passphraseto protectyoursecretkey.
  33. 1
复制代码
Enjoy some added security in your database environment, on your laptop and even on your Raspberry Pi!
程金平 发表于 2016-10-15 04:38:59
明明回贴贴
回复 支持 反对

使用道具 举报

贾果 发表于 2016-10-24 04:25:19
小手一抖,经验到手,为了升级,到处游走,纯属路过,不要介意,高抬贵手,立马飘走.
回复 支持 反对

使用道具 举报

LGSUOYI 发表于 2016-11-14 21:01:57
经验之谈,谢谢活在當下了,请继续努力
回复 支持 反对

使用道具 举报

Edmund3717 发表于 2016-11-14 21:26:09
滴答滴答,我路过的!
回复 支持 反对

使用道具 举报

我要投稿

回页顶回复上一篇下一篇回列表
手机版/c.CoLaBug.com ( 粤ICP备05003221号 | 粤公网安备 44010402000842号 )

© 2001-2017 Comsenz Inc.

返回顶部 返回列表