Exemplo n.º 1
0
        private void ParseLocations(HttpDatagram dgram)
        {
            ClearLocations();

            string location = dgram.Headers.Get("Location");

            if (!String.IsNullOrEmpty(location))
            {
                AddLocation(location);
            }

            string [] als = dgram.Headers.GetValues("AL");
            if (als != null)
            {
                foreach (string al in als)
                {
                    AddLocation(al);
                }
            }

            if (LocationCount == 0)
            {
                throw new ApplicationException("No Location/AL found in header");
            }
        }
Exemplo n.º 2
0
        private static void TestHttpRequest(string httpString, string expectedMethodString = null, string expectedUri = null, HttpVersion expectedVersion = null, HttpHeader expectedHeader = null, string expectedBodyString = null)
        {
            Datagram          expectedBody   = expectedBodyString == null ? null : new Datagram(Encoding.ASCII.GetBytes(expectedBodyString));
            HttpRequestMethod expectedMethod = expectedMethodString == null ? null : new HttpRequestMethod(expectedMethodString);

            Packet packet = BuildPacket(httpString);

            // HTTP
            HttpDatagram http = packet.Ethernet.IpV4.Tcp.Http;

            Assert.IsTrue(http.IsRequest, "IsRequest " + httpString);
            Assert.IsFalse(http.IsResponse, "IsResponse " + httpString);
            Assert.AreEqual(expectedVersion, http.Version, "Version " + httpString);
            Assert.AreEqual(expectedHeader, http.Header, "Header " + httpString);
            if (expectedHeader != null)
            {
                Assert.AreEqual(expectedHeader.ToString(), http.Header.ToString(), "Header " + httpString);
            }

            HttpRequestDatagram request = (HttpRequestDatagram)http;

            Assert.AreEqual(expectedMethod, request.Method, "Method " + httpString);
            Assert.AreEqual(expectedUri, request.Uri, "Uri " + httpString);
            Assert.AreEqual(expectedBody, request.Body, "Body " + httpString);
        }
Exemplo n.º 3
0
 private void PrintHttp(PPacket ppacket)
 {
     HttpDatagram http = ppacket.Packet.Ethernet.IpV4.Tcp.Http;
     //ReadOnlyCollection<HttpDatagram> httpCollection = ppacket.Packet.Ethernet.IpV4.Tcp.HttpCollection;
     WriteTitle("[http]");
     WriteValues(0, "version", http.Version != null ? http.Version.ToString() : "null");
     WriteValues(0, "is request", http.IsRequest);
     WriteValues(0, "is response", http.IsResponse);
     WriteValues(0, "header", http.Header != null ? http.Header.ToString() : "null");
 }
Exemplo n.º 4
0
        private static void CompareHttpFirstLine(XElement httpFirstLineElement, HttpDatagram httpDatagram)
        {
            foreach (var field in httpFirstLineElement.Fields())
            {
                field.AssertNoFields();
                switch (field.Name())
                {
                case "http.request.method":
                    Assert.IsTrue(httpDatagram.IsRequest, field.Name() + " IsRequest");
                    field.AssertShow(((HttpRequestDatagram)httpDatagram).Method.Method);
                    break;

                case "http.request.uri":
                    Assert.IsTrue(httpDatagram.IsRequest, field.Name() + " IsRequest");
                    field.AssertShow(((HttpRequestDatagram)httpDatagram).Uri.ToWiresharkLiteral());
                    break;

                case "http.request.version":
                    if (httpDatagram.Version == null)
                    {
                        if (field.Show() != string.Empty)
                        {
                            Assert.IsTrue(field.Show().Contains(" ") || field.Show().Length < 8);
                        }
                    }
                    else
                    {
                        field.AssertShow(httpDatagram.Version.ToString());
                    }
                    break;

                case "http.response.code":
                    Assert.IsTrue(httpDatagram.IsResponse, field.Name() + " IsResponse");
                    field.AssertShowDecimal(IsBadHttp(httpDatagram) ? 0 : ((HttpResponseDatagram)httpDatagram).StatusCode.Value);
                    break;

                case "http.response.phrase":
                    Datagram reasonPhrase = ((HttpResponseDatagram)httpDatagram).ReasonPhrase;
                    if (reasonPhrase == null)
                    {
                        Assert.IsTrue(IsBadHttp(httpDatagram));
                    }
                    else
                    {
                        field.AssertValue(reasonPhrase);
                    }
                    break;

                default:
                    throw new InvalidOperationException("Invalid HTTP first line field " + field.Name());
                }
            }
        }
Exemplo n.º 5
0
        public void HandlePacket(IPacketProducer source, Packet packet)
        {
            HttpDatagram http = packet.Ethernet.IpV4.Tcp.Http;

            if (http.IsValid && http.IsRequest)
            {
                var req = (HttpRequestDatagram)http;
                if (req.Method?.KnownMethod == HttpRequestKnownMethod.Get)
                {
                    // Compulsory fields for establishing a WebSocket connection
                    string host                = null;
                    string upgrade             = null;
                    string connection          = null;
                    string secWebsocketKey     = null;
                    string secWebsocketVersion = null;

                    foreach (HttpField field in req.Header)
                    {
                        if (field.Name.Equals("Host", StringComparison.OrdinalIgnoreCase))
                        {
                            host = field.ValueString;
                        }
                        if (field.Name.Equals("Upgrade", StringComparison.OrdinalIgnoreCase))
                        {
                            upgrade = field.ValueString;
                        }
                        if (field.Name.Equals("Connection", StringComparison.OrdinalIgnoreCase))
                        {
                            connection = field.ValueString;
                        }
                        if (field.Name.Equals("Sec-WebSocket-Key", StringComparison.OrdinalIgnoreCase))
                        {
                            secWebsocketKey = field.ValueString;
                        }
                        if (field.Name.Equals("Sec-WebSocket-Version", StringComparison.OrdinalIgnoreCase))
                        {
                            secWebsocketVersion = field.ValueString;
                        }
                        //Console.WriteLine($"{field.Name}: {field.ValueString}");
                    }
                    if (host != null && upgrade != null && connection != null && secWebsocketKey != null && secWebsocketVersion != null)
                    {
                        Console.WriteLine("Starting Recording");
                        var recorder = new WebSocketRecorder(packet.Ethernet.IpV4);
                        recorder.HandlePacket(source, packet);
                        source.AddConsumer(recorder);
                    }
                    //WriteLine($"Http Get Detected {host} {upgrade} {connection} {secWebsocketKey} {secWebsocketVersion}");
                }
            }
        }
