示例#1
0
        public static MIB_TCPROW_OWNER_PID[] GetTable()
        {
            MIB_TCPROW_OWNER_PID[] tTable;
            int    AF_INET   = 2;
            int    buffSize  = 0;
            uint   ret       = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
            IntPtr buffTable = Marshal.AllocHGlobal(buffSize);

            try
            {
                ret = GetExtendedTcpTable(buffTable, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
                if (ret != 0)
                {
                    return(null);
                }
                MIB_TCPTABLE_OWNER_PID tab = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(buffTable, typeof(MIB_TCPTABLE_OWNER_PID));
                IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.dwNumEntries));
                tTable = new MIB_TCPROW_OWNER_PID[tab.dwNumEntries];
                for (int i = 0; i < tab.dwNumEntries; i++)
                {
                    MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID));
                    tTable[i] = tcpRow;
                    rowPtr    = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow));
                }
            }
            finally
            {
                Marshal.FreeHGlobal(buffTable);
            }
            return(tTable);
        }
示例#2
0
文件: Net.cs 项目: yycmmc/Swiddler
 private static IEnumerable <MIB_TCPROW_OWNER_PID> EnumTcpConnectionsV4()
 {
     int    dwSize = sizeof(int) + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID)) * 100;
     IntPtr hTcpTable;
     {
         hTcpTable = Marshal.AllocHGlobal(dwSize);
         int ret = GetExtendedTcpTable(hTcpTable, ref dwSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
         if (ret != NO_ERROR)
         {
             // retry for new dwSize.
             Marshal.FreeHGlobal(hTcpTable);
             hTcpTable = Marshal.AllocHGlobal(dwSize);
             ret       = GetExtendedTcpTable(hTcpTable, ref dwSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
             if (ret != NO_ERROR)
             {
                 Marshal.FreeHGlobal(hTcpTable);
                 throw new Exception("GetExtendedTcpTable return: " + ret);
             }
         }
     }
     {
         MIB_TCPROW_OWNER_PID item = new MIB_TCPROW_OWNER_PID();
         int    dwNumEntries       = Marshal.ReadInt32(hTcpTable);
         IntPtr pItem = new IntPtr(hTcpTable.ToInt64() + sizeof(int));
         for (int i = 0; i < dwNumEntries; ++i)
         {
             Marshal.PtrToStructure(pItem, item);
             pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID)));
             yield return(item);
         }
         Marshal.FreeHGlobal(hTcpTable);
     }
 }
示例#3
0
        public static MIB_TCPROW_OWNER_PID[] GetTable()
        {
            MIB_TCPROW_OWNER_PID[] tTable;
            int AF_INET = 2;
            int buffSize = 0;
            uint ret = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
            IntPtr buffTable = Marshal.AllocHGlobal(buffSize);
            try
            {
                ret = GetExtendedTcpTable(buffTable, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
                if (ret != 0)
                    return null;
                MIB_TCPTABLE_OWNER_PID tab = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(buffTable, typeof(MIB_TCPTABLE_OWNER_PID));
                IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.dwNumEntries));
                tTable = new MIB_TCPROW_OWNER_PID[tab.dwNumEntries];
                for (int i = 0; i < tab.dwNumEntries; i++)
                {
                    MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID));
                    tTable[i] = tcpRow;
                    rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow));
                }

            }
            finally
            {
                Marshal.FreeHGlobal(buffTable);
            }
            return tTable;
        }
        static MIB_TCPROW_OWNER_PID[] GetAllTcpConnections()
        {
            MIB_TCPROW_OWNER_PID[] rows;
            int AF_INET = 2;    // IP_v4
            uint buff_size = 0;

            uint ret = SafeNativeMethods.GetExtendedTcpTable(IntPtr.Zero, ref buff_size, true, AF_INET, SafeNativeMethods.TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
            IntPtr buffTable = Marshal.AllocHGlobal((int)buff_size);

            try
            {
                ret = SafeNativeMethods.GetExtendedTcpTable(buffTable, ref buff_size, true, AF_INET, SafeNativeMethods.TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
                if (ret != 0) return null;

                var tab = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(buffTable, typeof(MIB_TCPTABLE_OWNER_PID));
                IntPtr row_ptr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.dwNumEntries));
                rows = new MIB_TCPROW_OWNER_PID[tab.dwNumEntries];

                for (int i = 0; i < tab.dwNumEntries; i++)
                {
                    var row = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(row_ptr, typeof(MIB_TCPROW_OWNER_PID));
                    rows[i] = row;
                    row_ptr = (IntPtr)((long)row_ptr + Marshal.SizeOf(row));
                }

            }
            finally
            {
                Marshal.FreeHGlobal(buffTable);
            }
            return rows;
        }
示例#5
0
            /// <summary>
            /// 从MIB_TCPROW_OWNER_PID对象获得数据
            /// </summary>
            /// <param name="row">MIB_TCPROW_OWNER_PID</param>
            /// <returns></returns>
            internal static TcpPort FromTcpRow(MIB_TCPROW_OWNER_PID row)
            {
                int port = IPAddress.NetworkToHostOrder((short)row.LocalPort);
                var pid  = (int)row.OwningPid;

                return(new TcpPort(port, pid));
            }
示例#6
0
        public static bool GetPerTcpConnectionEStats_Path(MIB_TCPROW_OWNER_PID row, ref TCP_ESTATS_PATH_ROD_v0 rod)
        {
            var rw = new TCP_ESTATS_PATH_RW_v0();

            if (!GetPerTcpConnectionEStats(row, TCP_ESTATS_TYPE.TcpConnectionEstatsPath, ref rw, ref rod))
            {
                return(false);
            }

            if (rw.EnableCollection)
            {
                return(true);
            }

            rw.EnableCollection = true;
            if (!SetPerTcpConnectionEStats(row, TCP_ESTATS_TYPE.TcpConnectionEstatsPath, ref rw,
                                           nameof(rw.EnableCollection)))
            {
                return(false);
            }

            if (!GetPerTcpConnectionEStats(row, TCP_ESTATS_TYPE.TcpConnectionEstatsPath, ref rw, ref rod))
            {
                return(false);
            }

            return(rw.EnableCollection);
        }
