Лайфхаки

Маленькие, полезные хитрости

Реверс-прокси на службе человечества. Постановка задачи

25.06.2022 в 05:58

Реверс-прокси на службе человечества. Постановка задачи


В ходе проведения пентестов и RedTeam кампаний не всегда удается воспользоваться штатными средствами Заказчиков, такими как VPN, RDP, Citrix и т.д. в качестве закрепления для захода во внутреннюю сеть. Где-то штатный VPN работает по MFA и в качестве второго фактора используется железный токен, где-то он жестоко мониторится и наш вход по VPN сразу же становится виден, как говорится — со всеми вытекающими, а где-то таких средств попросту нет.В подобных случаях постоянно приходится делать так называемые «обратные туннели» — соединения из внутренней сети к внешнему ресурсу или контролируемому нами серверу. Внутри такого туннеля мы уже можем работать с внутренними ресурсами Заказчиков.Существуют несколько разновидностей таких обратных туннелей. Самый известный из них, конечно же, Meterpreter. Так же большим спросом в народных хакерских массах пользуются SSH-туннели с обратным пробросом портов. Средств осуществления обратного туннелирования достаточно много и многие из них хорошо изучены и описаны.Конечно же, со своей стороны разработчики защитных решений не стоят в стороне и активно детектируют подобные действия.К примеру, MSF-сессии успешно детектируются современными IPS от Cisco или Positive Tech, а обратный SSH- туннель можно задетектить практически любым мало-мальским нормальным файерволлом.Следовательно, для того чтобы остаться незамеченным в хорошей RedTeam кампании — нам необходимо строить обратный туннель нестандартными средствами и максимально близко подстраиваться под реальный режим работы сети.Давайте попробуем найти или изобрести нечто подобное.Прежде чем что-то изобретать надо понять, какого результата мы хотим достичь, какие функции должна выполнять наша разработка. Какие же будут требования к туннелю, чтобы мы могли работать в режиме максимальной скрытности?Понятно, что для каждого случая такие требования могут сильно отличаться, но по опыту работы можно выделить основные:
  • работа на ОС Windows-7-10. Так как в большинстве корпоративных сетях используется именно винда;
  • клиент соединяется с сервером по SSL для исключения тупого прослушивания средствами ips;
  • при соединении клиент должен поддерживать работу через прокси-сервер с авторизацией, т.к. во многих компаниях выход в интернет происходит через прокси. На самом деле, клиентская машина может об этом даже ничего и не знать, а прокси используется в транспарентном режиме. Но такой функционал мы должны заложить;
  • клиентская часть должна быть лаконична и портабельна;
    Понятно, что для работы внутри сети Заказчика на клиентской машине можно установить OpenVPN и поднять полноценный туннель до своего сервера (благо что клиенты openvpn умеют работать через прокси). Но, во-первых, это не всегда получится, так как мы можем не быть там локальными админами, а во-вторых, это наделает так много шуму, что порядочный SIEM или HIPS тут же на нас «настучит куда надо». В идеале наш клиент должен быть так называемой inline командой, как например реализованы многие bash-шеллы, и запускаться через командную строку, например, при выполнении команд из word-макроса.
  • наш туннель должен быть многопоточным и поддерживать множество соединений одновременно;
  • соединение клиент-сервер должно иметь какую-либо авторизацию, чтобы туннель устанавливался только для нашего клиента, а не для всех, кто придет к нам на сервер по указанному адресу и порту. В идеале, для «сторонних пользователей» должна открываться лендинг-страница с котиками или профессионально тематикой, связанной с исходным доменом.
    Например, если Заказчиком выступает медицинская организация, то для администратора информационной безопасности, решившего проверить ресурс, на который обращался сотрудник клиники, должна открыться страница с фармацевтическими товарами, википедия с описанием диагноза или блог доктора Комаровского и т.д.

Reverse Proxy nginx, что это. Nginx as a Reverse Proxy

Nginx is a versatile tool: webserver, load balancer, reverse proxy. In this article, I show how to use Nginx as the central reverse proxy in your cloud that works with Consul and local DNS servers for providing well-known domain names of applications running in your cloud.

You know, sometimes a tool is great, but you wish to have more control, and you wish to truly understand the problems that a tool solves. This is my motivation for … replacing the edge Router Traefik with Nginx.

Nginx is first and foremost a proven, resource effective, open source webserver. It also is, as of a march 2020 report , the number one webserver with 37% market share. Nginx is the web server that we employ at work to load balance services, to provide TLS, and as an ingress server in our Kubernetes cluster.

All good reasons to use Nginx in my infrastructure at home project as well. Nginx will fulfill several roles. First of all, it will be an edge router, connection external networks with the services that run in my cloud. Second, it will provide TLS encryption for client to service and for service to service communication.

In this article, I will show how to start and configure Nginx to work as a reverse proxy server.

This article appeared originally at my blog .

Custom Nginx Docker Image

The custom Docker image will be based on the official Nginx image. I will add two volumes: One for providing the config files, and one for providing static content. Here is the Dockerfile:

We build the docker container.

>> docker build . -t inginx Sending build context to Docker daemon 2.048kB Step 1/3 : FROM nginx:1.17.9-alpine --- > 377c0837328f Step 2/3 : VOLUME --- > Using cache --- > b1fca48d47f8 Step 3/3 : VOLUME --- > Using cache --- > 26e85fbde6b0 Successfully built 26e85fbde6b0 Successfully tagged inginx:latest