Exemplo n.º 6
0
        private void ParseExpiration(HttpDatagram dgram)
        {
            // Prefer the "Cache-Control: max-age=SECONDS" directive
            string cc_max_age = dgram.Headers.Get("Cache-Control");

            if (!String.IsNullOrEmpty(cc_max_age))
            {
                if (cc_max_age_regex == null)
                {
                    cc_max_age_regex = new Regex(@"max-age\s*=\s*([0-9]+)", RegexOptions.IgnoreCase);
                }

                Match match = cc_max_age_regex.Match(cc_max_age);
                if (match.Success && match.Groups.Count == 2)
                {
                    ushort expire = 0;
                    if (UInt16.TryParse(match.Groups[1].Value, out expire))
                    {
                        Expiration = DateTime.Now + TimeSpan.FromSeconds(expire);
                        return;
                    }
                }
            }

            // Fall back to possible Expires header
            string expires = dgram.Headers.Get("Expires");

            if (String.IsNullOrEmpty(expires))
            {
                DateTime expire_date;
                if (DateTime.TryParse(expires, out expire_date))
                {
                    DateTime now = DateTime.Now;
                    if (expire_date <= now || expire_date >= now.AddYears(1))
                    {
                        Expiration = expire_date;
                        return;
                    }
                }
            }

            if (Client.StrictProtocol)
            {
                throw new ApplicationException("Service does not specifiy a cache expiration");
            }

            // Fall back to the default expiration value
            Expiration = DateTime.Now + TimeSpan.FromSeconds(Protocol.DefaultMaxAge);
        }
Exemplo n.º 7
0
        internal void Update(HttpDatagram dgram, bool isGena)
        {
            if (isGena)
            {
                ServiceType = dgram.Headers.Get("NT");
                if (Client.StrictProtocol && String.IsNullOrEmpty(dgram.Headers.Get("Host")))
                {
                    throw new ApplicationException("Service did not send Host header");
                }
            }
            else
            {
                ServiceType = dgram.Headers.Get("ST");
                if (Client.StrictProtocol && dgram.Headers.Get("Ext") == null)
                {
                    throw new ApplicationException("Service did not send an Ext header " +
                                                   "acknowledging 'Man: \"ssdp:discover\"' in request");
                }
            }

            if (String.IsNullOrEmpty(ServiceType))
            {
                throw new ApplicationException(String.Format("Service did not send {0} header",
                                                             isGena ? "NT" : "ST"));
            }

            Usn = dgram.Headers.Get("USN");
            if (String.IsNullOrEmpty(Usn))
            {
                throw new ApplicationException("Service did not send USN header");
            }

            if (Client.StrictProtocol)
            {
                if (String.IsNullOrEmpty(dgram.Headers.Get("Server")))
                {
                    throw new ApplicationException("Service did not send Server header");
                }

                if (String.IsNullOrEmpty(dgram.Headers.Get("Server")))
                {
                    throw new ApplicationException("Service did not send Server header");
                }
            }

            ParseExpiration(dgram);
            ParseLocations(dgram);
        }
Exemplo n.º 8
0
        // Callback function invoked by Pcap.Net for ps4 tcp messages
        private void PacketHandlerTcp(Packet packet)
        {
            IpV4Datagram ip       = packet.Ethernet.IpV4;
            IpV4Protocol protocol = ip.Protocol;

            if (protocol == IpV4Protocol.Tcp)
            {
                TcpDatagram  tcpDatagram  = ip.Tcp;
                HttpDatagram httpDatagram = tcpDatagram.Http;
                if (httpDatagram.Length > 0 && httpDatagram.Header != null)
                {
                    string httpPacket = httpDatagram.Decode(Encoding.UTF8);
                    if (httpPacket.StartsWith("GET /sce/rp/session HTTP/1.1\r\n"))
                    {
                        Dictionary <string, string> header = HttpUtils.SplitHttpResponse(httpPacket);
                        header.TryGetValue("RP-Registkey", out var registKey);
                        this.textBoxPcapLogOutput.Invoke(new MethodInvoker(() => AppendLogOutputToPcapLogTextBox("RP-Registkey: " + registKey)));

                        _livePcapContext.LivePcapState = LivePcapState.SESSION_REQUEST;
                        _livePcapContext.Session       = null;
                    }
                    else if (httpDatagram.IsResponse && httpPacket.StartsWith("HTTP/1.1 200 OK\r\n") && _livePcapContext.LivePcapState == LivePcapState.SESSION_REQUEST)
                    {
                        Dictionary <string, string> header = HttpUtils.SplitHttpResponse(httpPacket);
                        header.TryGetValue("RP-Nonce", out var rpNonce);
                        if (rpNonce == null)
                        {
                            return;
                        }

                        byte[] rpKeyBuffer    = HexUtil.Unhexlify(_settingManager.GetRemotePlayData().RemotePlay.RpKey);
                        byte[] rpNonceDecoded = Convert.FromBase64String(rpNonce);

                        this.textBoxPcapLogOutput.Invoke(new MethodInvoker(() => AppendLogOutputToPcapLogTextBox("RP-Nonce from \"/sce/rp/session\" response: " + HexUtil.Hexlify(rpNonceDecoded))));

                        string controlAesKey = HexUtil.Hexlify(CryptoService.GetSessionAesKeyForControl(rpKeyBuffer, rpNonceDecoded));
                        string controlNonce  = HexUtil.Hexlify(CryptoService.GetSessionNonceValueForControl(rpNonceDecoded));
                        this.textBoxPcapLogOutput.Invoke(new MethodInvoker(() => AppendLogOutputToPcapLogTextBox("!!! Control AES Key: " + controlAesKey)));
                        this.textBoxPcapLogOutput.Invoke(new MethodInvoker(() => AppendLogOutputToPcapLogTextBox("!!! Control AES Nonce: " + controlNonce + Environment.NewLine)));
                        _livePcapContext.LivePcapState = LivePcapState.SESSION_RESPONSE;
                        _livePcapContext.Session       = CryptoService.GetSessionForControl(rpKeyBuffer, rpNonceDecoded);
                    }
                }
            }
        }