示例#7
0
            public static MIB_TCPROW_OWNER_PID[] GetAllTcpConnections()
            {
                MIB_TCPROW_OWNER_PID[] tTable;
                int AF_INET  = 2;   // IP_v4
                int buffSize = 0;

                // how much memory do we need?
                uint ret = GetExtendedTcpTable(IntPtr.Zero,
                                               ref buffSize,
                                               true,
                                               AF_INET,
                                               TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL,
                                               0);

                if (ret != 0 && ret != 122) // 122 insufficient buffer size
                {
                    throw new Exception("bad ret on check " + ret);
                }
                IntPtr buffTable = Marshal.AllocHGlobal(buffSize);

                try
                {
                    ret = GetExtendedTcpTable(buffTable,
                                              ref buffSize,
                                              true,
                                              AF_INET,
                                              TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL,
                                              0);
                    if (ret != 0)
                    {
                        throw new Exception("bad ret " + ret);
                    }

                    // get the number of entries in the table
                    MIB_TCPTABLE_OWNER_PID tab =
                        (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(
                            buffTable,
                            typeof(MIB_TCPTABLE_OWNER_PID));
                    IntPtr rowPtr = (IntPtr)((long)buffTable +
                                             Marshal.SizeOf(tab.dwNumEntries));
                    tTable = new MIB_TCPROW_OWNER_PID[tab.dwNumEntries];

                    for (int i = 0; i < tab.dwNumEntries; i++)
                    {
                        MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal
                                                      .PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID));
                        tTable[i] = tcpRow;
                        // next entry
                        rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow));
                    }
                }
                finally
                {
                    // Free the Memory
                    Marshal.FreeHGlobal(buffTable);
                }
                return(tTable);
            }
        public static List <TcpRecordPid> GetAllTcpConnections()
        {
            int AF_INET  = 2;   // IP_v4
            int buffSize = 0;

            // getting the memory size needed
            uint val = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);

            if (val != 0 && val != 122)
            {
                throw new Exception("invalid size " + val);
            }

            IntPtr buffTable = Marshal.AllocHGlobal(buffSize);
            List <TcpRecordPid> lstRecords = new List <TcpRecordPid>();

            try
            {
                val = GetExtendedTcpTable(buffTable, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);

                if (val != 0)
                {
                    throw new Exception("ivalid data " + val);
                }

                // get the number of entries in the table
                MIB_TCPTABLE_OWNER_PID tcpTable = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(buffTable, typeof(MIB_TCPTABLE_OWNER_PID));
                IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tcpTable.dwNumEntries));
                //tTable = new MIB_TCPROW_OWNER_PID[tcpTable.dwNumEntries];

                for (int i = 0; i < tcpTable.dwNumEntries; i++)
                {
                    MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID));
                    //tTable[i] = tcpRow;
                    lstRecords.Add(new TcpRecordPid(
                                       new IPAddress(tcpRow.localAddr),
                                       new IPAddress(tcpRow.remoteAddr),
                                       BitConverter.ToUInt16(new byte[2] {
                        tcpRow.localPort2, tcpRow.localPort1
                    }, 0),                                                                                // reverse order
                                       BitConverter.ToUInt16(new byte[2] {
                        tcpRow.remotePort2, tcpRow.remotePort1
                    }, 0),                                                                                // reverse order
                                       tcpRow.owningPid,
                                       tcpRow.state));
                    // next entry
                    rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow));
                }
            }
            finally
            {
                // Free the Memory
                Marshal.FreeHGlobal(buffTable);
            }
            return(lstRecords);
        }
示例#9
0
        private TcpConnectionInformation2(MIB_TCPROW_OWNER_PID row)
        {
            State = (TcpState)row.state;
            var port  = (row.localPort1 << 8) | row.localPort2;
            var port2 = (State != TcpState.Listen) ? ((row.remotePort1 << 8) | row.remotePort2) : 0;

            LocalEndPoint  = new IPEndPoint(row.localAddr, port);
            RemoteEndPoint = new IPEndPoint(row.remoteAddr, port2);
            ProcessId      = row.owningPid;
        }
        //public TcpRow[] GetAllTcpConnections()
        public static MIB_TCPROW_OWNER_PID[] GetAllTcpConnections()
        {
            if (getAllTcpConnections_cached == null || getAllTcpConnections_cached_lastTime + new TimeSpan(0, 0, 1) < DateTime.Now)
            {
                //  TcpRow is my own class to display returned rows in a nice manner.
                //    TcpRow[] tTable;
                MIB_TCPROW_OWNER_PID[] tTable;
                int AF_INET  = 2;   // IP_v4
                int buffSize = 0;

                // how much memory do we need?
                uint   ret       = NativeMethods.GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
                IntPtr buffTable = Marshal.AllocHGlobal(buffSize);

                try
                {
                    ret = NativeMethods.GetExtendedTcpTable(buffTable, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
                    if (ret != 0)
                    {
                        return(new MIB_TCPROW_OWNER_PID[0]);
                    }

                    // get the number of entries in the table
                    //MibTcpTable tab = (MibTcpTable)Marshal.PtrToStructure(buffTable, typeof(MibTcpTable));
                    MIB_TCPTABLE_OWNER_PID tab = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(buffTable, typeof(MIB_TCPTABLE_OWNER_PID));
                    //IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.numberOfEntries) );
                    IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.dwNumEntries));
                    // buffer we will be returning
                    //tTable = new TcpRow[tab.numberOfEntries];
                    tTable = new MIB_TCPROW_OWNER_PID[tab.dwNumEntries];

                    //for (int i = 0; i < tab.numberOfEntries; i++)
                    for (int i = 0; i < tab.dwNumEntries; i++)
                    {
                        //MibTcpRow_Owner_Pid tcpRow = (MibTcpRow_Owner_Pid)Marshal.PtrToStructure(rowPtr, typeof(MibTcpRow_Owner_Pid));
                        MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID));
                        //tTable[i] = new TcpRow(tcpRow);
                        tTable[i] = tcpRow;
                        rowPtr    = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow)); // next entry
                    }
                }
                finally
                {
                    // Free the Memory
                    Marshal.FreeHGlobal(buffTable);
                }


                getAllTcpConnections_cached          = tTable;
                getAllTcpConnections_cached_lastTime = DateTime.Now;
            }

            return(getAllTcpConnections_cached);
        }
示例#11
0
        public static IEnumerable <ActiveConnectionDto> GetTcpConnections(int processId)
        {
            MIB_TCPROW_OWNER_PID[] tTable;
            var AF_INET  = 2; // IP_v4
            var buffSize = 0;

            // how much memory do we need?
            var ret = NativeMethods.GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);

            if (ret != 0 && ret != 122) // 122 insufficient buffer size
            {
                throw new Exception("bad ret on check " + ret);
            }

            var buffTable = Marshal.AllocHGlobal(buffSize);

            try
            {
                ret = NativeMethods.GetExtendedTcpTable(buffTable, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);
                if (ret != 0)
                {
                    throw new Exception("bad ret " + ret);
                }

                // get the number of entries in the table
                var tab    = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(buffTable, typeof(MIB_TCPTABLE_OWNER_PID));
                var rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.dwNumEntries));
                tTable = new MIB_TCPROW_OWNER_PID[tab.dwNumEntries];

                for (var i = 0; i < tab.dwNumEntries; i++)
                {
                    var tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID));
                    tTable[i] = tcpRow;
                    // next entry
                    rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow));
                }
            }
            finally
            {
                // Free the Memory
                Marshal.FreeHGlobal(buffTable);
            }

            return(tTable.Where(x => x.owningPid == processId).Select(x => new ActiveConnectionDto
            {
                ProtocolName = ProtocolName.Tcp,
                LocalAddress = IntToIp(x.localAddr),
                LocalPort = x.LocalPort,
                RemoteAddress = IntToIp(x.remoteAddr),
                RemotePort = x.RemotePort,
                State = ConvertToState(x.state)
            }));
        }
示例#12
0
        //return the MIB_TCPROW_OWNER_PID array as connection
        public MIB_TCPROW_OWNER_PID[] GetAllTcpConnections()
        {
            MIB_TCPROW_OWNER_PID[] tTable;
            int AF_INET  = 2;   // IP_v4
            int buffSize = 0;


            // what the size of the memory we need to allocate for the table?
            uint ret = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);
            //set pointer to buffer
            IntPtr buffTable = Marshal.AllocHGlobal(buffSize);


            try
            {
                //getting the buffer
                ret = GetExtendedTcpTable(buffTable, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);
                if (ret != 0)
                {
                    return(null);
                }


                //convert pointer to MIB_TCPTABLE_OWNER_PID pointer
                MIB_TCPTABLE_OWNER_PID tab = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(buffTable, typeof(MIB_TCPTABLE_OWNER_PID));
                IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.dwNumEntries));


                tTable = new MIB_TCPROW_OWNER_PID[tab.dwNumEntries];


                //reading the row from buffer using next position pointer
                //size of MIB_TCPROW_OWNER_PID
                for (int i = 0; i < tab.dwNumEntries; i++)
                {
                    //convert pointer to MIB_TCPROW_OWNER_PID pointer
                    MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID));
                    //save row in table
                    tTable[i] = tcpRow;
                    //go to the next entry.
                    rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow));
                }
            }
            finally
            {
                // clear buffer
                Marshal.FreeHGlobal(buffTable);
            }


            return(tTable);
        }
示例#13
0
        //public TcpRow[] GetAllTcpConnections()
        public static MIB_TCPROW_OWNER_PID[] GetAllTcpConnections()
        {
            //  TcpRow is my own class to display returned rows in a nice manner.
            //    TcpRow[] tTable;
            MIB_TCPROW_OWNER_PID[] tTable;
            int AF_INET = 2;    // IP_v4
            int buffSize = 0;

            // how much memory do we need?
            uint ret = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);
            IntPtr buffTable = Marshal.AllocHGlobal(buffSize);

            try
            {
                ret = GetExtendedTcpTable(buffTable, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);
                if (ret != 0)
                {
                    return null;
                }

                // get the number of entries in the table
                //MibTcpTable tab = (MibTcpTable)Marshal.PtrToStructure(buffTable, typeof(MibTcpTable));
                MIB_TCPTABLE_OWNER_PID tab = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(buffTable, typeof(MIB_TCPTABLE_OWNER_PID));
                //IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.numberOfEntries) );
                IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.dwNumEntries));
                // buffer we will be returning
                //tTable = new TcpRow[tab.numberOfEntries];
                tTable = new MIB_TCPROW_OWNER_PID[tab.dwNumEntries];

                //for (int i = 0; i < tab.numberOfEntries; i++)
                for (int i = 0; i < tab.dwNumEntries; i++)
                {
                    //MibTcpRow_Owner_Pid tcpRow = (MibTcpRow_Owner_Pid)Marshal.PtrToStructure(rowPtr, typeof(MibTcpRow_Owner_Pid));
                    MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID));
                    //tTable[i] = new TcpRow(tcpRow);
                    tTable[i] = tcpRow;
                    rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow));   // next entry
                }
            }
            finally
            {
                // Free the Memory
                Marshal.FreeHGlobal(buffTable);
            }

            return tTable;
        }
示例#14
0
        public MIB_TCPROW_OWNER_PID[] SelectAllTcpConnections()
        {
            MIB_TCPROW_OWNER_PID[] tTable;
            int AF_INET  = 2;   // IP_v4
            int buffSize = 0;

            // calculate memory usage
            uint   res       = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);
            IntPtr buffTable = Marshal.AllocHGlobal(buffSize);

            try
            {
                res = GetExtendedTcpTable(buffTable, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);
                if (res != 0)
                {
                    return(null);
                }

                // get the number of entries in the table
                MIB_TCPTABLE_OWNER_PID tab = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(buffTable, typeof(MIB_TCPTABLE_OWNER_PID));

                IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.dwNumEntries));

                // buffer we will be returning
                tTable = new MIB_TCPROW_OWNER_PID[tab.dwNumEntries];

                for (int i = 0; i < tab.dwNumEntries; i++)
                {
                    MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID));
                    tTable[i] = tcpRow;

                    //getting the next entry
                    //  C/C++  baseAddress+= sizeof( MIB_TCPROW_OWNER_PID);
                    rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow));
                }
            }
            finally
            {
                // Free the Memory
                Marshal.FreeHGlobal(buffTable);
            }



            return(tTable);
        }
示例#15
0
        public static bool GetPerTcpConnectionEStats <TRW, TROD>(MIB_TCPROW_OWNER_PID row, TCP_ESTATS_TYPE statsType, ref TRW rw, ref TROD rod)
        {
            var buffRow = IntPtr.Zero;
            var buffRW  = IntPtr.Zero;
            var buffROD = IntPtr.Zero;

            try
            {
                buffRow = Marshal.AllocHGlobal(Marshal.SizeOf(row));
                Marshal.StructureToPtr(row, buffRow, false);
                buffRW  = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(TRW)));
                buffROD = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(TROD)));

                var result = GetPerTcpConnectionEStats(buffRow, statsType,
                                                       buffRW, 0, (uint)Marshal.SizeOf(typeof(TRW)),
                                                       IntPtr.Zero, 0, 0,
                                                       buffROD, 0, (uint)Marshal.SizeOf(typeof(TROD)));

                if (result != 0)
                {
                    return(false);
                }

                rw  = (TRW)Marshal.PtrToStructure(buffRW, typeof(TRW));
                rod = (TROD)Marshal.PtrToStructure(buffROD, typeof(TROD));
            }
            finally
            {
                // Free the Memory
                if (buffRow != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(buffRow);
                }
                if (buffRW != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(buffRW);
                }
                if (buffROD != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(buffROD);
                }
            }
            return(true);
        }
示例#16
0
        public static MIB_TCPROW_OWNER_PID[] GetAllTcpConnections()
        {
            MIB_TCPROW_OWNER_PID[] tcpConnectionRows;
            int AF_INET  = 2;   // IPv4
            int buffSize = 0;

            // use WinAPI GetExtendedTcpTable to query all active tcp connection information
            uint ret = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, AF_INET, TCP_TABLE_TYPE.TCP_TABLE_OWNER_PID_ALL, 0);

            if (ret != 0 && ret != 122) // 122 means insufficient buffer size
            {
                throw new Exception("Error occurred when trying to query tcp table, return code: " + ret);
            }
            IntPtr buffTable = Marshal.AllocHGlobal(buffSize);

            try
            {
                ret = GetExtendedTcpTable(buffTable, ref buffSize, true, AF_INET, TCP_TABLE_TYPE.TCP_TABLE_OWNER_PID_ALL, 0);
                if (ret != 0)
                {
                    throw new Exception("Error occurred when trying to query tcp table, return code: " + ret);
                }

                // get the number of entries in the table
                MIB_TCPTABLE_OWNER_PID table = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(buffTable, typeof(MIB_TCPTABLE_OWNER_PID));
                IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(table.dwNumEntries));
                tcpConnectionRows = new MIB_TCPROW_OWNER_PID[table.dwNumEntries];

                for (int i = 0; i < table.dwNumEntries; i++)
                {
                    MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID));
                    tcpConnectionRows[i] = tcpRow;
                    rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow));
                }
            }
            finally
            {
                // free memory
                Marshal.FreeHGlobal(buffTable);
            }
            return(tcpConnectionRows);
        }
        public MIB_TCPROW_OWNER_PID[] GetAllTcpConnections()
        {
            // TcpRow is my own class to display returned rows in a nice manner.
            MIB_TCPROW_OWNER_PID[] tTable;
            int AF_INET  = 2;   // IP_v4
            int buffSize = 0;

            // how much memory do we need?
            uint   ret       = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
            IntPtr buffTable = Marshal.AllocHGlobal(buffSize);

            try
            {
                ret = GetExtendedTcpTable(buffTable, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
                if (ret != 0)
                {
                    return(null);
                }

                // get the number of entries in the table
                MIB_TCPTABLE_OWNER_PID tab = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(buffTable, typeof(MIB_TCPTABLE_OWNER_PID));
                IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.dwNumEntries));
                // buffer we will be returning;
                tTable = new MIB_TCPROW_OWNER_PID[tab.dwNumEntries];

                for (int i = 0; i < tab.dwNumEntries; i++)
                {
                    MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID));
                    tTable[i] = tcpRow;
                    rowPtr    = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow)); // next entry
                }
            }
            finally
            {
                // Free the Memory
                Marshal.FreeHGlobal(buffTable);
            }
            return(tTable);
        }
示例#18
0
        public static MIB_TCPROW_OWNER_PID[] GetTcpTableEx()
        {
            MIB_TCPROW_OWNER_PID[] tTable;

            int buffSize = 0;

            // Determine much memory is needed
            uint   ret       = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, (int)AddressFamily.InterNetwork, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
            IntPtr buffTable = Marshal.AllocHGlobal(buffSize);

            try
            {
                ret = GetExtendedTcpTable(buffTable, ref buffSize, true, (int)(int)AddressFamily.InterNetwork, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
                if (ret != 0)
                {
                    return(null);
                }

                // get the number of entries in the table
                MIB_TCPTABLE_OWNER_PID tab = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(buffTable, typeof(MIB_TCPTABLE_OWNER_PID));
                IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.dwNumEntries));

                // buffer we will be returning
                tTable = new MIB_TCPROW_OWNER_PID[tab.dwNumEntries];

                for (int i = 0; i < tab.dwNumEntries; i++)
                {
                    MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID));
                    tTable[i] = tcpRow;
                    rowPtr    = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow)); // next entry
                }
            }
            finally
            {
                // Free the Memory
                Marshal.FreeHGlobal(buffTable);
            }
            return(tTable);
        }
示例#19
0
        private static MIB_TCPROW_OWNER_PID[] GetAllTcpConnections()
        {
            const int NO_ERROR = 0;
            const int IP_v4    = 2;

            MIB_TCPROW_OWNER_PID[] tTable = null;
            int buffSize = 0;

            GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, IP_v4, TCP_TABLE_OWNER_PID_ALL, 0);
            IntPtr buffTable = Marshal.AllocHGlobal(buffSize);

            try
            {
                if (NO_ERROR != GetExtendedTcpTable(buffTable, ref buffSize, true, IP_v4, TCP_TABLE_OWNER_PID_ALL, 0))
                {
                    return(null);
                }
                MIB_TCPTABLE_OWNER_PID tab =
                    (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(buffTable, typeof(MIB_TCPTABLE_OWNER_PID));
                IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.dwNumEntries));
                tTable = new MIB_TCPROW_OWNER_PID[tab.dwNumEntries];

                int rowSize = Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID));
                for (int i = 0; i < tab.dwNumEntries; i++)
                {
                    MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID));
                    tTable[i] = tcpRow;
                    rowPtr    = (IntPtr)((long)rowPtr + rowSize);
                }
            }
            catch { }
            finally
            {
                Marshal.FreeHGlobal(buffTable);
            }
            return(tTable);
        }
