Просмотр http запросов приложения windows

Есть некое приложение на пк, по структуре грубо говоря как и сам сайт (прим. Steam), т.е. интерфейс, кнопки и всё т.п. взято с сайта, но отличается буквально пара кнопочек, которые есть только в десктопном приложении
Вот мне и нужно узнать что конкретно происходит после нажатия на эти кнопки, в радужном воображении где всё легко это представляется как обычные post/get запросы, которые можно разобрать прямо как в отслеживании трафика в хроме
После нажатия на кнопку в этом приложении открывается ссылка в браузере, хочется понять где эта ссылка генерируется
Fiddler/Charles будто бы пропускает почти всю основу что мне нужно узнать (показывают один запрос из самого приложения, который мне ничего не даёт, а следующим запросом уже сразу же идёт get на эту нужную ссылку, отсюда мне тоже брать нечего, какие-то соединительные запросы между ними должны быть это уж точно)
Wireshark я будто бы и не смог осилить и понять как правильно использовать. Сразу же миллион и миллион различных запросов сыпятся, поверхностно вижу только кучу ipшников и не знаю какие из этих всех мне нужны
Может нужно по-другому настроить Fiddler, либо можете подсказать как найти нужные запросы от приложения в Wireshark?


  • Вопрос задан

  • 2789 просмотров

There are times when you want to view the raw HTTP requests that are being sent from a client to
a server. This can, for example, be when you are developing an application that sends or receives
HTTP requests or are using a third-party tool to test HTTP-based APIs. When you’re writing code
that sends HTTP requests you can usually only guess what the actual raw HTTP request will look like.
When using tools such as SoapUI or Postman you’ll get a better notion of what the raw request will
look like. However, there are often extra headers and so on that gets added later by the respective
applications (such as Content-Length or User-Agent), that are not necessarily shown in the GUI itself.

This post gives a brief overview over how I usually view the raw HTTP requests in order to debug them.
Some methods are better than other in different circumstances, which is why I list several methods.

Fiddler

The easiest way to debug HTTP requests, in my opinion, is by using Fiddler. I’ve only used it for Windows,
so I don’t know how well it works for Linux and OS X. Fiddler can be downloaded from the official home
of Fiddler. You are required to type in an email and what you’re using Fiddler for, but this can be whatever
you like. You are not required to give them a valid email, you’ll get to download the software anyway.

Fiddler generally works out-of-the-box, but if it doesn’t you can try to look up in the documentation
on how to set it up. Fiddler works by setting up a proxy on port 8888. It will therefore sit between the
client and the server and listen to requests and responses, which it shows in a list. If you’re using a
tool such as SoapUI you might have to restart it after starting Fiddler. Otherwise it will not use the
Fiddler proxy. You might also have to restart the tool or any consoles after shutting down Fiddler, in
order to stop using the proxy.

To use Fiddler you just have to start it, assuming you have set up the client if that’s needed. It will
start listening to outgoing request and incoming responses. You can toggle the listening status with F12.
You generally only want to log while debugging. Otherwise the list will start filling up with a ton of
request. Here is a request I sent with SoapUI being listed in Fiddler:

Screenshot of Fiddler

We can see the request body under the Inspectors tab. To see the raw request use the Raw sub tab.

Fiddler is a fairly advanced tool, but easy to get into. You can write your own extensions in .NET (C#).
There are more info about that here.

netcat

netcat is a well-known network tool used for creating TCP and UDP connections. netcat
was originally written for Unix, but is now also available for Windows and OS X. Here I’ll use
ncat, which is a fork of netcat. You might have problems using netcat in corporate environments.
It’s often blocked for security reasons, as it can be used as a port scanner and for creating backdoors.

netcat can be used for many things, one one of them is to make it act as a server that listens to a given port.
That is done by running:

I’m now listening to port 1234 for anything that’s willing to send to it. netcat won’t respond to the
request unless you specifically make a response yourself (by writing something inside the console
window or by piping into netcat).

So if I point the client (in this case SoapUI) to http://localhost:1234 it will send the data to the server
netcat made. The text in the netcat window is the raw data that SoapUI sends:

Screenshot of SoapUI and nc

As we can see, SoapUI adds several headers that we’re unable to see in SoapUI itself. netcat will not
forward the request to the actual server we’re trying to use, and the connection will eventually time out,
unless you write something in the netcat window.

Wireshark

Wireshark is a tool I’ve written several posts
about before. Wireshark is easy to use and supported on all major operating systems. It’s a full blown
packet capturing and protocol analyzing application that can do way more than just log HTTP requests. It
can be downloaded from the Wireshark homepage. You might have problems using Wireshark in corporate
environments, as it can be used to sniff passwords etc. You probably also need admin rights to install and use it.

To see HTTP requests in Wireshark you just have to start capturing on the correct network adapter. The HTTP
request will exists as one or more packets, and potentially the same for the response. Just right click on the packet
and choose Follow –> TCP stream.

Screenshot of Wireshark - 1

This will show the stream of packets between the client and server and also show the request and response like this:

Screenshot of Wireshark - 2

Tracing requests with the framework in use

You might be unable to install Fiddler, Wireshark and similar applications in a production environment. This is where
it’s nice to log the requests to a file or a database instead. Here is an example where I use the tracing functionality
in the .NET framework to log requests and other data to two different log files. You can probably find similar examples
for Java, C++, etc. by searching Google.

Let’s say we have the following application:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using psi.udir.no.kl06._2016._04;

namespace TracingTest
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var client = new GrepSoapClient();

            var request = new finnaarstrinnrequest() { valgtspraak = "no" };
            var response = await client.FinnAarstrinnAsync(request);

            Console.WriteLine(response.treff[0].kode);
        }
    }
}

