Vadim Smirnov

Forum Replies Created

Viewing 15 posts - 1,066 through 1,080 (of 1,490 total)
  • Author
    Posts
  • in reply to: TCP/IP Hook – Traffic observing for all IP’s #6395
    Vadim Smirnov
    Keymaster

      The code below tracks incoming HTTP packets (port 80) and blocks if finds a particular string pattern in the packet. This is a simple sample for porno filter or URL blocking, you should be able easily adopt it for you needs:


      /*************************************************************************/
      /* Copyright (c) 2000-2007 NT Kernel Resources. */
      /* All Rights Reserved. */
      /* http://www.ntkernel.com */
      /* [email protected] */
      /* */
      /* Module Name: wwwcensor.cpp */
      /* */
      /* Abstract: Defines the entry point for the console application */
      /* */
      /*************************************************************************/

      #include "stdafx.h"

      USHORT ntohs( USHORT netshort )
      {
      PUCHAR pBuffer;
      USHORT nResult;

      nResult = 0;
      pBuffer = (PUCHAR )&netshort;

      nResult = ( (pBuffer[ 0 ] << 8) & 0xFF00 )
      | ( pBuffer[ 1 ] & 0x00FF );

      return( nResult );
      }

      #define htons ntohs

      int main(int argc, char* argv[])
      {
      TCP_AdapterList AdList;
      CNdisApi api;
      ETH_REQUEST Request;
      INTERMEDIATE_BUFFER PacketBuffer;
      ether_header_ptr pEthHeader = NULL;
      iphdr_ptr pIpHeader = NULL;
      tcphdr_ptr pTcpHeader = NULL;
      HANDLE hEvent[256];
      DWORD dwAdIndex = 0;
      char szTempString[1500];
      char szPattern[256];
      BOOL bDrop = FALSE;


      if (argc < 2)
      {
      printf ("Command line syntax:ntwwwcensor.exe pattern ntpattern - phrase or word to block HTTP packets with.n");
      return 0;
      }

      if(!api.IsDriverLoaded())
      {
      printf ("Driver not installed on this system of failed to load.n");
      return 0;
      }

      if ( strlen(argv[1]) > 255 )
      {
      printf ("Pattern is too,long, please use one with maximum of 255 characters.n");
      return 0;
      }

      //
      // Get pattern in upper case
      //
      ZeroMemory ( szPattern, 256 );
      strcpy ( szPattern, argv[1] );
      for ( unsigned i = 0; i < strlen (szPattern); ++i )
      {
      if (isalpha(((UCHAR)szPattern)))
      szPattern
      = (char)toupper((UCHAR)szPattern);
      }

      //
      // Get system installed network interfaces
      //
      api.GetTcpipBoundAdaptersInfo ( &AdList );

      //
      // Initialize common ADAPTER_MODE structure (all network interfaces will operate in the same mode)
      //
      ADAPTER_MODE Mode;
      Mode.dwFlags = MSTCP_FLAG_SENT_TUNNEL|MSTCP_FLAG_RECV_TUNNEL;

      //
      // Create notification events and initialize the driver to pass packets thru us
      //
      for (dwAdIndex = 0; dwAdIndex < AdList.m_nAdapterCount; ++dwAdIndex)
      {
      hEvent[dwAdIndex] = CreateEvent(NULL, TRUE, FALSE, NULL);

      if (!hEvent[dwAdIndex])
      {
      printf("Failed to create notification event for network interface n");
      return 0;
      }

      Mode.hAdapterHandle = (HANDLE)AdList.m_nAdapterHandle[dwAdIndex];

      //
      // Set MSTCP_FLAG_SENT_TUNNEL|MSTCP_FLAG_RECV_TUNNEL for the network interface
      //
      api.SetAdapterMode(&Mode);

      //
      // Set packet notification event for the network interface
      //
      api.SetPacketEvent((HANDLE)AdList.m_nAdapterHandle[dwAdIndex], hEvent[dwAdIndex]);
      }


      // Initialize common part of ETH_REQUEST
      ZeroMemory ( &Request, sizeof(ETH_REQUEST) );
      ZeroMemory ( &PacketBuffer, sizeof(INTERMEDIATE_BUFFER) );
      Request.EthPacket.Buffer = &PacketBuffer;

      //
      // Go into the endless loop (this is just a sample application)
      //
      while (TRUE)
      {
      //
      // Wait before any of the interfaces is ready to indicate the packet
      //
      dwAdIndex = WaitForMultipleObjects ( AdList.m_nAdapterCount, hEvent, FALSE, INFINITE ) - WAIT_OBJECT_0;

      //
      // Reset signalled event
      //
      ResetEvent(hEvent[dwAdIndex]);

      //
      // Complete initialization of ETH_REQUEST
      //

      Request.hAdapterHandle = (HANDLE)AdList.m_nAdapterHandle[dwAdIndex];

      //
      // Read packet from the interface until there are any
      //
      while(api.ReadPacket(&Request))
      {
      //
      // Get Ethernet header
      //
      pEthHeader = (ether_header_ptr)PacketBuffer.m_IBuffer;

      //
      // Check if Ethernet frame contains IP packet
      //
      if(ntohs(pEthHeader->h_proto) == ETH_P_IP)
      {
      //
      // Get IP header
      //
      pIpHeader = (iphdr_ptr)(pEthHeader + 1);

      //
      // Check if IP packet contains TCP packet
      //
      if (pIpHeader->ip_p == IPPROTO_TCP)
      {
      //
      // Get TCP header pointer
      //
      pTcpHeader = (tcphdr_ptr)((PUCHAR)pIpHeader + pIpHeader->ip_hl*4);

      //
      // Check if this HTTP packet (destined to remote system port 80, or received from it)
      //

      if (((pTcpHeader->th_dport == htons (80))&&(PacketBuffer.m_dwDeviceFlags == PACKET_FLAG_ON_SEND))||
      ((pTcpHeader->th_sport == htons (80))&&(PacketBuffer.m_dwDeviceFlags == PACKET_FLAG_ON_RECEIVE)))
      {
      //
      // Get data size in the packet and pointer to the data
      //

      DWORD dwDataLength = PacketBuffer.m_Length - (sizeof(ether_header) + pIpHeader->ip_hl*4 + pTcpHeader->th_off*4);
      PCHAR pData = (PCHAR)pEthHeader + (sizeof(ether_header) + pIpHeader->ip_hl*4 + pTcpHeader->th_off*4);

      // If packet contains any data - process it
      if (dwDataLength)
      {
      //
      // Copy packet payload into the temporary string, replace all 0 bytes with 0x20, convert string to upper case and place at the end
      //
      memcpy (szTempString, pData, dwDataLength);
      for (unsigned t = 0; t < dwDataLength; ++t)
      {
      if (szTempString[t] == 0)
      szTempString[t] = 0x20;

      if (isalpha((UCHAR)szTempString[t]))
      szTempString[t] = (char)toupper((UCHAR)szTempString[t]);
      }
      szTempString[dwDataLength] = 0;

      //
      // Check if this packet payload contains user supplied pattern in ASCII code
      //

      if (strstr ( szTempString, szPattern ))
      bDrop = TRUE;
      }
      }

      }
      }

      if(bDrop)
      {
      printf ("TCP %d.%d.%d.%d:%d -> %d.%d.%d.%d:%d pattern found & packet dropped n",
      pIpHeader->ip_src.S_un.S_un_b.s_b1, pIpHeader->ip_src.S_un.S_un_b.s_b2, pIpHeader->ip_src.S_un.S_un_b.s_b3, pIpHeader->ip_src.S_un.S_un_b.s_b4, ntohs(pTcpHeader->th_sport),
      pIpHeader->ip_dst.S_un.S_un_b.s_b1, pIpHeader->ip_dst.S_un.S_un_b.s_b2, pIpHeader->ip_dst.S_un.S_un_b.s_b3, pIpHeader->ip_dst.S_un.S_un_b.s_b4, ntohs (pTcpHeader->th_dport));
      bDrop = FALSE;
      }
      else
      if (PacketBuffer.m_dwDeviceFlags == PACKET_FLAG_ON_SEND)
      {
      // Place packet on the network interface
      api.SendPacketToAdapter(&Request);
      }
      else
      {
      // Indicate packet to MSTCP
      api.SendPacketToMstcp(&Request);
      }
      }

      }

      return 0;
      }

      in reply to: TCP/IP Hook – Traffic observing for all IP’s #6391
      Vadim Smirnov
      Keymaster

        Can someone say me which headers are necessary? (where can i download these?)

        http://www.ntkernel.com/w&p.php?id=7

        in reply to: installation NDIS-IM driver failed under winXP 64-bit [rus] #6383
        Vadim Smirnov
        Keymaster

          Гмм, ничего по идее не изменилось с x64. Как я использовал слегка переделанный вариант snetcfg, так и использую с учетом пеерсборки последнего под x64.

          А представленный код собирается под x64? Если нет, то вероятно это просто ограничение 32 битных процессов какое-то.

          in reply to: TCP/IP Hook – Traffic observing for all IP’s #6388
          Vadim Smirnov
          Keymaster

            Well, basically you can use WinpkFilter for parsing packets and blocking once quota exceeded.

            Alternatively you can create you own own driver for this. Here depending of the exact requirement you have several options like LSP, TDI filter, NDIS IM, NDIS hooking, WFP…

            in reply to: Modify packets #6381
            Vadim Smirnov
            Keymaster

              Using ndisapi.dll from C# is a bit trickier because you can’t pass managed memory to the driver directly. We have got some C# samples to include in the next WinpkFilter release, you can request pre-release preview of these samples by e-mailing support(at)ntkernel.com.

              in reply to: Create New Ethernet Packet problem #6370
              Vadim Smirnov
              Keymaster

                I can’t see any problem with your code and as you may have already noticed you can send ANY packet to the network even filled with all zeros.

                There is also a chance that you have a firewall installed which intercepts and blocks your packet.

                in reply to: Modify packets #6379
                Vadim Smirnov
                Keymaster

                  I do not use a network LAN Ethernet, but a network Wireless WAN, I can use winpkfilter in this case?.

                  Yes of course.

                  does winpkfilter recover the packets in the two directions (entering and outgoing)? because my work must recover the packets in the two directions.

                  Yes, if you set driver filter mode as passthru sample does then you inspect filter both incoming and outgoing packets.

                  in reply to: Modify packets #6377
                  Vadim Smirnov
                  Keymaster

                    all packets on the network layer (i.e., IP)

                    May be something like filter hook or firewall hook driver, I’m not sure if they deliver packet with or without Ethernet header . Basically I don’t see any problem with having Ethernet header for the packet like WinpkFilter does for implementing the solution you mentioned. IP packet follows Ethernet header, just make a 14 bytes offset.

                    or even transport layer (i.e., TCP)

                    You can create an LSP to operate on the winsock level or TDI level filter.

                    in reply to: TDI FILTER driver #6336
                    Vadim Smirnov
                    Keymaster

                      SerpentFly, не поможешь?

                      Почитал бы описание, покопался в отладчике, там ничего сложного то нет. Поставь breakpoint, посмотри что где приходит. Я на память не помню, надо тоже лезть смотреть, а на это время все-таки нужно. Если уж совсем никак попробую найти время отписаться.

                      in reply to: Create New Ethernet Packet problem #6368
                      Vadim Smirnov
                      Keymaster

                        I can’t say what exactly may be wrong with your code, proofreading someones code is beyond support obligations, however here is the simple sample code which is confirmed to work:


                        /*************************************************************************/
                        /* Copyright (c) 2000-2007 NT Kernel Resources. */
                        /* All Rights Reserved. */
                        /* http://www.ntkernel.com */
                        /* [email protected] */
                        /* */
                        /* Module Name: sender.cpp */
                        /* */
                        /* Abstract: Defines the entry point for the console application */
                        /* */
                        /*************************************************************************/
                        // sender.cpp : Defines the entry point for the console application.
                        //

                        #include "stdafx.h"
                        TCP_AdapterList AdList;
                        DWORD iIndex;
                        CNdisApi api;
                        ETH_REQUEST Request;
                        INTERMEDIATE_BUFFER PacketBuffer;
                        HANDLE hEvent;

                        USHORT ntohs( USHORT netshort )
                        {
                        PUCHAR pBuffer;
                        USHORT nResult;

                        nResult = 0;
                        pBuffer = (PUCHAR )&netshort;

                        nResult = ( (pBuffer[ 0 ] << 8) & 0xFF00 )
                        | ( pBuffer[ 1 ] & 0x00FF );

                        return( nResult );
                        }

                        int main(int argc, char* argv[])
                        {
                        UINT counter = 0;
                        ether_header* pEthHeader = NULL;

                        if (argc < 3)
                        {
                        printf ("Command line syntax:ntsender.exe index numntindex - network interface index.ntnum - number or packets to sendntYou can use ListAdapters to determine correct index.n");
                        return 0;
                        }

                        iIndex = atoi(argv[1]) - 1;
                        counter = atoi(argv[2]);

                        if(!api.IsDriverLoaded())
                        {
                        printf ("Driver not installed on this system of failed to load.n");
                        return 0;
                        }

                        api.GetTcpipBoundAdaptersInfo ( &AdList );

                        if ( iIndex + 1 > AdList.m_nAdapterCount )
                        {
                        printf("There is no network interface with such index on this system.n");
                        return 0;
                        }

                        // Initialize Request
                        ZeroMemory ( &Request, sizeof(ETH_REQUEST) );
                        ZeroMemory ( &PacketBuffer, sizeof(INTERMEDIATE_BUFFER) );
                        Request.EthPacket.Buffer = &PacketBuffer;
                        Request.hAdapterHandle = (HANDLE)AdList.m_nAdapterHandle[iIndex];

                        pEthHeader = (ether_header*)PacketBuffer.m_IBuffer;

                        memcpy(&pEthHeader->h_source, AdList.m_czCurrentAddress[iIndex], ETH_ALEN);
                        memset(&pEthHeader->h_dest, 0xFF, ETH_ALEN);
                        pEthHeader->h_proto = ETH_P_IP;
                        Request.EthPacket.Buffer->m_Length = MAX_ETHER_FRAME;

                        while (counter--)
                        api.SendPacketToAdapter(&Request);

                        return 0;
                        }

                        This simple application sends over network the specified amount of Ethernet broadcast frames filled with zeros. It’s work can be easily seen with any network sniffer.

                        in reply to: Create New Ethernet Packet problem #6366
                        Vadim Smirnov
                        Keymaster

                          But its not reaching the other side.

                          Can you see the packet going out with the sniffer installed on the local system?

                          in reply to: OpenFilterDriver fails.. help! #6363
                          Vadim Smirnov
                          Keymaster

                            Hmm, it is kind of difficulty to point the problem, but I suspect it is somehow related to setting up the project. I would suggest to start from the existing project (an example from passthru) and try to compile it in your environment.

                            Also, is the driver that is downloadable from the website time-limited in any way or is it an unlimited demo for private use? (this is what I understood… but I read a few posts here mentioning a 100-packet limit.. please clarify)

                            This limitation was removed a couple of years ago.

                            in reply to: TDI FILTER driver #6331
                            Vadim Smirnov
                            Keymaster

                              Что-то не совсем понимаю что за датаграммы такие..

                              UDP протокол

                              in reply to: TDI FILTER driver #6327
                              Vadim Smirnov
                              Keymaster

                                Your debugger is not using the correct symbols

                                Символы в отладчик загрузить не судьба? Только не спрашивай как, читай документацию.

                                in reply to: TDI FILTER driver #6325
                                Vadim Smirnov
                                Keymaster

                                  М-да, просто нет слов… У тебя:

                                  typedef NTSTATUS (*OLDCLIENTEVENTRECEIVE)(IN PVOID,
                                  IN CONNECTION_CONTEXT,
                                  IN ULONG,
                                  IN ULONG,
                                  IN ULONG,
                                  OUT ULONG,
                                  IN PVOID,
                                  OUT PIRP);

                                  Должно быть:


                                  typedef NTSTATUS (*OLDCLIENTEVENTRECEIVE)(IN PVOID,
                                  IN CONNECTION_CONTEXT,
                                  IN ULONG,
                                  IN ULONG,
                                  IN ULONG,
                                  OUT ULONG*,
                                  IN PVOID,
                                  OUT PIRP*);

                                  ULONG * – это тип указатель на ULONG, PIRP * – указатель на PIRP. ВСЕ ЧТО ДО ИМЕНИ ПАРАМЕТРА – ЭТО ТИП ПАРАМЕТРА.

                                Viewing 15 posts - 1,066 through 1,080 (of 1,490 total)