示例#20
0
        public static bool SetPerTcpConnectionEStats <TRW>(MIB_TCPROW_OWNER_PID row,
                                                           TCP_ESTATS_TYPE statsType, ref TRW rw, string fieldName)
        {
            var offset = (uint)Marshal.OffsetOf(typeof(TRW), fieldName);

            var buffRow = IntPtr.Zero;
            var buffRW  = IntPtr.Zero;

            try
            {
                buffRow = Marshal.AllocHGlobal(Marshal.SizeOf(row));
                Marshal.StructureToPtr(row, buffRow, false);
                buffRW = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(TRW)));
                Marshal.StructureToPtr(rw, buffRW, false);

                var result = SetPerTcpConnectionEStats(buffRow, statsType,
                                                       buffRW, 0, (uint)Marshal.SizeOf(typeof(TRW)), offset);

                if (result != 0)
                {
                    return(false);
                }
            }
            finally
            {
                // Free the Memory
                if (buffRow != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(buffRow);
                }
                if (buffRW != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(buffRW);
                }
            }
            return(true);
        }
示例#21
0
        public static MIB_TCPROW_OWNER_PID[] GetAllTcpConnections()
        {
            MIB_TCPROW_OWNER_PID[] tTable;
            var buffSize = 0;

            // how much memory do we need?
            var ret       = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
            var buffTable = Marshal.AllocHGlobal(buffSize);

            try
            {
                ret = GetExtendedTcpTable(buffTable, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
                if (ret != 0)
                {
                    return(null);
                }

                // get the number of entries in the table
                var tab    = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(buffTable, typeof(MIB_TCPTABLE_OWNER_PID));
                var rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.dwNumEntries));
                tTable = new MIB_TCPROW_OWNER_PID[tab.dwNumEntries];

                for (var i = 0; i < tab.dwNumEntries; i++)
                {
                    var tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID));
                    tTable[i] = tcpRow;
                    rowPtr    = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow)); // next entry
                }
            }
            finally
            {
                // Free the Memory
                Marshal.FreeHGlobal(buffTable);
            }
            return(tTable);
        }
