技术控

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

[其他] Encrypt your –defaults-file

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

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x

Encrypt your –defaults-file-1 (password,database,examples,familiar,secret)
      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.
  [code]$ sudoapt-get installgnupggnupg-agentpinentry-curses
[/code]  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:
  [code]$ gpg --gen-key
gpg (GnuPG) 1.4.12; Copyright (C) 2012 FreeSoftwareFoundation, Inc.
This is freesoftware: youarefreeto changeand redistributeit.
Thereis NOWARRANTY, to theextentpermittedbylaw.

Pleaseselectwhat kindofkeyyouwant:
(1) RSAand RSA (default)
(2) DSAand Elgamal
(3) DSA (signonly)
(4) RSA (signonly)
Yourselection? 1
RSAkeysmaybebetween 1024 and 4096 bitslong.
What keysizedo youwant? (4096)
Requestedkeysizeis 4096 bits
Pleasespecifyhowlong thekeyshouldbevalid.
0 = keydoesnot expire
= keyexpiresin n days
w = keyexpiresin n weeks
m = keyexpiresin n months
y = keyexpiresin n years
Keyis validfor? (5y)
Keyexpiresat Tue 05 Oct 2021 23:59:00 BST
Is this correct? (y/N) y

Youneed a userID to identifyyourkey; thesoftwareconstructstheuserID
fromtheRealName, Commentand EmailAddressin this form:
"Heinrich Heine (Der Dichter) "

Realname: CeriWilliams
Emailaddress: [email protected]
Comment: Encryptedcredentialsfor MySQL
Youselectedthis USER-ID:
"Ceri Williams (Encrypted credentials for MySQL) "

Change (N)ame, (C)omment, (E)mailor (O)kay/(Q)uit? O
Youneed a Passphraseto protectyoursecretkey.
[/code]  After typing a password and gaining sufficient entropy you will have your first key! You can show your private keys as follows:
  [code]$ gpg --list-secret-keys
/home/ceri/.gnupg/secring.gpg
-----------------------------
sec 4096R/C38C02B0 2016-10-06 [expires: 2021-10-05]
uidCeriWilliams (Encryptedcredentialsfor MySQL)
[/code]  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.
  [code]$ cat < ~/.gnupg/gpg.conf
default-keyC38C02B0
use-agent
no-greeting
EOF
[/code]  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.
  [code]$ cat < ~/.gnupg/gpg-agent.conf
pinentry-program /usr/bin/pinentry-curses
default-cache-ttl 86400
max-cache-ttl 86400
EOF
[/code]   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”:
  [code]$ echo hello | gpg -e --armor -r C38C02B0
-----BEGINPGPMESSAGE-----
Version: GnuPGv1

hQIMA/T3pqGixN5nAQ/+IxmmgoHNVY2IXp7OAQUZZtCw0ayZu/rFotsJBiQcNG4W
J9JZmG78fgPfyF2FD4oVsXDBW7yDzfDSxCcX7LL9z4p33bzUAYOwofRP9+8qJGq/
qob1SclNN4fdFc/PtI7XKYBFYcHlfFeTIH44w9GEGdZlyfDfej+qGTJX+UHrKTo3
DaE2qpb7GvohEnDPX5WM0Pts3cATi3PcH4C9OZ5dgYizmlPB58R2DZl1ioERy2jE
WSIhkZ8ZPW9ezWYDCtFbgFSpgynzYeFRVv1rel8cxZCSYgHOHrUgQM6WdtVFmEjL
ONaRiEA9IcXZXDXaeFezKr2F8PJyaVfmheZDdRTdw54e4R6kPunDeWtD2aCJE4EF
ztyWLgQZ0wNE8UY0PepSu5p0FAENk08xd9xNMCSiCuwmBAorafaO9Q8EnJjHS/w5
aKLJzNzad+8zKq3zgBxHGj1liHmx873Epz5izsH/lK9Jwy6H5qGVB71XuNuRMzNr
ghgHFWNX7Wy8wnBnV6MrenASgtCUY6cGdT7YpPe6pLr8Qj/3QRLdzHDlMi9gGxoS
26emhTi8sIUzQRtQxFKKXyZ43sldtRewHE/k4/ZRXz5N6ST2cSFAcsMyjScS4p2a
JvPvHt4xhn8uRhgiauqd7IqCCSWFrAR4J50AdARmVeucWsbRzIJIEnKW4G/XikvS
QQFOvcdalGWKMpH+mRBkHRjbOgGpB0GeRbuKzhdDvVT+EhhIOG8DphumgI0yDyTo
Ote5sANgTRpr0KunJPgz5pER
=HsSu
-----END PGPMESSAGE-----
[/code]  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.
  [code]$ cat < [client]
user = ceri
password = mysecretpassword

[mysql]
skip-auto-rehash
prompt = "smysql d> "
EOF
[/code]  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  
  [code]#!/bin/bash

set -e