It sends a SOAP request and prints a part of the response to the console. In order to log the raw request and response I
have to add a listener to the trace source of System.Net and System.ServiceModel.MessageLogging. That is usually done
by creating a configuration file (app.config) and setting it up so it looks something like this:

<configuration>
    <system.diagnostics>

        <trace autoflush="true" />

        <sources>
            <source name="System.Net" maxdatasize="1024">
                <listeners>
                    <add name="SystemNetTraceFile"/>
                </listeners>
            </source>
            <source name="System.ServiceModel.MessageLogging">
                <listeners>
                    <add name="SystemServiceModelMessageLoggingTraceFile"/>
                </listeners>
            </source>
        </sources>

        <sharedListeners>
            <add
              name="SystemNetTraceFile"
              type="System.Diagnostics.TextWriterTraceListener"
              initializeData="System.Net.trace.log" />
            <add
              name="SystemServiceModelMessageLoggingTraceFile"
              type="System.Diagnostics.TextWriterTraceListener"
              initializeData="System.ServiceModel.MessageLogging.trace.log" />
        </sharedListeners>

        <switches>
            <add name="System.Net" value="Verbose" />
            <add name="System.ServiceModel.MessageLogging" value="Verbose" />
        </switches>

    </system.diagnostics>

    <system.serviceModel>
        <diagnostics wmiProviderEnabled="true">
            <messageLogging
                logEntireMessage="true"
                logMalformedMessages="true"
                logMessagesAtServiceLevel="true"
                logMessagesAtTransportLevel="true"
                maxMessagesToLog="3000"
            />
        </diagnostics>
    </system.serviceModel>
</configuration>

It’s built on this and this example.

I attach one listener to the System.Net trace source and one to the System.ServiceModel.MessageLogging
trace source. They will log to System.Net.trace.log and System.ServiceModel.MessageLogging.trace.log,
respectively. The log file will look something like this after sending the request:

Screenshot of trace log

We can see the raw request and response, as wanted. If this particular instance I used SOAP. It will, of
course, work for all HTTP requests.

This doesn’t work very well for .NET Core, as of now, but I believe it will improve in version 3.0.

Summary

  • I recommend using Fiddler if that’s possible. Windows might be needed, and it works best when in a
    development environment where you are able to install applications.
  • netcat is very light weight and is often installed in *nix environments. It’s a multipurpose networking
    utility that’s used for much more than viewing raw requests. Often not possible to use netcat in
    corporate environments.
  • Wireshark is a full-blown packet analyzer and is better suited when you are developing applications
    that use protocols at a lower abstraction level than HTTP. Is also impossible to install and use in some
    corporate environments.
  • Tracing and logging requests with the used framework (e.g. .NET, Spring, etc.) is typically needed
    in production environments as you can’t really install Fiddler, Wireshark, etc. there.

FiddlerT3 Light_1200x303

What if you found a simple yet effective way to trace HTTP(s) requests and responses with a few clicks? While you may initially miss the painstaking method of tracing HTTP requests manually, you can harness the power of a web proxy to trace and debug network requests and responses. 

Could you put it in perspective? You have hundreds of requests coming from your system, whether it be a web browser, an application, or any process running in the background of your network. It’s 4:40 pm, and your boss notifiies you that there is site failure and expects you to trace and debug an application immediately. With no time to spare, you need to turn to a tool that can securely perform an HTTP trace. You turn to Fiddler Everywhere; it is easy to download, install, and comes with a free 30-day trial and works on Windows, macOS and Linux.  
Within 10 minutes, you are using Fiddler Everywhere’s traffic inspector to trace every HTTP network request. By tracing all HTTP requests within Fiddler Everywhere’s live traffic tab, you look for failing requests, incorrect responses, and performance concerns to troubleshoot the problem. 

Steps to Take:

  1. Download Fiddler Everywhere from https://www.telerik.com/download/fiddler-everywhere and select the appropriate install, Windows, macOS or Linux.
  2. Start the tool, then the browser or client app. Reproduce the problem. 
  3. Fix the problem, Menu > Tools > Options > HTTPS tab > Check Decrypt HTTPS traffic.