Now we need to provide the basic configuration file/etc/nginx/conf.d/serve_static.conf. The file will create a Nginx process that listens on port80and it will serve the route /data/www.

Then, provide some files for/data/www/and run the container.

Enterhttp://localhost:80/staticin your browser, and you will see something like this:

Good. Now let’s evolve this basic config to a reverse proxy.

Nginx Reverse Proxy Configuration

In a nutshell, a reverse proxy is a server that receives incoming requests and forwards them to another server. In a production setup, you would also configure features like load balancing requests between different servers, applying modifications the request URI and modifying the headers. The example in our case will be to accept requests for the hostgrafana.infraand forward them to the same named service that is registered with Consul.

Let’s build the configuration file

DNS Resolution for Services

First, we need to understand the following Nginx configuration directives:

    resolver: The server that provides DNS resolution upstream: Defines one or a group of servers to which the traffic will be forwarded. Eachservercan be defined as an IP address or with a domain name.

The definition of an upstream server for the Grafana is this:

As you see, I'm using the local DNS resolver to resolve the domain namegrafana.service.consul- behind the scenes, Consul will provide the real IP for this service.

Forward Incoming Requests

Now we need to define how to accept and process requests. The relevant Nginx directives are:

    server: Defines a request handler server_name: This directive defines for which domain name the request handler is responsible, you can use multiple servers or wildcards in the domain name listen: The ports on which Nginx listens location: Each location block defines what to do when the URL matches a specific route proxy_pass: The server to which the incoming requests will be forwarded to

We want requests fromgrafana.infrato be passed to our upstreamgrafanaserver. The configuration is the following snippet:

This configuration works … not completely. For some reasons, JavaScript resources cannot be properly loaded. When I run the Docker container, and then open browser console, I see this:

Why is that? The Grafana server does not know that a proxy was involved. We need to add additional HTTP headers for forwarding requests from Nginx to Grafana. These headers are:

Their meaning is:

    proxy_redirect- Do not bounce traffic back to the receiving end Host- Keep the same host name from the original request X-Real-IP: Keep the original requests IP address X-Forwarded-For: A list of IP addresses telling the service how this request was routed X-Forwarded-Proto: Keep the requests scheme

Final Configuration File

Let’s put all of this together. The final configuration filegateway.confis this:

Running the Nginx Reverse Proxy

Now we can run the Docker container, and access it in our browser.

Reverse Proxy nginx настройка. Benefits of a Reverse Proxy

Configuring an Nginx reverse proxy means that all incoming requests are handled at a single point, which provides several advantages:

  • Load balancing – The reverse proxy distributes incoming connections to backend servers, and can even do so according to the current load that each server is under. This ensures that none of the backend servers get overloaded with requests. It also prevents downtime, since the reverse proxy can reroute traffic if a backend server happens to go offline.
  • Central logging – Rather than having multiple servers generate log files, the reverse proxy can log all relevant information in a single location. This makes the administrator’s job immensely easier, since problems can be isolated much more quickly and there is no need to parse log files from multiple locations when troubleshooting issues.
  • Improved security – A reverse proxy will obfuscate information about the backend servers, as well as act as a first line of defense against incoming attacks. Since the reverse proxy is filtering out traffic prior to forwarding it to the backend, only innocuous traffic is passed along to the other servers.
  • Better performance – A reverse proxy server can make smart decisions about how to distribute the load across backend servers, which results in speedier response times. Other common server tasks such as caching and compression can also be offloaded to the reverse proxy server, freeing up resources for the backend servers.

Reverse Proxy vs Proxy. Reverse Proxy

Reverse Proxy is something that doesn't show in your system settings or browsing the web but it's something that every developer should know. Let's take an example where you host a website onwww.something.comand it became popular. The number of people reaching your website increases dramatically and as new users start coming, your web server starts to slow down and starts dropping connection. Now what do you do ?

You decided to upgrade the computer on which it is hosted, well that does solve the problem, but to what extent. Eventually if the traffic increases your server won't be able to handle the users.

Then let's say you decided that you will add another server to handle the traffic. But how will you go out and tell everyone and deviate traffic. How will the user know which server to hit to get access to the website? This is where a reverse proxy comes in.

Instead of choosing between which server to go to, the user will hit your reverse proxy and the reverse proxy will deviate some users towebserver1and some users towebserver2. And if you add more servers, you can just tell the address of the newly added servers to reverse proxy. This concept is known as load balancing.

You may ask, what if the reverse proxy gets overwhelmed, well yes that can happen and does happen, but then we have other methods to handle such massive traffic using DNS based load balancing or breaking your service into smaller parts and hosting them differently.

Uses of reverse proxy

  • Load balancing – A reverse proxy server can act as a “traffic cop,” sitting in front of your backend servers and distributing client requests across a group of servers in a manner that maximizes speed and capacity utilization while ensuring no one server is overloaded, which can degrade performance. If a server goes down, the load balancer redirects traffic to the remaining online servers.
  • Web acceleration – Reverse proxies can compress inbound and outbound data, as well as cache commonly requested content, both of which speed up the flow of traffic between clients and servers. They can also perform additional tasks such as SSL encryption to take load off of your web servers, thereby boosting their performance.
  • Security and anonymity – By intercepting requests headed for your backend servers, a reverse proxy server protects their identities and acts as an additional defense against security attacks. It also ensures that multiple servers can be accessed from a single record locator or URL regardless of the structure of your local area network.