declare -raARGS=( "${@}" )
declare -riARGV=${#ARGS[@]}
declare -r SEC_MYCNF=$(test -f ${1:-undef} && echo $_ || echo '.my.cnf.asc')
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 exec_cmd {
  local -r cmd=${1}
  set +u
  ${cmd} --defaults-pold=${SEC_FIFO} "${PASSTHRU[@]}"
  set -u
}

trap cleanup EXIT

test -e ${SEC_MYCNF} || exit 1

cleanup && mkfifo ${SEC_FIFO} && decrypt &

exec_cmd /usr/bin/mysql
[/code]  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:
  [code]$ ./smysql.sh .my.test.asc
Welcometo theMySQLmonitor. Commandsend with ; or g.
YourMySQLconnectionid is 56
Serverversion: 5.7.14-8 PerconaServer (GPL), Release '8', Revision '1f84ccd'

Copyright (c) 2009-2016 PerconaLLCand/or itsaffiliates
Copyright (c) 2000, 2016, Oracleand/or itsaffiliates. Allrightsreserved.

Oracleis a registeredtrademarkofOracleCorporationand/or its
affiliates. Othernamesmaybetrademarksoftheirrespective
owners.

Type 'help;' or 'h' for help. Type 'c' to clear thecurrentinputstatement.

smysql (none)>
[/code]  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:
  [code]#!
/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}
[/code]  Now we can set up some symlinks so that the script can be called in a way that the correct application is chosen:
  [code]$ gpg --gen-key
gpg (GnuPG) 1.4.12; Copyright (C) 2012 FreeSoftwareFoundation, Inc.
This is freesoftware: youarefreeto changeand redistributeit.
Thereis NOWARRANTY, to theextentpermittedbylaw.

Pleaseselectwhat kindofkeyyouwant:
(1) RSAand RSA (default)
(2) DSAand Elgamal
(3) DSA (signonly)
(4) RSA (signonly)
Yourselection? 1
RSAkeysmaybebetween 1024 and 4096 bitslong.
What keysizedo youwant? (4096)
Requestedkeysizeis 4096 bits
Pleasespecifyhowlong thekeyshouldbevalid.
0 = keydoesnot expire
= keyexpiresin n days
w = keyexpiresin n weeks
m = keyexpiresin n months
y = keyexpiresin n years
Keyis validfor? (5y)
Keyexpiresat Tue 05 Oct 2021 23:59:00 BST
Is this correct? (y/N) y

Youneed a userID to identifyyourkey; thesoftwareconstructstheuserID
fromtheRealName, Commentand EmailAddressin this form:
"Heinrich Heine (Der Dichter) "

Realname: CeriWilliams
Emailaddress: [email protected]
Comment: Encryptedcredentialsfor MySQL
Youselectedthis USER-ID:
"Ceri Williams (Encrypted credentials for MySQL) "

Change (N)ame, (C)omment, (E)mailor (O)kay/(Q)uit? O
Youneed a Passphraseto protectyoursecretkey.
0[/code]  Examples

  With some symlinks now in place we can try out some of the tools that we have enabled:
  [code]$ gpg --gen-key
gpg (GnuPG) 1.4.12; Copyright (C) 2012 FreeSoftwareFoundation, Inc.
This is freesoftware: youarefreeto changeand redistributeit.
Thereis NOWARRANTY, to theextentpermittedbylaw.

Pleaseselectwhat kindofkeyyouwant:
(1) RSAand RSA (default)
(2) DSAand Elgamal
(3) DSA (signonly)
(4) RSA (signonly)
Yourselection? 1
RSAkeysmaybebetween 1024 and 4096 bitslong.
What keysizedo youwant? (4096)
Requestedkeysizeis 4096 bits
Pleasespecifyhowlong thekeyshouldbevalid.
0 = keydoesnot expire
= keyexpiresin n days
w = keyexpiresin n weeks
m = keyexpiresin n months
y = keyexpiresin n years
Keyis validfor? (5y)
Keyexpiresat Tue 05 Oct 2021 23:59:00 BST
Is this correct? (y/N) y

Youneed a userID to identifyyourkey; thesoftwareconstructstheuserID
fromtheRealName, Commentand EmailAddressin this form:
"Heinrich Heine (Der Dichter) "

Realname: CeriWilliams
Emailaddress: [email protected]
Comment: Encryptedcredentialsfor MySQL
Youselectedthis USER-ID:
"Ceri Williams (Encrypted credentials for MySQL) "

Change (N)ame, (C)omment, (E)mailor (O)kay/(Q)uit? O
Youneed a Passphraseto protectyoursecretkey.
1[/code]  Enjoy some added security in your database environment, on your laptop and even on your Raspberry Pi!
友荐云推荐




上一篇:BAOCMS外卖O2O系统功能升级,多样化配送新玩法来啦!
下一篇:Faster PostgreSQL Counting
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

程金平 发表于 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
滴答滴答,我路过的!
回复 支持 反对

使用道具 举报

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表