Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions application/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
return "<p>Hello, Linux!</p>"

@app.route("/get")
def handle_get():
return "<p>Received a GET request!</p>"

@app.route("/post")
def handle_post():
return "<p>Received a POST request!</p>"

@app.route("/put")
def handle_put():
return "<p>Received a PUT request!</p>"

app.run(host='0.0.0.0', port=5000)
10 changes: 10 additions & 0 deletions configs/LinuxA/00-installer-config.yaml
Original file line number Diff line number Diff line change
@@ -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
13 changes: 13 additions & 0 deletions configs/LinuxA/web-server.service
Original file line number Diff line number Diff line change
@@ -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
12 changes: 12 additions & 0 deletions configs/LinuxB/00-installer-config.yaml
Original file line number Diff line number Diff line change
@@ -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
10 changes: 10 additions & 0 deletions configs/LinuxB/rules.v4
Original file line number Diff line number Diff line change
@@ -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
67 changes: 67 additions & 0 deletions configs/LinuxB/sysctl.conf
Original file line number Diff line number Diff line change
@@ -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
10 changes: 10 additions & 0 deletions configs/LinuxC/00-installer-config.yaml
Original file line number Diff line number Diff line change
@@ -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
104 changes: 104 additions & 0 deletions report.md
Original file line number Diff line number Diff line change
@@ -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. Все настройки сохраняются после перезагрузки системы.
Binary file added screenshots/curlA.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added screenshots/curlC.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added screenshots/ipaddrA.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added screenshots/ipaddrB.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added screenshots/ipaddrC.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added screenshots/iproute.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added screenshots/iptables.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added screenshots/pingloss.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added screenshots/tcpdump.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added screenshots/webserver.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.