Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading;
- using System.Collections.Generic;
- namespace Task1_2
- {
- public class Program
- {
- static void Main(string[] args)
- {
- int port = 8080;
- TcpListener listener = new TcpListener(IPAddress.Any, port);
- listener.Start();
- Console.WriteLine($"[+] Прокси-сервер запущен на порту {port}...");
- while (true)
- {
- TcpClient client = listener.AcceptTcpClient();
- Thread thread = new Thread(() => HandleClient(client));
- thread.Start();
- }
- }
- private static readonly List<string> MaliciousPatterns = new List<string>
- {
- "SQLmap",
- "MaliciousHeader",
- "/etc/passwd",
- "cmd.exe",
- "union select"
- };
- private static void HandleClient(TcpClient client)
- {
- using (client)
- {
- try
- {
- NetworkStream clientStream = client.GetStream();
- byte[] buffer = new byte[8192];
- int bytesRead = clientStream.Read(buffer, 0, buffer.Length);
- if (bytesRead == 0)
- {
- return;
- }
- string requestText = Encoding.UTF8.GetString(buffer, 0, bytesRead);
- Console.WriteLine($"[>] Запрос от клиента:\n{requestText.Split('\n')[0]}");
- if (IsMalicious(requestText))
- {
- Console.WriteLine("[!] Подозрительный запрос заблокирован!");
- string forbiddenResponse = "HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n";
- byte[] responseBytes = Encoding.UTF8.GetBytes(forbiddenResponse);
- clientStream.Write(responseBytes, 0, responseBytes.Length);
- return;
- }
- ForwardRequest(requestText, clientStream);
- }
- catch (Exception ex)
- {
- Console.WriteLine($"[x] Ошибка: {ex.Message}");
- }
- }
- }
- private static bool IsMalicious(string request)
- {
- request = request.ToLower();
- foreach (var pattern in MaliciousPatterns)
- {
- if (request.Contains(pattern.ToLower()))
- {
- return true;
- }
- }
- return false;
- }
- private static void ForwardRequest(string requestText, NetworkStream clientStream)
- {
- try
- {
- string[] lines = requestText.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None);
- string hostLine = Array.Find(lines, line => line.StartsWith("Host:", StringComparison.OrdinalIgnoreCase));
- if (hostLine == null)
- {
- Console.WriteLine("[!] Не удалось определить хост.");
- return;
- }
- string host = hostLine.Substring(6).Trim();
- int port = 80;
- using (TcpClient server = new TcpClient(host, port))
- using (NetworkStream serverStream = server.GetStream())
- {
- byte[] requestBytes = Encoding.UTF8.GetBytes(requestText);
- serverStream.Write(requestBytes, 0, requestBytes.Length);
- byte[] buffer = new byte[8192];
- int bytesRead;
- while ((bytesRead = serverStream.Read(buffer, 0, buffer.Length)) > 0)
- {
- clientStream.Write(buffer, 0, bytesRead);
- }
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine($"[x] Ошибка при пересылке запроса: {ex.Message}");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement