在命令行中输入命令并不是一个好主意,会造成安全问题。但是如果你决定去写一个应用,而这个应用需要在命令行中使用密码或者其他敏感信息。那么,你能通过以下方法禁止系统的其他用户轻易的看到这些敏感数据 呢?,类似MySQL在ps命令下隐藏密码。
假设我这里系统里两个用户,一个是root ,一个是dabu 。测试系统为centos 6.5在按照下面的步骤做:
[root@dabu.info ~]#su dabu #切换到dabu这个账号[dabu@dabu.info ~]$cd ~ #切换到dabu的home目录[dabu@dabu.info ~]$ touch pwhide.c #创建 pwhide.c文件[dabu@dabu.info ~]$ls显示:
复制代码 代码如下:pwhide.c
将下面的代码保存到 pwhide.c :
#include <stdio.h>#include <unistd.h> #include <string.h> #include <sys/types.h> int main(int argc, char *argv[]) {int i = 0;pid_t mypid = getpid(); if (argc == 1) return 1; printf("argc = %d and arguments are:\n", argc); for (i ; i < argc ; i++) printf("%d = %s\n" ,i, argv[i]); printf("Replacing first argument with x:es... Now open another terminal and run: ps p %d\n", (int)mypid); fflush(stdout); /memset(argv[1], 'x', strlen(argv[1])); /*注意,这里是本文的重点和关键点。(原文http://www.dabu.info/?p=5150)就是利用memset(void *s, int c, size_t n)函数用x来覆盖密码的每个字符*。你也可以将x替换为 a ,然后重新编译运行,再ps看看有什么不同/getc(stdin); return 0; #include <stdio.h>#include <unistd.h> #include <string.h> #include <sys/types.h> int main(int argc, char *argv[]) {int i = 0;pid_t mypid = getpid(); if (argc == 1) return 1; printf("argc = %d and arguments are:\n", argc); for (i ; i < argc ; i++) printf("%d = %s\n" ,i, argv[i]); printf("Replacing first argument with x:es... Now open another terminal and run: ps p %d\n", (int)mypid); fflush(stdout); /memset(argv[1], 'x', strlen(argv[1])); /*注意,这里是本文的重点和关键点。(原文http://www.dabu.info/?p=5150)就是利用memset(void *s, int c, size_t n)函数用x来覆盖密码的每个字符*。你也可以将x替换为 a ,然后重新编译运行,再ps看看有什么不同/getc(stdin); return 0; }然后编译 pwhide.c ,命令如下:
显示:
复制代码 代码如下:hide pwhide.c
用编译后的程序进行测试:
[dabu@dabu.info ~]$ ./hide dabu.info //dabu.info作为参数(其实就是密码) 进行测试显示:argc = 2 and arguments are:0 = ./hide1 = dabu.infoReplacing first argument with x:es... Now open another terminal and run: ps p 15585注意:ps p 15585 。你可能和我的不一样,因为pid每次运行,都会变的。你显示什么数字,后面就用什么数字。
显示出上面结果后,不再进行任何操作,也不关闭这个终端窗口(命令窗口)。然后在用root账号登录,就是相当于同时开两个终端窗口。输入下面的命令:
[root@dabu.info ~]#ps p 15585 #就是运行 ./hide dabu.info后,得到的该程序的pid显示:PID TTY STAT TIME COMMAND15585 pts/0 S+ 0:00 ./hide xxxxxxxxx //dabu.info 共有9个字符,所以这里就显示9个x由此测试的结果,我们知道了这个方法能够使MySQL如何在ps命令下隐藏命令行中的密码。以此类推,在写其他程序后,就知道如何使用这个方法来 让程序 在ps命令下隐藏命令行参数。
为了简明起见,上面的代码可能不怎么好移植到其他平台,但是它可以工作在linux上,并且如愿的表达了关键点。在其它环境,如FreeBSD,你可以使用系统调用setproctitle() 来为你做这种苦力活。关键的一点是重写argv