Esempio n. 1
0
        public static PacketCommunicator OpenLiveDevice()
        {
            NetworkInterface networkInterface =
                NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(
                    ni => !ni.IsReceiveOnly && ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet && ni.OperationalStatus == OperationalStatus.Up);
            LivePacketDevice device = networkInterface.GetLivePacketDevice();

            MoreAssert.IsMatch(@"Network adapter '.*' on local host", device.Description);
            Assert.AreEqual(DeviceAttributes.None, device.Attributes);
            Assert.AreNotEqual(MacAddress.Zero, device.GetMacAddress());
            Assert.AreNotEqual(string.Empty, device.GetPnpDeviceId());
            MoreAssert.IsBiggerOrEqual(1, device.Addresses.Count);
            foreach (DeviceAddress address in device.Addresses)
            {
                if (address.Address.Family == SocketAddressFamily.Internet)
                {
                    MoreAssert.IsMatch("Address: " + SocketAddressFamily.Internet + @" [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+ " +
                                       "Netmask: " + SocketAddressFamily.Internet + @" 255\.[0-9]+\.[0-9]+\.[0-9]+ " +
                                       "Broadcast: " + SocketAddressFamily.Internet + @" 255.255.255.255",
                                       address.ToString());
                }
                else
                {
                    Assert.AreEqual(SocketAddressFamily.Internet6, address.Address.Family);
                    MoreAssert.IsMatch("Address: " + SocketAddressFamily.Internet6 + @" (?:[0-9A-F]{4}:){7}[0-9A-F]{4} " +
                                       "Netmask: " + SocketAddressFamily.Unspecified + @" " + IpV6Address.Zero + " " +
                                       "Broadcast: " + SocketAddressFamily.Unspecified + @" " + IpV6Address.Zero,
                                       address.ToString());
                }
            }

            PacketCommunicator communicator = device.Open();

            try
            {
                MoreAssert.AreSequenceEqual(new[] { DataLinkKind.Ethernet, DataLinkKind.Docsis }.Select(kind => new PcapDataLink(kind)), communicator.SupportedDataLinks);
                PacketTotalStatistics totalStatistics = communicator.TotalStatistics;
                Assert.AreEqual <object>(totalStatistics, totalStatistics);
                Assert.AreNotEqual(null, totalStatistics);
                Assert.AreEqual(totalStatistics.GetHashCode(), totalStatistics.GetHashCode());
                Assert.IsTrue(totalStatistics.Equals(totalStatistics));
                Assert.IsFalse(totalStatistics.Equals(null));
                Assert.AreNotEqual(null, totalStatistics);
                Assert.AreNotEqual(totalStatistics, 2);
                MoreAssert.IsSmallerOrEqual <uint>(1, totalStatistics.PacketsCaptured, "PacketsCaptured");
                Assert.AreEqual <uint>(0, totalStatistics.PacketsDroppedByDriver, "PacketsDroppedByDriver");
                Assert.AreEqual <uint>(0, totalStatistics.PacketsDroppedByInterface, "PacketsDroppedByInterface");
                MoreAssert.IsSmallerOrEqual <uint>(1, totalStatistics.PacketsReceived, "PacketsReceived");
                Assert.IsNotNull(totalStatistics.ToString());
                communicator.SetKernelBufferSize(2 * 1024 * 1024); // 2 MB instead of 1
                communicator.SetKernelMinimumBytesToCopy(10);      // 10 bytes minimum to copy
                communicator.SetSamplingMethod(new SamplingMethodNone());
                Assert.AreEqual(DataLinkKind.Ethernet, communicator.DataLink.Kind);
                communicator.DataLink = communicator.DataLink;
                Assert.AreEqual("EN10MB (Ethernet)", communicator.DataLink.ToString());
                Assert.AreEqual(communicator.DataLink, new PcapDataLink(communicator.DataLink.Name));
                Assert.IsTrue(communicator.IsFileSystemByteOrder);
                Assert.AreEqual(PacketCommunicatorMode.Capture, communicator.Mode);
                Assert.IsFalse(communicator.NonBlocking);
                Assert.AreEqual(PacketDevice.DefaultSnapshotLength, communicator.SnapshotLength);
                return(communicator);
            }
            catch (Exception)
            {
                communicator.Dispose();
                throw;
            }
        }