示例#22
0
        /// <summary>
        /// The main worker thread that does process scanning. Background this so it doesn't interfere with our main thread.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void procListUpdater_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            //Make sure we're in Debug Mode so we have access to all processes.
            Process.EnterDebugMode();
            //Change our process priority to Below Normal so we don't eat all the CPU time.
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.BelowNormal;
            BackgroundWorker worker = sender as BackgroundWorker;
            List<Process> procs = new List<Process>();
            Process[] all = Process.GetProcesses();

            for (int i = 0; i < all.Length; i++)
            {
                double pct = (double) i / (double) all.Length;
                pct = pct * 100;

                Process p = all[i];

                //Report our progress as a percentage of the process list completed.
                worker.ReportProgress((int)pct,"");

                //It's important to refresh processes before each check. A full scan is time consuming, and process state can often change in between.
                p.Refresh();
                try
                {
                    //Check to make sure our process is still there
                    if (!p.HasExited)
                    {
                        //Filter out ourselves as well as the Windows Defender module. Windows Defender will almost always have the signature we're looking for provided AntiPwny is running
                        if (!p.MainModule.FileName.ToLower().Contains("msmpeng"))
                        {
                            //Use a different scan for Java. We still need to look for meterpreter in java as well, because it can be migrated. This will look specifically for Java Meterpreter
                            if (p.ProcessName == "java")
                            {
                                if (Utilities.scanJava(p))
                                {
                                    procs.Add(p);
                                }
                            }

                            //Scan our process for Meterpreter
                            if (Utilities.scanProcess(p))
                            {
                                procs.Add(p);
                            }

                        }
                    }
                }
                catch (Exception f) { Console.WriteLine("Error opening " + p.ProcessName); Console.WriteLine(f.Message); }
            }

            //Build our TCP table so we have all connections
            MIB_TCPROW_OWNER_PID[] table;

            int inet = 2;
            int buffSize = 0;
            uint ret = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, inet, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);

            IntPtr buffTable = Marshal.AllocHGlobal(buffSize);

            try
            {
                ret = GetExtendedTcpTable(buffTable, ref buffSize, true, inet, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);
                if (ret != 0)
                {
                    return;
                }

                // get the number of entries in the table
                MIB_TCPTABLE_OWNER_PID tab = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(buffTable, typeof(MIB_TCPTABLE_OWNER_PID));
                IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.dwNumEntries));
                table = new MIB_TCPROW_OWNER_PID[tab.dwNumEntries];

                for (int i = 0; i < tab.dwNumEntries; i++)
                {
                    MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID));
                    table[i] = tcpRow;
                    rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow));   // next entry
                }
            }
            finally
            {
                // Free the Memory
                Marshal.FreeHGlobal(buffTable);
            }

            worker.ReportProgress(100, "Scanning Connections");

            //Map connections to PIDs for easier lookup
            Dictionary<int, List<ProcessListObject>> map = new Dictionary<int, List<ProcessListObject>>();
            foreach (MIB_TCPROW_OWNER_PID row in table){
                List<ProcessListObject> list;
                map.TryGetValue(row.owningPid, out list);
                if (list != null)
                {
                    ProcessListObject temp = new ProcessListObject();
                    temp.ProcessName = new IPAddress(BitConverter.GetBytes(row.localAddr)).ToString() +" (" + BitConverter.ToUInt16(
                        new byte[2] { row.localPort2, row.localPort1 }, 0) + ")";
                    temp.ProcessID = "->";
                    temp.ProcessPath = new IPAddress(BitConverter.GetBytes(row.remoteAddr)).ToString() + " (" + BitConverter.ToUInt16(
                        new byte[2] { row.localPort2, row.localPort1 }, 0) + ")";
                    list.Add(temp);
                    temp.InternalID = row.owningPid;
                    map.Remove(row.owningPid);
                    map.Add(row.owningPid, list);
                }
                else
                {
                    list = new List<ProcessListObject>();
                    ProcessListObject temp = new ProcessListObject();
                    temp.ProcessName = new IPAddress(BitConverter.GetBytes(row.localAddr)).ToString() + " (" + BitConverter.ToUInt16(
                        new byte[2] { row.localPort2, row.localPort1 }, 0) + ")";
                    temp.ProcessID = "->";
                    temp.ProcessPath = new IPAddress(BitConverter.GetBytes(row.remoteAddr)).ToString() + " (" + BitConverter.ToUInt16(
                        new byte[2] { row.localPort2, row.localPort1 }, 0) + ")";
                    list.Add(temp);
                    temp.InternalID = row.owningPid;
                    map.Add(row.owningPid, list);
                }
            }

            List<ProcessListObject> objects = new List<ProcessListObject>();
            List<ProcessListObject> reference;

            //Loop back through the processes we detected with Meterpreter and correlate connections going outbound for display
            foreach (Process p in procs)
            {
                p.Refresh();

                if (!p.HasExited)
                {
                    if (PreventionMode)
                    {
                        builder.Clear();
                        builder.Append(p.ProcessName);
                        builder.Append(" Killed");
                        w.write(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString(), builder.ToString(), "Meterpreter");
                        p.Kill();
                    }
                    else
                    {
                        ProcessListObject temp = new ProcessListObject();
                        temp.ProcessID = p.Id.ToString();
                        temp.ProcessName = p.ProcessName;
                        temp.ProcessPath = p.MainModule.FileName;
                        temp.InternalID = p.Id;
                        temp.Detected = "Meterpreter";

                        map.TryGetValue(p.Id, out reference);
                        if (reference != null)
                        {
                            foreach (ProcessListObject t in reference)
                            {
                                t.Parent = temp;
                            }
                            temp.Connections = reference;

                        }
                        else
                        {
                            temp.Connections = null;
                        }
                        objects.Add(temp);
                    }
                }
            }

            worker.ReportProgress(100, "Scanning cmd.exe");

            //Looking for reverse shells. They usually manifest as cmd.exe with a parent process running that has the actual reverse connection
            foreach (Process p in Process.GetProcessesByName("cmd"))
            {
                Process par = Utilities.ParentProcessUtilities.GetParentProcess(p.Id);
                if (par != null)
                    map.TryGetValue(par.Id, out reference);
                else
                    map.TryGetValue(p.Id, out reference);
                if (reference != null)
                {
                    if (PreventionMode)
                    {
                        p.Kill();
                        w.write(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString(), "Killed cmd.exe", "Reverse Shell");
                    }
                    else
                    {
                        ProcessListObject temp = new ProcessListObject();
                        temp.ProcessID = p.Id.ToString();
                        temp.ProcessName = p.ProcessName;
                        temp.ProcessPath = p.MainModule.FileName;
                        temp.InternalID = p.Id;
                        temp.Detected = "Reverse Shell";

                        foreach (ProcessListObject t in reference)
                        {
                            t.Parent = temp;
                        }

                        temp.Connections = reference;

                        objects.Add(temp);
                    }
                }
            }

            worker.ReportProgress(100, "Scanning wscript");

            //Look through wscript and cscript, which are almost always used for meterpreter. If we find the command line arguments
            //contain both temp and .vbs, we can be fairly certain this is a persistence script being called.
            foreach (Process p in Process.GetProcessesByName("wscript"))
            {
                string s = Utilities.GetCmdArguments(p);
                if (s.ToLower().Contains("temp") && s.ToLower().Contains(".vbs"))
                {
                    ProcessListObject temp = new ProcessListObject();
                    temp.ProcessID = p.Id.ToString();
                    temp.ProcessName = p.ProcessName;
                    temp.ProcessPath = p.MainModule.FileName;
                    temp.InternalID = p.Id;
                    temp.Detected = "Persistence WScript";
                    temp.Connections = null;
                    objects.Add(temp);
                }
            }

            foreach (Process p in Process.GetProcessesByName("cscript"))
            {
                string s = Utilities.GetCmdArguments(p);
                if (s.ToLower().Contains("temp") && s.ToLower().Contains(".vbs"))
                {
                    ProcessListObject temp = new ProcessListObject();
                    temp.ProcessID = p.Id.ToString();
                    temp.ProcessName = p.ProcessName;
                    temp.ProcessPath = p.MainModule.FileName;
                    temp.InternalID = p.Id;
                    temp.Detected = "Persistence CScript";
                    temp.Connections = null;
                    objects.Add(temp);
                }
            }
            Process.LeaveDebugMode();
            //Exit Debug Mode
            worker.ReportProgress(100, "Waiting :60 Till Next Scan");
            //Report our finished status
            e.Result = objects;
        }
示例#23
0
        private static Connection[] GetTCP()
        {
            MIB_TCPROW_OWNER_PID[] tTable;
            int AF_INET  = 2;
            int buffSize = 0;

            uint   ret       = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);
            IntPtr buffTable = Marshal.AllocHGlobal(buffSize);

            try
            {
                ret = GetExtendedTcpTable(buffTable, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);
                if (ret != 0)
                {
                    Connection[] con = new Connection[0];
                    return(con);
                }

                MIB_TCPTABLE_OWNER_PID tab = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(buffTable, typeof(MIB_TCPTABLE_OWNER_PID));
                IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.dwNumEntries));
                tTable = new MIB_TCPROW_OWNER_PID[tab.dwNumEntries];

                for (int i = 0; i < tab.dwNumEntries; i++)
                {
                    MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID));
                    tTable[i] = tcpRow;
                    rowPtr    = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow)); // next entry
                }
            }
            finally
            {
                Marshal.FreeHGlobal(buffTable);
            }

            Connection[] cons = new Connection[tTable.Length];

            for (int i = 0; i < tTable.Length; i++)
            {
                IPAddress localip   = new IPAddress(BitConverter.GetBytes(tTable[i].dwLocalAddr));
                IPAddress remoteip  = new IPAddress(BitConverter.GetBytes(tTable[i].dwRemoteAddr));
                byte[]    barray    = BitConverter.GetBytes(tTable[i].dwLocalPort);
                int       localport = (barray[0] * 256) + barray[1];
                barray = BitConverter.GetBytes(tTable[i].dwRemotePort);
                int    remoteport = (barray[0] * 256) + barray[1];
                string state;
                switch (tTable[i].dwState)
                {
                case 1:
                    state = "Closed";
                    break;

                case 2:
                    state = "LISTENING";
                    break;

                case 3:
                    state = "SYN SENT";
                    break;

                case 4:
                    state = "SYN RECEIVED";
                    break;

                case 5:
                    state = "ESTABLISHED";
                    break;

                case 6:
                    state = "FINSIHED 1";
                    break;

                case 7:
                    state = "FINISHED 2";
                    break;

                case 8:
                    state = "CLOSE WAIT";
                    break;

                case 9:
                    state = "CLOSING";
                    break;

                case 10:
                    state = "LAST ACKNOWLEDGE";
                    break;

                case 11:
                    state = "TIME WAIT";
                    break;

                case 12:
                    state = "DELETE TCB";
                    break;

                default:
                    state = "UNKNOWN";
                    break;
                }
                Connection tmp = new Connection(localip, localport, remoteip, remoteport, (int)tTable[i].dwOwningPid, state);
                cons[i] = (tmp);
            }
            return(cons);
        }