Fiddler Everywhere has different types of Traffic Inspectors available, which can be used based on the content’s format. You can switch the Inspectors by merely clicking on the required tab. Some of the available Inspectors in Fiddler Everywhere include:   

  • Headers 
  • Text 
  • Raw 
  • JSON 
  • XML 
  • Cookies 
  • Web Forms (Request only) 
  • Image (Response only) 
  • Web (Response only) 

Traffic Inspector UI

What You Can Accomplish by Tracing HTTP Requests On-the-Fly 

Quick insight into network traffic requests

For example, you can trace the type of content that has been received, whether it’s an HTML format, JSON, or if it’s a CSS or JavaScript. 

Look at requests side by side

You can trace HTTP(S) status codes and the protocol and the host, and the URL of the network request. Plus, Fiddler Everywhere provides insight about the method and the body size, along with the content type and the process from which the request originated. 

Ability to go deeper within a request

If you want to further trace a particular request, all you need to do is click on that request, and you will see the request inspector at the top and the response inspector at the bottom. 

The on-the-fly process described above gives you an advantage you won’t experience outside of Fiddler Everywhere: the ability to play with the traffic and trace non-web apps. You can’t solve an issue if you can’t see it and that is what Fiddler Everywhere HTTP tracing does; it lets you go behind the scenes to get to a fix right away. 

There are other scenarios where the use of HTTP tracing can help you debug issues. Whether you need to trace different devices or manipulate responses to run «what if’s» or intercept your traffic, you can use Fiddler Everywhere to speed up your debugging process and go from error to fix faster than you ever thought possible. Don’t leave your HTTP(s) tracing and debugging success to chance—start a 30-day trial to realize the benefits you can derive from adding Fiddler Everywhere to your workflow. 

Get started with the steps above today to trace your HTTP requests, there is no software to ship, or lengthy approval process—the software is ready to go at https://www.telerik.com/fiddler.

Try Fiddler Now


About the Author

Eve Turzillo

Eve Turzillo is a Developer Advocate at Progress, with a passion for all things related to digital experience. For close to 20 years, Eve has been bridging the gap between technologies and community, starting with .NET and now with managed file transfer. Her experience spans various technical ecosystems, yet fostering community engagement and developing initiatives that align with both organizational goals and community needs has always been at the core of what she does.

Related Posts

Comments

Программа Fiddler — это прокси, позволяющий просматривать все клиентские HTTP запросы и отслеживать трафик между локальным ПК и удаленным сервером/сервисом.

Она отлично работает, например, при отладке клиентской части сайта, позволяет просматривать внешние запросы, параметры и данные форм и куки (cookies).

Но при работе с веб-сервисами (web services), когда, например, нужно отследить по какому URL адресу сервис осуществил запрос, без дополнительной настройки программы Fiddler данного действия не увидеть. Это возможно, если сайт работает через инструмент Cassini, но в случае с IIS — Fiddler не покажет необходимую информацию о трафике сервиса.

Причина кроется в учетных записях, от имени которых работают IIS и Fiddler. Они оба запускаются под администратором. А вот приложения (сайты, сервисы) под управлением IIS работают уже из-под учетной записи «Network Service». Если бы можно было запустить Fiddler под Network Service, проблема была бы решена, но к сожалению, это невозможно.

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

Сделаем следующие шаги:

1) Добавим пользователя, обладающего правами администратора, в группу IIS_IUSRS (для IIS 7 и младше) или в группу IIS_WPG (для IIS 6 и старше) (группа обладает правами сетевой службы).

Для этого переходим:

Computer Management -> Local Users and Groups -> Groups -> IIS_IUSRS/IIS_WPG и добавляем в группу администратора.

computer-management.png

2) Теперь необходимо настроить пул веб-приложения (Application Pool) для его запуска под учетной записью администратора.

Здесь может быть два варианта. Если для сайта, который нужно отслеживать, выделен отдельный пул, то настройку можно производить конкретно для него. Либо создать новый пул специально для подобных процедур и затем при необходимости привязывать его к нужным приложениям.

Итак, заходим в IIS, в списке пулов (Application Pools) выбираем нужный пул и переходим в его расширенные настройки (Advanced Settings):

 

iis-application-pool.png

В настройках пула в параметре Identity выбираем Custom account и по нажатию на Set — прописываем учетные данные администратора (логин и два раза пароль):

iis-application-pool-identity-setting.png

При необходимости связываем пул приложения (Application Pool) с веб-приложением. Для этого переходим в расширенные настройки нужного сайта/приложения и указываем пул:

iis-web-app-advanced-setting.png

Теперь можно запускать Fiddler, стартовать сайт/сервис и программа будет отслеживать все его запросы.

fiddler.png

© Ella S.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Мем обои windows 10
  • Синхронизация каталогов windows robocopy
  • Ecs h55h m драйвера windows 10
  • Чем открыть pdf файл на windows 10 бесплатно
  • Windows service local system local service