diff --git a/application/app.py b/application/app.py new file mode 100644 index 0000000..78d69d5 --- /dev/null +++ b/application/app.py @@ -0,0 +1,21 @@ +from flask import Flask + +app = Flask(__name__) + +@app.route("/") +def hello_world(): + return "

Hello, Linux!

" + +@app.route("/get") +def handle_get(): + return "

Received a GET request!

" + +@app.route("/post") +def handle_post(): + return "

Received a POST request!

" + +@app.route("/put") +def handle_put(): + return "

Received a PUT request!

" + +app.run(host='0.0.0.0', port=5000) \ No newline at end of file diff --git a/configs/LinuxA/00-installer-config.yaml b/configs/LinuxA/00-installer-config.yaml new file mode 100644 index 0000000..b2f29bc --- /dev/null +++ b/configs/LinuxA/00-installer-config.yaml @@ -0,0 +1,10 @@ +# This is the network config written by 'subiquity' +network: + ethernets: + enp0s3: + dhcp4: true + enp0s8: + dhcp4: no + addresses: [192.168.20.10/24] + gateway4: 192.168.20.1 + version: 2 \ No newline at end of file diff --git a/configs/LinuxA/web-server.service b/configs/LinuxA/web-server.service new file mode 100644 index 0000000..feec09d --- /dev/null +++ b/configs/LinuxA/web-server.service @@ -0,0 +1,13 @@ +[Unit] +Description=My Flask Web Server Sheptunov +After=network.target + +[Service] +Type=idle +User=sheptunov_1 +WorkingDirectory=/home/sheptunov_1/server/ +ExecStart=/usr/bin/python3 /home/sheptunov_1/server/app.py +Restart=always + +[Install] +WantedBy=multi-user.target \ No newline at end of file diff --git a/configs/LinuxB/00-installer-config.yaml b/configs/LinuxB/00-installer-config.yaml new file mode 100644 index 0000000..4d6eaba --- /dev/null +++ b/configs/LinuxB/00-installer-config.yaml @@ -0,0 +1,12 @@ +# This is the network config written by 'subiquity' +network: + ethernets: + enp0s3: + dhcp4: true + enp0s8: + dhcp4: no + addresses: [192.168.20.1/24] + enp0s9: + dhcp4: no + addresses: [192.168.2.1/24] + version: 2 \ No newline at end of file diff --git a/configs/LinuxB/rules.v4 b/configs/LinuxB/rules.v4 new file mode 100644 index 0000000..3934440 --- /dev/null +++ b/configs/LinuxB/rules.v4 @@ -0,0 +1,10 @@ +# Generated by iptables-save v1.8.4 on Sun Apr 20 11:26:07 2025 +*filter +:INPUT ACCEPT [8:848] +:FORWARD DROP [0:0] +:OUTPUT ACCEPT [8:848] +-A FORWARD -i enp0s8 -o enp0s9 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT +-A FORWARD -i enp0s9 -o enp0s8 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT +-A FORWARD -i enp0s9 -o enp0s8 -p tcp -m tcp --dport 5000 -m conntrack --ctstate NEW -j ACCEPT +COMMIT +# Completed on Sun Apr 20 11:26:07 2025 \ No newline at end of file diff --git a/configs/LinuxB/sysctl.conf b/configs/LinuxB/sysctl.conf new file mode 100644 index 0000000..1d5d55b --- /dev/null +++ b/configs/LinuxB/sysctl.conf @@ -0,0 +1,67 @@ +# +# /etc/sysctl.conf - Configuration file for setting system variables +# See /etc/sysctl.d/ for additional system variables. +# See sysctl.conf (5) for information. +# + +#kernel.domainname = example.com + +# Uncomment the following to stop low-level messages on console +#kernel.printk = 3 4 1 3 + +##############################################################3 +# Functions previously found in netbase +# + +# Uncomment the next two lines to enable Spoof protection (reverse-path filter) +# Turn on Source Address Verification in all interfaces to +# prevent some spoofing attacks +#net.ipv4.conf.default.rp_filter=1 +#net.ipv4.conf.all.rp_filter=1 + +# Uncomment the next line to enable TCP/IP SYN cookies +# See http://lwn.net/Articles/277146/ +# Note: This may impact IPv6 TCP sessions too +#net.ipv4.tcp_syncookies=1 + +# Uncomment the next line to enable packet forwarding for IPv4 +net.ipv4.ip_forward=1 + +# Uncomment the next line to enable packet forwarding for IPv6 +# Enabling this option disables Stateless Address Autoconfiguration +# based on Router Advertisements for this host +#net.ipv6.conf.all.forwarding=1 + +################################################################### +# Additional settings - these settings can improve the network +# security of the host and prevent against some network attacks +# including spoofing attacks and man-in-the-middle attacks through +# redirection. Some network environments, however, require that these +# settings are disabled so review and enable them as needed. +# +# Do not accept ICMP redirects (prevent MITM attacks) +#net.ipv4.conf.all.accept_redirects = 0 +#net.ipv6.conf.all.accept_redirects = 0 +# _or_ +# Accept ICMP redirects only for gateways listed in our default +# gateway list (enabled by default) +# net.ipv4.conf.all.secure_redirects = 1 +# +# Do not send ICMP redirects (we are not a router) +#net.ipv4.conf.all.send_redirects = 0 +# +# Do not accept IP source route packets (we are not a router) +#net.ipv4.conf.all.accept_source_route = 0 +#net.ipv6.conf.all.accept_source_route = 0 +# +# Log Martian Packets +#net.ipv4.conf.all.log_martians = 1 +# + +################################################################### +# Magic system request Key +# 0=disable, 1=enable all +# >1 bitmask of sysrq functions +# See https://www.kernel.org/doc/html/latest/admin-guide/sysrq.html +# for what other values do +#kernel.sysrq=438 \ No newline at end of file diff --git a/configs/LinuxC/00-installer-config.yaml b/configs/LinuxC/00-installer-config.yaml new file mode 100644 index 0000000..22d0323 --- /dev/null +++ b/configs/LinuxC/00-installer-config.yaml @@ -0,0 +1,10 @@ +# This is the network config written by 'subiquity' +network: + ethernets: + enp0s3: + dhcp4: true + enp0s8: + dhcp4: no + addresses: [192.168.2.10/24] + gateway4: 192.168.2.1 + version: 2 \ No newline at end of file diff --git a/report.md b/report.md new file mode 100644 index 0000000..1e28bf1 --- /dev/null +++ b/report.md @@ -0,0 +1,104 @@ +# Отчет по практической работе: Базовое администрирование Linux + +**Цель работы:** Настройка трех виртуальных машин Linux (сервер, шлюз, клиент), конфигурация сети между ними, настройка маршрутизации с фильтрацией трафика и развертывание простого веб-сервера. + +**Используемые инструменты:** VirtualBox, Ubuntu Server 20.04 LTS. + +**Личные данные:** +* Фамилия: sheptunov +* День рождения: 20 +* Месяц рождения: 2 + +## 1. Подготовка виртуальных машин + +Были созданы три виртуальные машины Ubuntu Server 20.04 в VirtualBox. Исходная машина была настроена, затем дважды клонирована. + +## 2. Настройка Linux A (sheptunov_server) + +### 2.1. Имя хоста и пользователь +* Hostname: `sheptunov_server` +* Пользователь: `sheptunov_1` + +### 2.2. Настройка сети +Сетевые адаптеры в VirtualBox: +* Адаптер 1: Сетевой мост (для доступа с хоста) +* Адаптер 2: Внутренняя сеть `servernet` + +Конфигурация Netplan (`/etc/netplan/00-installer-config.yaml`) + +Проверка IP-адресов после применения Netplan: +![Скриншот команды ip addr для машины A](./screenshots/ipaddrA.png) +### 2.3. Настройка веб-сервера (Flask) +Установлен Flask (pip install flask). +Создан файл app.py (см. папку application). +Создан и настроен сервис systemd /lib/systemd/system/web-server.service +Проверка статуса и автозагрузки сервиса: +![systemctl status web-server.service](./screenshots/webserver.png) +Проверка локальной работы сервера: +![ss -tulnp | grep 5000 и curl http://127.0.0.1:5000/... для всех эндпоинтов](./screenshots/curlA.png) +## 3. Настройка Linux B (sheptunov_gateway) +### 3.1. Имя хоста и пользователь +Hostname: sheptunov_gateway +Пользователь: sheptunov_2 + +### 3.2. Настройка сети +Сетевые адаптеры в VirtualBox: +Адаптер 1: Сетевой мост +Адаптер 2: Внутренняя сеть servernet +Адаптер 3: Внутренняя сеть clientnet +Конфигурация Netplan (/etc/netplan/00-installer-config.yaml) + +Проверка IP-адресов: +(Скриншот ip addr для машины B) +![ip addr для машины B](./screenshots/ipaddrB.png) +### 3.3. Настройка маршрутизации и файрвола +Включен IP Forwarding + +Настроены правила iptables для пропуска трафика только на порт 5000 от C к A и связанных соединений. Политика по умолчанию для FORWARD - DROP. +(Скриншот команды sudo iptables -L FORWARD -v -n --line-numbers ПОСЛЕ настройки) +![sudo iptables -L FORWARD -v -n ](./screenshots/iptables.png) +Правила сохранены с помощью iptables-persistent. + +## 4. Настройка Linux C (sheptunov_client) +### 4.1. Имя хоста и пользователь +Hostname: sheptunov_client +Пользователь: sheptunov_3 + +### 4.2. Настройка сети +Сетевые адаптеры в VirtualBox: +Адаптер 1: Сетевой мост +Адаптер 2: Внутренняя сеть clientnet +Конфигурация Netplan (/etc/netplan/00-installer-config.yaml) + +Проверка IP-адресов: +(Скриншот ip addr для машины C) +![ip addr для машины C](./screenshots/ipaddrC.png) +Проверка маршрута по умолчанию: +(Скриншот ip route для машины C) +![ip route для машины C](./screenshots/iproute.png) + +## 5. Тестирование сквозного соединения +### 5.1. Запуск tcpdump на шлюзе (Linux B) +Запущена команда sudo tcpdump -i any port 5000 -n для отслеживания трафика. +### 5.2. Отправка запросов с клиента (Linux C) на сервер (Linux A) +Выполнены команды curl к http://192.168.20.10:5000 для эндпоинтов /get, /post, /put. +(Скриншот выполнения команд curl на машине C с успешными ответами) +![curl на машине C с успешными ответами](./screenshots/curlC.png) +### 5.3. Анализ трафика на шлюзе (Linux B) +Вывод tcpdump показал успешный обмен пакетами между C (192.168.2.10) и A (192.168.20.10) на порту 5000. +(Скриншот вывода tcpdump во время выполнения curl) +![Вывод tcpdump](./screenshots/tcpdump.png) + +### 5.4. Проверка блокировки другого трафика +Попытка ping 192.168.20.10 с машины C была неуспешной (пакеты блокируются шлюзом B). +(Скриншот выполнения ping на машине C с потерей пакетов) +![ping на машине C с потерей пакетов](./screenshots/pingloss.png) +## 6. Проверка сохранения настроек после перезагрузки +Все три виртуальные машины были перезагружены (sudo reboot). После перезагрузки были выполнены следующие проверки: +IP Forwarding на Linux B активен (cat /proc/sys/net/ipv4/ip_forward показал 1). +Правила iptables на Linux B загружены (sudo iptables -L FORWARD -v -n показал настроенные правила). +Веб-сервер на Linux A запущен (systemctl status web-server.service показал active (running)). +Тестовый запрос curl http://192.168.20.10:5000/get с Linux C на Linux A прошел успешно. + +## 7. Выводы +В ходе практической работы была успешно настроена сетевая инфраструктура из трех виртуальных машин Linux. Настроен статический IP-адрес для сервера (A) и клиента (C), а также два статических IP для шлюза (B). С помощью iptables на шлюзе настроена маршрутизация и фильтрация трафика, разрешающая только HTTP-запросы на порт 5000 от клиента к серверу. Веб-сервер на Flask был развернут на сервере и настроен для автозапуска с помощью systemd. Все настройки сохраняются после перезагрузки системы. \ No newline at end of file diff --git a/screenshots/curlA.png b/screenshots/curlA.png new file mode 100644 index 0000000..0ac8438 Binary files /dev/null and b/screenshots/curlA.png differ diff --git a/screenshots/curlC.png b/screenshots/curlC.png new file mode 100644 index 0000000..95a7ea1 Binary files /dev/null and b/screenshots/curlC.png differ diff --git a/screenshots/ipaddrA.png b/screenshots/ipaddrA.png new file mode 100644 index 0000000..29887b3 Binary files /dev/null and b/screenshots/ipaddrA.png differ diff --git a/screenshots/ipaddrB.png b/screenshots/ipaddrB.png new file mode 100644 index 0000000..86375bd Binary files /dev/null and b/screenshots/ipaddrB.png differ diff --git a/screenshots/ipaddrC.png b/screenshots/ipaddrC.png new file mode 100644 index 0000000..96e0d52 Binary files /dev/null and b/screenshots/ipaddrC.png differ diff --git a/screenshots/iproute.png b/screenshots/iproute.png new file mode 100644 index 0000000..c6de37d Binary files /dev/null and b/screenshots/iproute.png differ diff --git a/screenshots/iptables.png b/screenshots/iptables.png new file mode 100644 index 0000000..2020697 Binary files /dev/null and b/screenshots/iptables.png differ diff --git a/screenshots/pingloss.png b/screenshots/pingloss.png new file mode 100644 index 0000000..b92288e Binary files /dev/null and b/screenshots/pingloss.png differ diff --git a/screenshots/tcpdump.png b/screenshots/tcpdump.png new file mode 100644 index 0000000..484e779 Binary files /dev/null and b/screenshots/tcpdump.png differ diff --git a/screenshots/webserver.png b/screenshots/webserver.png new file mode 100644 index 0000000..2b11a3a Binary files /dev/null and b/screenshots/webserver.png differ