示例#24
0
        public static List <TcpConnectionInfo> GetTcpConnections(IPVersion ipVersion, Dictionary <int, Process> processesByPid = null)
        {
            int bufferSize = 0;
            List <TcpConnectionInfo> tcpTableRecords = new List <TcpConnectionInfo>();

            int ulAf = AF_INET;

            if (ipVersion == IPVersion.IPv6)
            {
                ulAf = AF_INET6;
            }

            // Getting the initial size of TCP table.
            uint result = Iphlpapi.GetExtendedTcpTable(IntPtr.Zero, ref bufferSize, true, ulAf, TcpTableClass.TCP_TABLE_OWNER_PID_ALL);

            // Allocating memory as an IntPtr with the bufferSize.
            IntPtr tcpTableRecordsPtr = Marshal.AllocHGlobal(bufferSize);

            try
            {
                // The IntPtr from last call, tcpTableRecoresPtr must be used in the subsequent
                // call and passed as the first parameter.
                result = Iphlpapi.GetExtendedTcpTable(tcpTableRecordsPtr, ref bufferSize, true, ulAf, TcpTableClass.TCP_TABLE_OWNER_PID_ALL);

                // If not zero, the call failed.
                if (result != 0)
                {
                    return(new List <TcpConnectionInfo>());
                }

                // Marshals data fron an unmanaged block of memory to the
                // newly allocated managed object 'tcpRecordsTable' of type
                // 'MIB_TCPTABLE_OWNER_PID' to get number of entries of TCP
                // table structure.

                // Determine if IPv4 or IPv6.
                if (ipVersion == IPVersion.IPv4)
                {
                    MIB_TCPTABLE_OWNER_PID tcpRecordsTable = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(tcpTableRecordsPtr, typeof(MIB_TCPTABLE_OWNER_PID));

                    IntPtr tableRowPtr = (IntPtr)((long)tcpTableRecordsPtr + Marshal.SizeOf(tcpRecordsTable.dwNumEntries));

                    // Read and parse the TCP records from the table and store them in list
                    // 'TcpConnection' structure type objects.
                    for (int row = 0; row < tcpRecordsTable.dwNumEntries; row++)
                    {
                        MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(tableRowPtr, typeof(MIB_TCPROW_OWNER_PID));

                        // Add row to list of TcpConnetions.
                        tcpTableRecords.Add(new TcpConnectionInfo(
                                                Protocol.TCP,
                                                new IPAddress(tcpRow.localAddr),
                                                new IPAddress(tcpRow.remoteAddr),
                                                BitConverter.ToUInt16(new byte[2] {
                            tcpRow.localPort[1],
                            tcpRow.localPort[0]
                        }, 0),
                                                BitConverter.ToUInt16(new byte[2] {
                            tcpRow.remotePort[1],
                            tcpRow.remotePort[0]
                        }, 0),
                                                tcpRow.owningPid,
                                                tcpRow.state,
                                                GetProcessNameByPid(tcpRow.owningPid, processesByPid)));

                        tableRowPtr = (IntPtr)((long)tableRowPtr + Marshal.SizeOf(tcpRow));
                    }
                }
                else if (ipVersion == IPVersion.IPv6)
                {
                    MIB_TCP6TABLE_OWNER_PID tcpRecordsTable = (MIB_TCP6TABLE_OWNER_PID)Marshal.PtrToStructure(tcpTableRecordsPtr, typeof(MIB_TCP6TABLE_OWNER_PID));

                    IntPtr tableRowPtr = (IntPtr)((long)tcpTableRecordsPtr + Marshal.SizeOf(tcpRecordsTable.dwNumEntries));

                    // Read and parse the TCP records from the table and store them in list
                    // 'TcpConnection' structure type objects.
                    for (int row = 0; row < tcpRecordsTable.dwNumEntries; row++)
                    {
                        MIB_TCP6ROW_OWNER_PID tcpRow = (MIB_TCP6ROW_OWNER_PID)Marshal.PtrToStructure(tableRowPtr, typeof(MIB_TCP6ROW_OWNER_PID));

                        tcpTableRecords.Add(new TcpConnectionInfo(
                                                Protocol.TCP,
                                                new IPAddress(tcpRow.localAddr, tcpRow.localScopeId),
                                                new IPAddress(tcpRow.remoteAddr, tcpRow.remoteScopeId),
                                                BitConverter.ToUInt16(new byte[2] {
                            tcpRow.localPort[1],
                            tcpRow.localPort[0]
                        }, 0),
                                                BitConverter.ToUInt16(new byte[2] {
                            tcpRow.remotePort[1],
                            tcpRow.remotePort[0]
                        }, 0),
                                                tcpRow.owningPid,
                                                tcpRow.state,
                                                GetProcessNameByPid(tcpRow.owningPid, processesByPid)));

                        tableRowPtr = (IntPtr)((long)tableRowPtr + Marshal.SizeOf(tcpRow));
                    }
                }
            }
            catch (OutOfMemoryException outOfMemoryException)
            {
                throw outOfMemoryException;
            }
            catch (Exception exception)
            {
                throw exception;
            }
            finally
            {
                Marshal.FreeHGlobal(tcpTableRecordsPtr);
            }

            return(tcpTableRecords != null?tcpTableRecords.Distinct().ToList() : new List <TcpConnectionInfo>());
        }