Exemplo n.º 9
0
        internal override bool OnAsyncResultReceived(AsyncReceiveBuffer result)
        {
            try {
                HttpDatagram dgram = HttpDatagram.Parse(result.Buffer);
                if (dgram == null)
                {
                    return(true);
                }

                try {
                    client.ServiceCache.Add(new BrowseService(dgram, false));
                } catch (Exception e) {
                    Log.Exception("Invalid browse response", e);
                }
            } catch (Exception e) {
                Log.Exception("Invalid HTTPU datagram", e);
            }

            return(true);
        }
Exemplo n.º 10
0
        private static bool IsBadHttp(HttpDatagram httpDatagram)
        {
            if (httpDatagram.IsResponse)
            {
                HttpResponseDatagram httpResponseDatagram = (HttpResponseDatagram)httpDatagram;
                if (httpResponseDatagram.StatusCode == null)
                {
                    Assert.IsNull(httpResponseDatagram.Header);
                    return(true);
                }
            }
            else
            {
                HttpRequestDatagram httpRequestDatagram = (HttpRequestDatagram)httpDatagram;
                if (httpRequestDatagram.Version == null)
                {
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 11
0
        private static void TestHttpResponse(string httpString, HttpVersion expectedVersion = null, uint?expectedStatusCode = null, string expectedReasonPhrase = null, HttpHeader expectedHeader = null, string expectedBodyString = null)
        {
            Datagram expectedBody = expectedBodyString == null ? null : new Datagram(Encoding.ASCII.GetBytes(expectedBodyString));

            Packet packet = BuildPacket(httpString);

            // HTTP
            HttpDatagram http = packet.Ethernet.IpV4.Tcp.Http;

            Assert.IsFalse(http.IsRequest, "IsRequest " + httpString);
            Assert.IsTrue(http.IsResponse, "IsResponse " + httpString);
            Assert.AreEqual(expectedVersion, http.Version, "Version " + httpString);
            Assert.AreEqual(expectedHeader, http.Header, "Header " + httpString);
            if (expectedHeader != null)
            {
                Assert.IsNotNull(http.Header.ToString());
            }

            HttpResponseDatagram response = (HttpResponseDatagram)http;

            Assert.AreEqual(expectedStatusCode, response.StatusCode, "StatusCode " + httpString);
            Assert.AreEqual(expectedReasonPhrase == null ? null : new Datagram(Encoding.ASCII.GetBytes(expectedReasonPhrase)), response.ReasonPhrase, "ReasonPhrase " + httpString);
            Assert.AreEqual(expectedBody, response.Body, "Body " + httpString);
        }
Exemplo n.º 12
0
        private void PacketHandler(Packet packet)
        {
            this.count = ""; this.time = ""; this.source = ""; this.destination = ""; this.protocol = ""; this.length = "";


            paqueter = packet;

            EthernetDatagram eth = packet.Ethernet;
            IpV4Datagram     ip  = packet.Ethernet.IpV4;
            TcpDatagram      tcp = ip.Tcp;
            UdpDatagram      udp = ip.Udp;


            HttpDatagram httpPacket = null;



            if (ip.Protocol.ToString().Equals("Tcp"))
            {
                count            = packet.Count.ToString();
                time             = packet.Timestamp.ToString();
                this.source      = ip.Source.ToString();
                this.destination = ip.Destination.ToString();
                length           = eth.Length.ToString();
                protocol         = ip.Protocol.ToString();
            }
            else
            {
                if ((ip.Protocol.ToString().Equals("Udp")))
                {
                    count            = packet.Count.ToString();
                    time             = packet.Timestamp.ToString();
                    this.source      = ip.Source.ToString();
                    this.destination = ip.Destination.ToString();
                    length           = eth.Length.ToString();
                    protocol         = ip.Protocol.ToString();
                }
            }

            if (ip.Protocol.ToString().Equals("Tcp") && (save.Checked))
            {
                int _source      = tcp.SourcePort;
                int _destination = tcp.DestinationPort;

                if (tcp.PayloadLength != 0)
                {
                    payload = new byte[tcp.PayloadLength];
                    tcp.Payload.ToMemoryStream().Read(payload, 0, tcp.PayloadLength);
                    if (_destination == 80)
                    {
                        Packet1 packet1 = new Packet1();
                        int     i       = Array.IndexOf(payload, (byte)32, 6);
                        byte[]  t       = new byte[i - 5];
                        Array.Copy(payload, 5, t, 0, i - 5);
                        packet1.Name = System.Text.ASCIIEncoding.ASCII.GetString(t);

                        if (!packets.ContainsKey(_source))
                        {
                            packets.Add(_source, packet1);
                        }
                    }
                    else
                    if (_source == 80)
                    {
                        if (packets.ContainsKey(_destination))
                        {
                            Packet1 packet1 = packets[_destination];
                            if (packet1.Data == null)
                            {
                                if ((httpPacket.Header != null) && (httpPacket.Header.ContentLength != null))
                                {
                                    packet1.Data = new byte[(uint)httpPacket.Header.ContentLength.ContentLength];
                                    Array.Copy(httpPacket.Body.ToMemoryStream().ToArray(), packet1.Data, httpPacket.Body.Length);
                                    packet1.Order       = (uint)(tcp.SequenceNumber + payload.Length - httpPacket.Body.Length);
                                    packet1.Data_Length = httpPacket.Body.Length;
                                    for (int i = 0; i < packet1.TempPackets.Count; i++)
                                    {
                                        Temp tempPacket = packet1.TempPackets[i];
                                        Array.Copy(tempPacket.data, 0, packet1.Data, tempPacket.tempSeqNo - packet1.Order, tempPacket.data.Length);
                                        packet1.Data_Length += tempPacket.data.Length;
                                    }
                                }
                                else
                                {
                                    Temp tempPacket = new Temp();
                                    tempPacket.tempSeqNo = (uint)tcp.SequenceNumber;
                                    tempPacket.data      = new byte[payload.Length];
                                    Array.Copy(payload, tempPacket.data, payload.Length);
                                    packet1.TempPackets.Add(tempPacket);
                                }
                            }
                            else if (packet1.Data_Length != packet1.Data.Length)
                            {
                                Array.Copy(payload, 0, packet1.Data, tcp.SequenceNumber - packet1.Order, payload.Length);

                                packet1.Data_Length += payload.Length;
                            }

                            if (packet1.Data != null)
                            {
                                if (packet1.Data_Length == packet1.Data.Length)
                                {
                                    using (BinaryWriter writer = new BinaryWriter(File.Open(fullpath + Directory.CreateDirectory(Path.GetFileName(packet1.Name)), FileMode.Create)))
                                    {
                                        writer.Write(packet1.Data);
                                    }

                                    packets.Remove(_destination);
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 13
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);
        }
Exemplo n.º 14
0
        protected override bool Ignore(Datagram datagram)
        {
            HttpDatagram httpDatagram = (HttpDatagram)datagram;

            return(httpDatagram.Header != null && httpDatagram.Header.ContentLength != null && httpDatagram.Header.TransferEncoding != null);
        }
Exemplo n.º 15
0
 internal BrowseService(HttpDatagram dgram, IPEndPoint serverEndpoint, bool isGena)
 {
     SourceAddress = serverEndpoint.Address.ToString();
     Update(dgram, isGena);
 }
Exemplo n.º 16
0
        private void PacketHandler(Packet packet)
        {
            this.count  = String.Empty; this.time = String.Empty; this.source = String.Empty; this.destination = String.Empty; this.s_port = String.Empty; this.d_port = String.Empty; this.protocol = String.Empty; this.length = String.Empty;
            this.tcpack = String.Empty; this.tcpsec = String.Empty; this.tcpnsec = String.Empty; this.tcpsrc = String.Empty; this.tcpdes = String.Empty; this.udpscr = String.Empty;
            this.udpdes = String.Empty; this.httpheader = String.Empty; this.httpver = String.Empty; this.httpayload = String.Empty; this.reqres = String.Empty; this.httpbody = String.Empty; payload = String.Empty;

            IpV4Datagram ip   = packet.Ethernet.IpV4;
            TcpDatagram  tcp  = ip.Tcp;
            UdpDatagram  udp  = ip.Udp;
            HttpDatagram http = null;

            try
            {
                if (ip.Protocol.ToString().Equals("Tcp"))
                {
                    http = tcp.Http;

                    if (http.Header != null)
                    {
                        protocol   = "Http";
                        httpheader = http.Header.ToString();
                        httpver    = http.Version.ToString();
                        httpayload = http.Length.ToString();
                        httpbody   = http.Body.ToString();

                        if (http.IsRequest)
                        {
                            reqres = "Request";
                        }
                        else
                        {
                            reqres = "Response";
                        }
                    }

                    else
                    {
                        protocol = ip.Protocol.ToString();
                        s_port   = tcp.SourcePort.ToString();
                        d_port   = tcp.DestinationPort.ToString();
                        tcpack   = tcp.AcknowledgmentNumber.ToString();
                        tcpsec   = tcp.SequenceNumber.ToString();
                        tcpnsec  = tcp.NextSequenceNumber.ToString();
                        payload  = ", data:" + tcp.Payload.Length.ToString();
                    }
                }
                else if ((ip.Protocol.ToString().Equals("Udp")))
                {
                    protocol = ip.Protocol.ToString();
                    s_port   = udp.SourcePort.ToString();
                    d_port   = udp.DestinationPort.ToString();
                    payload  = ", data:" + udp.Payload.Length.ToString();
                }
                else
                {
                    protocol = ip.Protocol.ToString();
                }
                count            = packet.Count.ToString();
                time             = packet.Timestamp.ToString();
                this.source      = ip.Source.ToString();
                this.destination = ip.Destination.ToString();
                length           = ip.Length.ToString();
                payload          = ", data:" + ip.Payload.Length.ToString();
            }
            catch { }
        }
Exemplo n.º 17
0
        public void RandomHttpTest()
        {
            int seed = new Random().Next();

            Console.WriteLine("Seed: " + seed);
            Random random = new Random(seed);

            for (int i = 0; i != 200; ++i)
            {
                EthernetLayer ethernetLayer = random.NextEthernetLayer(EthernetType.None);
                IpV4Layer     ipV4Layer     = random.NextIpV4Layer(null);
                ipV4Layer.HeaderChecksum = null;
                Layer    ipLayer  = random.NextBool() ? (Layer)ipV4Layer : random.NextIpV6Layer(true);
                TcpLayer tcpLayer = random.NextTcpLayer();
                tcpLayer.Checksum = null;
                HttpLayer httpLayer = random.NextHttpLayer();

                Packet packet = PacketBuilder.Build(DateTime.Now, ethernetLayer, ipLayer, tcpLayer, httpLayer);
                Assert.IsTrue(packet.IsValid, "IsValid");

                HttpDatagram httpDatagram = packet.Ethernet.Ip.Tcp.Http;
                Assert.AreEqual(httpLayer.Version, httpDatagram.Version);
                if (httpLayer.Version != null)
                {
                    Assert.AreEqual(httpLayer.Version.GetHashCode(), httpDatagram.Version.GetHashCode());
                }
                if (httpLayer is HttpRequestLayer)
                {
                    Assert.IsTrue(httpDatagram.IsRequest);
                    Assert.IsTrue(httpLayer.IsRequest);
                    Assert.IsFalse(httpDatagram.IsResponse);
                    Assert.IsFalse(httpLayer.IsResponse);

                    HttpRequestLayer    httpRequestLayer    = (HttpRequestLayer)httpLayer;
                    HttpRequestDatagram httpRequestDatagram = (HttpRequestDatagram)httpDatagram;
                    Assert.AreEqual(httpRequestLayer.Method, httpRequestDatagram.Method);
                    if (httpRequestLayer.Method != null)
                    {
                        Assert.AreEqual(httpRequestLayer.Method.GetHashCode(), httpRequestDatagram.Method.GetHashCode());
                        Assert.AreEqual(httpRequestLayer.Method.KnownMethod, httpRequestDatagram.Method.KnownMethod);
                    }
                    Assert.AreEqual(httpRequestLayer.Uri, httpRequestDatagram.Uri);
                }
                else
                {
                    Assert.IsFalse(httpDatagram.IsRequest);
                    Assert.IsFalse(httpLayer.IsRequest);
                    Assert.IsTrue(httpDatagram.IsResponse);
                    Assert.IsTrue(httpLayer.IsResponse);

                    HttpResponseLayer    httpResponseLayer    = (HttpResponseLayer)httpLayer;
                    HttpResponseDatagram httpResponseDatagram = (HttpResponseDatagram)httpDatagram;
                    Assert.AreEqual(httpResponseLayer.StatusCode, httpResponseDatagram.StatusCode);
                    Assert.AreEqual(httpResponseLayer.ReasonPhrase, httpResponseDatagram.ReasonPhrase);
                }
                Assert.AreEqual(httpLayer.Header, httpDatagram.Header);
                if (httpLayer.Header != null)
                {
                    Assert.AreEqual(httpLayer.Header.GetHashCode(), httpDatagram.Header.GetHashCode());
                    if (!httpDatagram.IsRequest || ((HttpRequestDatagram)httpDatagram).Uri != "")
                    {
                        Assert.IsTrue(httpDatagram.IsValidStart, "IsValidStart");
                    }

                    foreach (var field in httpLayer.Header)
                    {
                        Assert.IsFalse(field.Equals("abc"));
                    }
                    foreach (var field in (IEnumerable)httpLayer.Header)
                    {
                        Assert.IsFalse(field.Equals("abc"));
                    }

                    MoreAssert.AreSequenceEqual(httpLayer.Header.Select(field => field.GetHashCode()), httpDatagram.Header.Select(field => field.GetHashCode()));

                    if (httpLayer.Header.ContentType != null)
                    {
                        var parameters = httpLayer.Header.ContentType.Parameters;
                        Assert.IsNotNull(((IEnumerable)parameters).GetEnumerator());
                        Assert.AreEqual <object>(parameters, httpDatagram.Header.ContentType.Parameters);
                        Assert.AreEqual(parameters.GetHashCode(), httpDatagram.Header.ContentType.Parameters.GetHashCode());
                        Assert.AreEqual(parameters.Count, httpDatagram.Header.ContentType.Parameters.Count);
                        int maxParameterNameLength = parameters.Any() ? parameters.Max(pair => pair.Key.Length) : 0;
                        Assert.IsNull(parameters[new string('a', maxParameterNameLength + 1)]);
                    }
                }
                Assert.AreEqual(httpLayer.Body, httpDatagram.Body);
                Assert.AreEqual(httpLayer, httpDatagram.ExtractLayer(), "HTTP Layer");
                Assert.AreEqual(httpLayer.Length, httpDatagram.Length);
            }
        }
Exemplo n.º 18
0
        //ham xu ly offlive
        private void DispatcherHandler(Packet packet)
        {
            this.count = ""; this.time = ""; this.source = ""; this.destination = ""; this.protocol = ""; this.length = "";

            this.tcpack = ""; this.tcpsec = ""; this.tcpnsec = ""; this.tcpsrc = ""; this.tcpdes = ""; this.udpscr = "";

            this.udpdes = ""; this.httpheader = ""; this.httpver = ""; this.httplen = ""; this.reqres = ""; this.httpbody = "";

            this.infor = "";
            IpV4Datagram ip         = packet.Ethernet.IpV4;
            TcpDatagram  tcp        = ip.Tcp;
            UdpDatagram  udp        = ip.Udp;
            HttpDatagram httpPacket = null;
            IcmpDatagram icmp       = ip.Icmp;

            if (ip.Protocol.ToString().Equals("Tcp"))
            {
                httpPacket = tcp.Http;//Initialize http variable only if the packet was tcp

                if ((httpPacket.Header != null) /* && (!_tcp.Checked)*/)
                {
                    protocol         = "Http";
                    httpheader       = httpPacket.Header.ToString();
                    count            = packet.Count.ToString();
                    time             = packet.Timestamp.ToString();
                    this.source      = ip.Source.ToString();
                    this.destination = ip.Destination.ToString();
                    length           = ip.Length.ToString();
                    httpver          = httpPacket.Version.ToString();
                    httplen          = httpPacket.Length.ToString();
                    if ((httpPacket.Body != null) /* && (!_tcp.Checked)*/)
                    {
                        httpbody = httpPacket.Body.ToString();
                    }
                    if (httpPacket.IsRequest)
                    {
                        reqres = "Request";
                    }
                    else
                    {
                        reqres = "Response";
                    }
                }

                else
                {
                    count            = packet.Count.ToString();
                    time             = packet.Timestamp.ToString();
                    this.source      = ip.Source.ToString();
                    this.destination = ip.Destination.ToString();
                    length           = ip.Length.ToString();
                    protocol         = ip.Protocol.ToString();
                    tcpsrc           = tcp.SourcePort.ToString();
                    tcpdes           = tcp.DestinationPort.ToString();
                    tcpack           = tcp.AcknowledgmentNumber.ToString();
                    tcpsec           = tcp.SequenceNumber.ToString();
                    tcpnsec          = tcp.NextSequenceNumber.ToString();
                    tcpwin           = tcp.Window.ToString();
                    tcplen           = tcp.Length.ToString();
                    tcp.Length.ToString();
                    infor = tcpsrc + "->" + tcpdes + " Seq=" + tcpsec + " win=" + tcpwin + " Ack= " + tcpack + " LEN= " + tcplen;
                }
            }
            else
            {
                if (ip.Protocol.ToString().Equals("Udp"))
                {
                    if (udp.DestinationPort.ToString().Equals(53))
                    {
                        protocol = "dns";
                    }
                    else
                    {
                        count            = packet.Count.ToString();
                        time             = packet.Timestamp.ToString();
                        this.source      = ip.Source.ToString();
                        this.destination = ip.Destination.ToString();
                        length           = ip.Length.ToString();
                        protocol         = ip.Protocol.ToString();
                        udpscr           = udp.SourcePort.ToString();
                        udpdes           = udp.DestinationPort.ToString();
                    }
                }

                else
                {
                    count            = packet.Count.ToString();
                    time             = packet.Timestamp.ToString();
                    this.source      = ip.Source.ToString();
                    this.destination = ip.Destination.ToString();
                    length           = ip.Length.ToString();
                    protocol         = ip.Protocol.ToString();
                }
            }

            if (!count.Equals(""))
            {
                no++;
                ListViewItem item = new ListViewItem(no.ToString());
                item.SubItems.Add(time);
                item.SubItems.Add(source);
                item.SubItems.Add(destination);
                item.SubItems.Add(protocol);
                item.SubItems.Add(length);
                item.SubItems.Add(infor);
                item.Tag = packet;
                SetText(item);
            }
        }
Exemplo n.º 19
0
        //public static string GetTcpStreamPacketString1(IndexedTcpConnection tcpConnection, PPacket ppacket, TcpDirection direction, bool printData)
        public static string GetTcpStreamPacketString1(PPacket ppacket, TcpDirection direction, bool printData)
        {
            IpV4Datagram ip     = ppacket.Ipv4;
            TcpDatagram  tcp    = ppacket.Tcp;
            string       saddr  = null;
            string       daddr  = null;
            string       mf     = null;
            string       offset = null;
            string       id     = null;

            if (ip != null)
            {
                saddr = ip.Source.ToString();
                daddr = ip.Destination.ToString();
                if (tcp != null)
                {
                    saddr += ":" + tcp.SourcePort.ToString();
                    daddr += ":" + tcp.DestinationPort.ToString();
                }
                //mf = ip.MoreFragment.ToString();
                mf     = (ip.Fragmentation.Options == IpV4FragmentationOptions.MoreFragments).ToString();
                offset = ip.Fragmentation.Offset.zToHex();
                id     = ip.Identification.zToHex();
            }
            StringBuilder sb = new StringBuilder();
            //direction
            string dir = null;

            //if (direction != null)
            //{
            if (direction == TcpDirection.SourceToDestination)
            {
                dir = "-->   ";
            }
            else
            {
                dir = "<--   ";
                string addr = saddr;
                saddr = daddr;
                daddr = addr;
            }
            //}
            //sb.Append(string.Format("{0,5}  {1,5}  {2,10:0.000000}  {3,-21}  {4}{5,-21} {6,-7}", packet.gGroupNumber, packet.PacketNumber, packet.RelativeTime.TotalSeconds, saddr, dir, daddr, packet.ProtocolCode));
            sb.Append(string.Format("{0,5}  {1,5}  {2,10:0.000000}  {3,-21}  {4}{5,-21} {6,-7}",
                                    ppacket.GetTcpConnection().Index, ppacket.PacketNumber, ppacket.RelativeTime.TotalSeconds, saddr, dir, daddr, ppacket.IpProtocolCode));
            string align = "";

            if (tcp != null)
            {
                string next_seq;
                if (tcp.PayloadLength > 0)
                {
                    next_seq = "0x" + (tcp.SequenceNumber + (uint)tcp.PayloadLength).zToHex();
                }
                else if (tcp.IsSynchronize)
                {
                    next_seq = "0x" + (tcp.SequenceNumber + 1).zToHex();
                }
                else
                {
                    next_seq = "          ";
                }
                string dataLength;
                if (tcp.PayloadLength > 0)
                {
                    dataLength = "0x" + ((ushort)tcp.PayloadLength).zToHex();
                }
                else
                {
                    dataLength = "      ";
                }
                string ack_seq;
                if (tcp.AcknowledgmentNumber != 0)
                {
                    ack_seq = "0x" + tcp.AcknowledgmentNumber.zToHex();
                }
                else
                {
                    ack_seq = "          ";
                }
                string urg_ptr = null;
                if (tcp.UrgentPointer != 0)
                {
                    urg_ptr = " 0x" + tcp.UrgentPointer.zToHex();
                }
                else
                {
                    align += "       ";
                }
                //TCPFlags(tcp)
                //tcp.GetFlagsString()
                sb.Append(string.Format("  {0,-20} {1} 0x{2} {3} {4} 0x{5}{6}", ppacket.GetTcpFlagsString(), dataLength, tcp.SequenceNumber.zToHex(), next_seq, ack_seq, tcp.Window.zToHex(), urg_ptr));
            }
            else
            {
                align += "                                                                                    ";
            }
            sb.Append(align + "   ");
            HttpDatagram http = tcp.Http;

            if (http != null)
            {
                sb.Append("http ");
                if (http.IsRequest)
                {
                    sb.Append("request");
                }
                else if (http.IsResponse)
                {
                    sb.Append("reply  ");
                }
                else
                {
                    sb.Append("????   ");
                }
                //sb.Append(http.Version.ToString());
            }
            else
            {
                sb.Append("                      ");
            }
            if (printData && tcp != null && tcp.PayloadLength > 0)
            {
                //sb.Append(align + "   ");
                //byte[] data = tcp.Payload;
                int i = 0;
                //int maxDataChar = 100;
                int maxDataChar = 50;
                foreach (byte b in tcp.Payload)
                {
                    if (++i > maxDataChar)
                    {
                        break;
                    }
                    sb.Append(" ");
                    sb.Append(b.zToHex());
                }
                sb.Append("  ");
                i = 0;
                foreach (byte b in tcp.Payload)
                {
                    if (++i > maxDataChar)
                    {
                        break;
                    }
                    if (b >= 32 && b <= 126)
                    {
                        sb.Append((char)b);
                    }
                    else
                    {
                        sb.Append('.');
                    }
                }
            }
            return(sb.ToString());
        }
Exemplo n.º 20
0
        private void PacketHandler(Packet packet)
        {
            this.count       = "";
            this.time        = "";
            this.source      = "";
            this.destination = "";
            this.protocol    = "";
            this.length      = "";

            this.tcpack    = "";
            this.tcpsec    = "";
            this.tcpnsec   = "";
            this.tcpsrc    = "";
            this.tcpdes    = "";
            this.tcpheader = "";

            this.udpscr = "";
            this.udpdes = "";


            IpV4Datagram ip        = packet.Ethernet.IpV4;
            TcpDatagram  tcp       = ip.Tcp;
            UdpDatagram  udp       = ip.Udp;
            HttpDatagram TcpPacket = null;


            if (ip.Protocol.ToString().Equals("Tcp"))
            {
                TcpPacket = tcp.Http;//Initialize http variable only if the packet was tcp

                if ((TcpPacket.Header != null) && (!_tcp.Checked))
                {
                    protocol         = "tcp";
                    tcppheader       = TcpPacket.Header.ToString();
                    count            = packet.Count.ToString();
                    time             = packet.Timestamp.ToString();
                    this.source      = ip.Source.ToString();
                    this.destination = ip.Destination.ToString();
                    length           = ip.Length.ToString();
                    httpver          = TcpPacket.Version.ToString();
                    httplen          = TcpPacket.Length.ToString();
                    httpbody         = TcpPacket.Body.ToString();

                    if (TcpPacket.IsRequest)
                    {
                        reqres = "Request";
                    }
                    else
                    {
                        reqres = "Response";
                    }
                }

                else
                {
                    count            = packet.Count.ToString();
                    time             = packet.Timestamp.ToString();
                    this.source      = ip.Source.ToString();
                    this.destination = ip.Destination.ToString();
                    length           = ip.Length.ToString();
                    protocol         = ip.Protocol.ToString();

                    tcpsrc  = tcp.SourcePort.ToString();
                    tcpdes  = tcp.DestinationPort.ToString();
                    tcpack  = tcp.AcknowledgmentNumber.ToString();
                    tcpsec  = tcp.SequenceNumber.ToString();
                    tcpnsec = tcp.NextSequenceNumber.ToString();
                }
            }
            else
            {
                if ((ip.Protocol.ToString().Equals("Udp")))
                {
                    count            = packet.Count.ToString();
                    time             = packet.Timestamp.ToString();
                    this.source      = ip.Source.ToString();
                    this.destination = ip.Destination.ToString();
                    length           = ip.Length.ToString();
                    protocol         = ip.Protocol.ToString();
                    udpscr           = udp.SourcePort.ToString();
                    udpdes           = udp.DestinationPort.ToString();
                }
                else
                {
                    count            = packet.Count.ToString();
                    time             = packet.Timestamp.ToString();
                    this.source      = ip.Source.ToString();
                    this.destination = ip.Destination.ToString();
                    length           = ip.Length.ToString();
                    protocol         = ip.Protocol.ToString();
                }
            }


            if (ip.Protocol.ToString().Equals("Tcp") && (save.Checked))
            {
                int _source      = tcp.SourcePort;
                int _destination = tcp.DestinationPort;

                if (tcp.PayloadLength != 0) //not syn or ack
                {
                    payload = new byte[tcp.PayloadLength];
                    tcp.Payload.ToMemoryStream().Read(payload, 0, tcp.PayloadLength); // read payload from 0 to length
                    if (_destination == 80)                                           // request from server
                    {
                        Packet1 packet1 = new Packet1();
                        int     i       = Array.IndexOf(payload, (byte)32, 6);
                        byte[]  t       = new byte[i - 5];
                        Array.Copy(payload, 5, t, 0, i - 5);
                        packet1.Name = System.Text.ASCIIEncoding.ASCII.GetString(t);

                        if (!packets.ContainsKey(_source))
                        {
                            packets.Add(_source, packet1);
                        }
                    }
                    else
                    if (_source == 80)
                    {
                        if (packets.ContainsKey(_destination))
                        {
                            Packet1 packet1 = packets[_destination];
                            if (packet1.Data == null)
                            {
                                if ((TcpPacket.Header != null) && (TcpPacket.Header.ContentLength != null))
                                {
                                    packet1.Data = new byte[(uint)TcpPacket.Header.ContentLength.ContentLength];
                                    Array.Copy(TcpPacket.Body.ToMemoryStream().ToArray(), packet1.Data, TcpPacket.Body.Length);
                                    packet1.Order       = (uint)(tcp.SequenceNumber + payload.Length - TcpPacket.Body.Length);
                                    packet1.Data_Length = TcpPacket.Body.Length;
                                    for (int i = 0; i < packet1.TempPackets.Count; i++)
                                    {
                                        Temp tempPacket = packet1.TempPackets[i];
                                        Array.Copy(tempPacket.data, 0, packet1.Data, tempPacket.tempSeqNo - packet1.Order, tempPacket.data.Length);
                                        packet1.Data_Length += tempPacket.data.Length;
                                    }
                                }
                                else
                                {
                                    Temp tempPacket = new Temp();
                                    tempPacket.tempSeqNo = (uint)tcp.SequenceNumber;
                                    tempPacket.data      = new byte[payload.Length];
                                    Array.Copy(payload, tempPacket.data, payload.Length);
                                    packet1.TempPackets.Add(tempPacket);
                                }
                            }
                            else if (packet1.Data_Length != packet1.Data.Length)
                            {
                                Array.Copy(payload, 0, packet1.Data, tcp.SequenceNumber - packet1.Order, payload.Length);

                                packet1.Data_Length += payload.Length;
                            }

                            if (packet1.Data != null)
                            {
                                if (packet1.Data_Length == packet1.Data.Length)
                                {
                                    using (BinaryWriter writer = new BinaryWriter(File.Open(@"E:\networks final\" + Directory.CreateDirectory(Path.GetFileName(packet1.Name)), FileMode.Create)))
                                    {
                                        writer.Write(packet1.Data);
                                    }

                                    packets.Remove(_destination);
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 21
0
        //hàm xử lý live
        private void PacketHandler(Packet packet)
        {
            this.count = ""; this.time = ""; this.source = ""; this.destination = ""; this.protocol = ""; this.length = "";

            this.tcpack = ""; this.tcpsec = ""; this.tcpnsec = ""; this.tcpsrc = ""; this.tcpdes = ""; this.udpscr = "";

            this.udpdes = ""; this.httpheader = ""; this.httpver = ""; this.httplen = ""; this.reqres = ""; this.httpbody = "";

            this.infor = "";
            if (no == 0)
            {
                InformationPacket(packet);
            }
            IpV4Datagram ip         = packet.Ethernet.IpV4;
            TcpDatagram  tcp        = ip.Tcp;
            UdpDatagram  udp        = ip.Udp;
            HttpDatagram httpPacket = null;
            IcmpDatagram icmp       = ip.Icmp;

            protocol = ip.Protocol.ToString();
            if (ip.Protocol.ToString().Equals("Tcp"))
            {
                httpPacket = tcp.Http;

                if ((httpPacket.Header != null))
                {
                    protocol         = "Http";
                    httpheader       = httpPacket.Header.ToString();
                    count            = packet.Count.ToString();
                    time             = packet.Timestamp.ToString();
                    this.source      = ip.Source.ToString();
                    this.destination = ip.Destination.ToString();
                    length           = ip.Length.ToString();
                    httpver          = httpPacket.Version.ToString();
                    httplen          = httpPacket.Length.ToString();
                    if ((httpPacket.Body != null) /* && (!_tcp.Checked)*/)
                    {
                        httpbody = httpPacket.Body.ToString();
                    }
                    if (httpPacket.IsRequest)
                    {
                        reqres = "Request";
                    }
                    else
                    {
                        reqres = "Response";
                    }
                }

                else
                {
                    count            = packet.Count.ToString();
                    time             = packet.Timestamp.ToString();
                    this.source      = ip.Source.ToString();
                    this.destination = ip.Destination.ToString();
                    length           = ip.Length.ToString();
                    protocol         = ip.Protocol.ToString();
                    tcpsrc           = tcp.SourcePort.ToString();
                    tcpdes           = tcp.DestinationPort.ToString();
                    tcpack           = tcp.AcknowledgmentNumber.ToString();
                    tcpsec           = tcp.SequenceNumber.ToString();
                    tcpnsec          = tcp.NextSequenceNumber.ToString();
                    tcpwin           = tcp.Window.ToString();
                    tcplen           = tcp.Length.ToString();
                    tcp.Length.ToString();
                    infor = tcpsrc + "->" + tcpdes + " Seq=" + tcpsec + " win=" + tcpwin + " Ack= " + tcpack + " LEN= " + tcplen;
                }
            }
            else
            {
                if (ip.Protocol.ToString().Equals("Udp"))
                {
                    if (udp.DestinationPort.ToString().Equals(53))
                    {
                        protocol = "dns";
                    }
                    else
                    {
                        count            = packet.Count.ToString();
                        time             = packet.Timestamp.ToString();
                        this.source      = ip.Source.ToString();
                        this.destination = ip.Destination.ToString();
                        length           = ip.Length.ToString();
                        protocol         = ip.Protocol.ToString();
                        udpscr           = udp.SourcePort.ToString();
                        udpdes           = udp.DestinationPort.ToString();
                    }
                }

                else
                {
                    count            = packet.Count.ToString();
                    time             = packet.Timestamp.ToString();
                    this.source      = ip.Source.ToString();
                    this.destination = ip.Destination.ToString();
                    length           = ip.Length.ToString();
                    protocol         = ip.Protocol.ToString();
                }
            }


            if (ip.Protocol.ToString().Equals("Tcp") /*&& (save.Checked)*/)
            {
                int _source      = tcp.SourcePort;
                int _destination = tcp.DestinationPort;

                if (tcp.PayloadLength != 0) //not syn or ack
                {
                    payload = new byte[tcp.PayloadLength];
                    tcp.Payload.ToMemoryStream().Read(payload, 0, tcp.PayloadLength); // read payload from 0 to length
                    if (_destination == 80)                                           // request from server
                    {
                        Packet1 packet1 = new Packet1();
                        if (payload.Count() > 1)
                        {
                            int    i = Array.IndexOf(payload, (byte)32, 6);
                            byte[] t = new byte[i - 5];
                            Array.Copy(payload, 5, t, 0, i - 5);
                            packet1.Name = System.Text.ASCIIEncoding.ASCII.GetString(t);

                            if (!packets.ContainsKey(_source))
                            {
                                packets.Add(_source, packet1);
                            }
                        }
                    }
                    else
                    if (_source == 80)
                    {
                        if (packets.ContainsKey(_destination))
                        {
                            Packet1 packet1 = packets[_destination];
                            if (packet1.Data == null)
                            {
                                if ((httpPacket.Header != null) && (httpPacket.Header.ContentLength != null))
                                {
                                    packet1.Data = new byte[(uint)httpPacket.Header.ContentLength.ContentLength];
                                    Array.Copy(httpPacket.Body.ToMemoryStream().ToArray(), packet1.Data, httpPacket.Body.Length);
                                    packet1.Order       = (uint)(tcp.SequenceNumber + payload.Length - httpPacket.Body.Length);
                                    packet1.Data_Length = httpPacket.Body.Length;
                                    for (int i = 0; i < packet1.TempPackets.Count; i++)
                                    {
                                        Temp tempPacket = packet1.TempPackets[i];
                                        Array.Copy(tempPacket.data, 0, packet1.Data, tempPacket.tempSeqNo - packet1.Order, tempPacket.data.Length);
                                        packet1.Data_Length += tempPacket.data.Length;
                                    }
                                }
                                else
                                {
                                    Temp tempPacket = new Temp();
                                    tempPacket.tempSeqNo = (uint)tcp.SequenceNumber;
                                    tempPacket.data      = new byte[payload.Length];
                                    Array.Copy(payload, tempPacket.data, payload.Length);
                                    packet1.TempPackets.Add(tempPacket);
                                }
                            }
                            else if (packet1.Data_Length != packet1.Data.Length)
                            {
                                Array.Copy(payload, 0, packet1.Data, tcp.SequenceNumber - packet1.Order, payload.Length);

                                packet1.Data_Length += payload.Length;
                            }

                            //if (packet1.Data != null)
                            //    if (packet1.Data_Length == packet1.Data.Length)
                            //    {

                            //        using (BinaryWriter writer = new BinaryWriter(File.Open(@"D:\captured\" + Directory.CreateDirectory(Path.GetFileName(packet1.Name)), FileMode.Create)))
                            //        {
                            //            writer.Write(packet1.Data);

                            //        }

                            //        packets.Remove(_destination);

                            //    }
                        }
                    }
                }
            }
            if (!count.Equals(""))
            {
                no++;
                ListViewItem item = new ListViewItem(no.ToString());
                item.SubItems.Add(time);
                item.SubItems.Add(source);
                item.SubItems.Add(destination);
                item.SubItems.Add(protocol);
                item.SubItems.Add(length);
                item.SubItems.Add(infor);
                item.Tag = packet;
                SetText(item);
            }
        }
Exemplo n.º 22
0
 internal BrowseService(HttpDatagram dgram, bool isGena)
 {
     Update(dgram, isGena);
 }