Esempio n. 2
0
        protected override bool CompareField(XElement field, Datagram datagram)
        {
            HttpDatagram httpDatagram = (HttpDatagram)datagram;

            if (field.Name() == "data" || field.Name() == "data.data")
            {
                if (field.Name() == "data")
                {
                    field.AssertNoShow();
                }

                MoreAssert.AreSequenceEqual(httpDatagram.Subsegment(0, _data.Length / 2), HexEncoding.Instance.GetBytes(_data.ToString()));
                // TODO: Uncomment once https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=10707 is fixed.
//                field.AssertValue(httpDatagram.Subsegment(_data.Length / 2 + 2, httpDatagram.Length - _data.Length / 2 - 2));
                return(false);
            }

            string fieldShow = field.Show();
            string httpFieldName;

            switch (field.Name())
            {
            case "http.request":
                field.AssertShowDecimal(httpDatagram.IsRequest);
                break;

            case "http.response":
                field.AssertShowDecimal(httpDatagram.IsResponse);
                break;

            case "":
                if (fieldShow == "HTTP chunked response")
                {
                    throw new InvalidOperationException("HTTP chunked response");
                }
                if (fieldShow == @"\r\n" || fieldShow == "HTTP response 1/1" || fieldShow == "HTTP request 1/1")
                {
                    break;
                }

                _data.Append(field.Value());

                if (_isFirstEmptyName)
                {
                    CompareHttpFirstLine(field, httpDatagram);
                    _isFirstEmptyName = false;
                }
                else if (fieldShow.StartsWith("Content-encoded entity body"))
                {
                    break;
                }
                else
                {
                    fieldShow = EncodingExtensions.Iso88591.GetString(HexEncoding.Instance.GetBytes(field.Value()));
                    fieldShow = fieldShow.Substring(0, fieldShow.Length - 2);
                    int colonIndex = fieldShow.IndexOf(':');
                    MoreAssert.IsBiggerOrEqual(0, colonIndex, "Can't find colon in field with empty name");

                    if (httpDatagram.Header == null)
                    {
                        if (httpDatagram.IsRequest)
                        {
                            Assert.IsNull(httpDatagram.Version);
                        }
                        else
                        {
                            Assert.IsTrue(IsBadHttp(httpDatagram));
                        }
                        break;
                    }
                    httpFieldName = fieldShow.Substring(0, colonIndex);
                    if (!field.Value().EndsWith("0d0a"))
                    {
                        Assert.IsNull(httpDatagram.Header[httpFieldName]);
                    }
                    else
                    {
                        string fieldValue         = fieldShow.Substring(colonIndex + 1).SkipWhile(c => c == ' ').TakeWhile(c => c != '\\').SequenceToString();
                        string expectedFieldValue = httpDatagram.Header[httpFieldName].ValueString;
                        Assert.IsTrue(expectedFieldValue.Contains(fieldValue),
                                      string.Format("{0} <{1}> doesn't contain <{2}>", field.Name(), expectedFieldValue, fieldValue));
                    }
                }
                break;

            case "data.len":
                field.AssertShowDecimal(httpDatagram.Length - _data.Length / 2);
                break;

            case "http.host":
            case "http.user_agent":
            case "http.accept":
            case "http.accept_language":
            case "http.accept_encoding":
            case "http.connection":
            case "http.cookie":
            case "http.cache_control":
            case "http.content_encoding":
            case "http.date":
            case "http.referer":
            case "http.last_modified":
            case "http.server":
            case "http.set_cookie":
            case "http.location":
                _data.Append(field.Value());
                httpFieldName = field.Name().Substring(5).Replace('_', '-');
                HttpField httpField = httpDatagram.Header[httpFieldName];
                if (!field.Value().EndsWith("0d0a"))
                {
                    Assert.IsNull(httpField);
                }
                else
                {
                    string fieldValue         = field.Show().Replace("\\\"", "\"");
                    string expectedFieldValue = httpField.ValueString;
                    Assert.IsTrue(expectedFieldValue.Contains(fieldValue),
                                  string.Format("{0} <{1}> doesn't contain <{2}>", field.Name(), expectedFieldValue, fieldValue));
                }
                break;

            case "http.content_length_header":
                _data.Append(field.Value());
                if (!IsBadHttp(httpDatagram))
                {
                    if (!field.Value().EndsWith("0d0a"))
                    {
                        Assert.IsNull(httpDatagram.Header.ContentLength);
                    }
                    else
                    {
                        field.AssertShowDecimal(httpDatagram.Header.ContentLength.ContentLength.Value);
                    }
                }
                break;

            case "http.content_type":
                _data.Append(field.Value());
                string[] mediaType = fieldShow.Split(new[] { ';', ' ', '/' }, StringSplitOptions.RemoveEmptyEntries);
                if (!IsBadHttp(httpDatagram))
                {
                    if (!field.Value().EndsWith("0d0a"))
                    {
                        Assert.IsNull(httpDatagram.Header.ContentType);
                    }
                    else
                    {
                        Assert.AreEqual(httpDatagram.Header.ContentType.MediaType, mediaType[0]);
                        Assert.AreEqual(httpDatagram.Header.ContentType.MediaSubtype, mediaType[1]);
                        int fieldShowParametersStart = fieldShow.IndexOf(';');
                        if (fieldShowParametersStart == -1)
                        {
                            Assert.IsFalse(httpDatagram.Header.ContentType.Parameters.Any());
                        }
                        else
                        {
                            string expected =
                                httpDatagram.Header.ContentType.Parameters.Select(pair => pair.Key + '=' + pair.Value.ToWiresharkLiteral()).
                                SequenceToString(';');
                            Assert.AreEqual(expected, fieldShow.Substring(fieldShowParametersStart + 1));
                        }
                    }
                }
                break;

            case "http.request.line":
            case "http.response.line":
                if (_data.ToString().EndsWith(field.Value()))
                {
                    break;
                }
                {
                    _data.Append(field.Value());
                }
                break;

            case "http.transfer_encoding":
                if (!IsBadHttp(httpDatagram))
                {
                    Assert.AreEqual(fieldShow.ToWiresharkLowerLiteral(),
                                    httpDatagram.Header.TransferEncoding.TransferCodings.SequenceToString(',').ToLowerInvariant().ToWiresharkLiteral());
                }
                break;

            case "http.request.full_uri":
                // TODO: Uncomment when https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=10681 is fixed.
                // Assert.AreEqual(fieldShow, ("http://" + httpDatagram.Header["Host"].ValueString + ((HttpRequestDatagram)httpDatagram).Uri).ToWiresharkLiteral());
                break;

            default:
                throw new InvalidOperationException("Invalid HTTP field " + field.Name());
            }

            return(true);
        }