示例#25
0
        //根据端口找PID
        private void TrySetProcessId(int port)
        {
            int bufferSize = 0;

            uint   result             = GetExtendedTcpTable(IntPtr.Zero, ref bufferSize, true, INET, TcpTableClass.TCP_TABLE_OWNER_PID_ALL);
            IntPtr tcpTableRecordsPtr = Marshal.AllocHGlobal(bufferSize);

            try
            {
                result = GetExtendedTcpTable(tcpTableRecordsPtr, ref bufferSize, true, INET, TcpTableClass.TCP_TABLE_OWNER_PID_ALL);

                MIB_TCPTABLE_OWNER_PID tcpRecordsTable = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(tcpTableRecordsPtr, typeof(MIB_TCPTABLE_OWNER_PID));

                IntPtr tableRowPtr = (IntPtr)((long)tcpTableRecordsPtr + Marshal.SizeOf(tcpRecordsTable.dwNumEntries));

                for (int row = 0; row < tcpRecordsTable.dwNumEntries; row++)
                {
                    MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(tableRowPtr, typeof(MIB_TCPROW_OWNER_PID));
                    int localPort = BitConverter.ToUInt16(new byte[2] {
                        tcpRow.localPort[1], tcpRow.localPort[0]
                    }, 0);
                    int remotePort = BitConverter.ToUInt16(new byte[2] {
                        tcpRow.remotePort[1], tcpRow.remotePort[0]
                    }, 0);
                    int pid = tcpRow.owningPid;

                    if (localPort == port)
                    {
                        Process p = Process.GetProcessById(pid);
                        //IE比较烦,要获取最先启动的那个主进程 这里不知道怎么找,暂时通过启动时间找,是否靠谱待验证
                        if (p.ProcessName == "iexplore")
                        {
                            DateTime  time  = DateTime.MaxValue;
                            Process[] procs = Process.GetProcessesByName("iexplore");
                            for (int ii = 0; ii < procs.Length; ii++)
                            {
                                if (time == DateTime.MaxValue)
                                {
                                    pid  = procs[ii].Id;
                                    time = procs[ii].StartTime;
                                    continue;
                                }
                                else if (procs[ii].StartTime < time)
                                {
                                    pid  = procs[ii].Id;
                                    time = procs[ii].StartTime;
                                    continue;
                                }
                            }
                        }
                        this.ProcessId = pid;
                        break;
                    }

                    tableRowPtr = (IntPtr)((long)tableRowPtr + Marshal.SizeOf(tcpRow));

                    //IPAddress localIp, IPAddress remoteIp, ushort localPort,ushort remotePort, int pId, MibTcpState state
                    //tcpTableRecords.Add(new TcpProcessRecord(
                    //                      new IPAddress(tcpRow.localAddr),
                    //                      new IPAddress(tcpRow.remoteAddr),
                    //                      BitConverter.ToUInt16(new byte[2] {
                    //                          tcpRow.localPort[1],
                    //                          tcpRow.localPort[0] }, 0),
                    //                      BitConverter.ToUInt16(new byte[2] {
                    //                          tcpRow.remotePort[1],
                    //                          tcpRow.remotePort[0] }, 0),
                    //                      tcpRow.owningPid, tcpRow.state));
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                Marshal.FreeHGlobal(tcpTableRecordsPtr);
            }
        }
示例#26
0
        public static List <TcpProcessRecord> GetAllTcpConnections()
        {
            int bufferSize = 0;
            List <TcpProcessRecord> tcpTableRecords = new List <TcpProcessRecord>();

            // Getting the size of TCP table, that is returned in 'bufferSize' variable.
            uint result = GetExtendedTcpTable(IntPtr.Zero, ref bufferSize, true, AF_INET,
                                              TcpTableClass.TCP_TABLE_OWNER_PID_ALL);

            // Allocating memory from the unmanaged memory of the process by using the
            // specified number of bytes in 'bufferSize' variable.
            IntPtr tcpTableRecordsPtr = Marshal.AllocHGlobal(bufferSize);

            try
            {
                // The size of the table returned in 'bufferSize' variable in previous
                // call must be used in this subsequent call to 'GetExtendedTcpTable'
                // function in order to successfully retrieve the table.
                result = GetExtendedTcpTable(tcpTableRecordsPtr, ref bufferSize, true,
                                             AF_INET, TcpTableClass.TCP_TABLE_OWNER_PID_ALL);

                // Non-zero value represent the function 'GetExtendedTcpTable' failed,
                // hence empty list is returned to the caller function.
                if (result != 0)
                {
                    return(new List <TcpProcessRecord>());
                }

                // Marshals data from an unmanaged block of memory to a newly allocated
                // managed object 'tcpRecordsTable' of type 'MIB_TCPTABLE_OWNER_PID'
                // to get number of entries of the specified TCP table structure.
                MIB_TCPTABLE_OWNER_PID tcpRecordsTable = (MIB_TCPTABLE_OWNER_PID)
                                                         Marshal.PtrToStructure(tcpTableRecordsPtr,
                                                                                typeof(MIB_TCPTABLE_OWNER_PID));
                IntPtr tableRowPtr = (IntPtr)((long)tcpTableRecordsPtr +
                                              Marshal.SizeOf(tcpRecordsTable.dwNumEntries));

                // Reading and parsing the TCP records one by one from the table and
                // storing them in a list of 'TcpProcessRecord' structure type objects.
                for (int row = 0; row < tcpRecordsTable.dwNumEntries; row++)
                {
                    MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.
                                                  PtrToStructure(tableRowPtr, typeof(MIB_TCPROW_OWNER_PID));
                    tcpTableRecords.Add(new TcpProcessRecord(
                                            new IPAddress(tcpRow.localAddr),
                                            new IPAddress(tcpRow.remoteAddr),
                                            BitConverter.ToUInt16(new byte[2] {
                        tcpRow.localPort[1],
                        tcpRow.localPort[0]
                    }, 0),
                                            BitConverter.ToUInt16(new byte[2] {
                        tcpRow.remotePort[1],
                        tcpRow.remotePort[0]
                    }, 0),
                                            tcpRow.owningPid, tcpRow.state));
                    tableRowPtr = (IntPtr)((long)tableRowPtr + Marshal.SizeOf(tcpRow));
                }
            }
            catch (OutOfMemoryException)
            {
            }
            catch (Exception)
            {
            }
            finally
            {
                Marshal.FreeHGlobal(tcpTableRecordsPtr);
            }
            return(tcpTableRecords != null?tcpTableRecords.Distinct()
                   .ToList <TcpProcessRecord>() : new List <TcpProcessRecord>());
        }