---
# System prepended metadata

title: Linux
tags: [iptables, сеть, linux]

---

# Linux
###### tags: `linux` `iptables` `сеть`

## сеть ubuntu 21.04

`nano /etc/netplan/01-netcfg.yaml`

```
network:
  version: 2
  renderer: networkd
  ethernets:
    enp0s3:
      dhcp4: no
      addresses: [172.16.11.1/24]
      nameservers:
          addresses: [8.8.8.8, 8.8.4.4]
      routes:
      - to: 0.0.0.0/0
        via: 172.16.11.254
```
```
sudo netplan apply
```

`ip route add default via 172.16.11.254`

 или
 
```
 ens3
auto ens3
allow-hotplug ens3
iface ens3 inet dhcp

# ip link set dev ens3 up
# ip link set dev ens3 down

service networking restart
```
## :bulb: ПРОВЕРЬ НАСТРОЙКИ ВРЕМЕНИ НА СЕРВЕРАХ
```
$ sudo apt-get install ntpdate
$ sudo ntpdate in.pool.ntp.org
```

- выставить зону Europe/Moscow (или зону где находится сервр)

`timedatectl set-timezone Europe/Moscow`

## настраиваем пользователя и доступ по сертификату

создаем пользователя

```
adduser user

usermod -aG sudo user

usermod -aG adm user
```

генерируем пару ключей на сервере откуда будем подключаться

`ssh-keygen -b 4096`

`cat /home/USER/.ssh/id_rsa.pub`

прописываем открытый ключ из файла id_rsa.pub на сервер куда подключаемся в файл 

`nano /home/USER/.ssh/authorized_keys`

* set persmittions
`chmod 0600 /home/your_home/.ssh/authorized_keys`

HBFW setup

```
  ufw default deny incoming
  ufw default allow outgoing
  sudo ufw allow 22
  sudo ufw allow 80
  sudo ufw allow 443
  sudo ufw limit 22
  sudo ufw allow 8443
  sudo ufw show added
  sudo ufw enable
  ufw status verbose
  ```


## SSHD_Conf

`sudo nano /etc/ssh/sshd_config`

```

# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.

Include /etc/ssh/sshd_config.d/*.conf

#Port 22
#AddressFamily any
ListenAddress 0.0.0.0
#ListenAddress ::

#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_ecdsa_key
#HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying
#RekeyLimit default none

# Logging
#SyslogFacility AUTH
#LogLevel INFO

# Authentication:

LoginGraceTime 2m
PermitRootLogin no
StrictModes yes
MaxAuthTries 3
MaxSessions 2

PubkeyAuthentication yes

# Expect .ssh/authorized_keys2 to be disregarded by default in future.
#AuthorizedKeysFile     .ssh/authorized_keys .ssh/authorized_keys2

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
PasswordAuthentication no
PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
KbdInteractiveAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the KbdInteractiveAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via KbdInteractiveAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and KbdInteractiveAuthentication to 'no'.
UsePAM yes

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
PrintMotd no
#PrintLastLog yes
#TCPKeepAlive yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS no
#PidFile /run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none
Banner /etc/issue.net

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

# override default of no subsystems
Subsystem sftp  /usr/lib/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#       X11Forwarding no
#       AllowTcpForwarding no
#       PermitTTY no
#       ForceCommand cvs server
#PasswordAuthentication no
```
`systemctl restart ssh`

## iptables (as router)

```
for private_ip in $(cat private_ip.list);
# do echo "Banning $IP"; 
iptables -A INPUT -s $IP/32 -d 0/0 -j DROP; 
done

```
```
 #!/bin/bash
 #Настроим iptables
 #Сбросим старые настройки
 iptables -F
 iptables -X
 iptables -t nat -F
 iptables -t nat -X
 
 #дропаем все по умолчанию
 iptables -P INPUT DROP
 iptables -P FORWARD DROP
 iptables -P OUTPUT DROP
 
 #разрешаем межблочный обмен на локал хост
 iptables -A INPUT -i lo -j ACCEPT
 iptables -A OUTPUT -o lo -j ACCEPT
 
 #Разрешим ICMP всем
 iptables -A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT
 iptables -A OUTPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT
 iptables -A FORWARD -p icmp -m icmp --icmp-type 8 -j DROP
 
 # разрешить локальные соединения с динамических портов
 iptables -A OUTPUT -p TCP --sport 32768:61000 -j ACCEPT
 iptables -A OUTPUT -p UDP --sport 32768:61000 -j ACCEPT
 
 # Droping all invalid packets
 iptables -A INPUT -m state --state INVALID -j DROP
 iptables -A FORWARD -m state --state INVALID -j DROP
 iptables -A OUTPUT -m state --state INVALID -j DROP
 
 # Разрешаем DNS
 iptables -A INPUT -p udp --dport 53 -j ACCEPT
 iptables -A OUTPUT -p udp --sport 53 --dport 1024:65535 -j ACCEPT
 
 #Разрешаем проходить пакетам по уже установленным соединениям
 iptables -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
 
 #Разрешить только те пакеты, которые мы запросили:
 iptables -I INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
 iptables -I OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
 
 #открываем SSH
 iptables -A INPUT -p tcp -s 0.0.0.0/0 --dport=22 -j ACCEPT
 #iptables -A INPUT -p tcp -s 192.168.10.0/24 --dport=22 -j ACCEPT
 #iptables -A INPUT -p tcp -s 192.168.41.0/24 --dport=22 -j ACCEPT
 #iptables -A INPUT -p tcp -s 172.16.1.0/24 --dport=22 -j ACCEPT
 #iptables -A INPUT -p tcp -s 172.16.1.0/24  -j ACCEPT
 
 #Разрешаем исходящие соединения из локальной сети к интернет-хостам
 iptables -A FORWARD -m conntrack --ctstate NEW -i enp0s8 -s 172.16.11.0/24 -j ACCEPT
 
 #пробросим NAT
 iptables -t nat -A POSTROUTING -o enp0s3 -j MASQUERADE
 
 #проброс внутрь SSH 
 #NGINX
 iptables -t nat -A PREROUTING -p tcp -s 0.0.0.0/0 --dport 2201 -j DNAT --to-destination 172.16.11.1:22
 iptables -A FORWARD -p tcp -d 172.16.11.1 --dport 22 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
 
 #пишем в лог все дропы
 iptables -N LOGGING
 iptables -A INPUT -j LOGGING
 iptables -A LOGGING -m limit --limit 2/min -j LOG --log-prefix "IPTables-Dropped: " --log-level 4
 iptables -A LOGGING -j DROP
 
 ## NEW Reject Forwarding  traffic
 iptables -A OUTPUT -j REJECT
 iptables -A FORWARD -j REJECT
 
 # save config
 iptables-save > /etc/iptables.rules
 echo "iptables rules complete"
```
# show used space 
`du -h --max-depth=1 /var/lib/docker/ | sort -hr`

- remove unused photos, we can use the below command
`docker image prune --all`

https://bobcares.com/blog/docker-overlay2-cleanup/

# Log rotation
https://evilinside.ru/rotaciya-logov-docker-kontejnerov/

https://itisgood.ru/2022/04/19/umenshenie-razmera-logov-docker-na-diske/


# Linux - как почистить логи /var/log/journal/
/var/log/journal - это директория с логами systemd пакета
директория /var/log/journal - стала заниматься слишком много места и ее нужно очистить:

953M    /var/log/journal
До очистки:

`journalctl --disk-usage`
`Archived and active journals take up 952.2M on disk.`
-Делаем чистку:

`journalctl --vacuum-size=50M`
`journalctl --verify`
- После очистки получаем результат:

`journalctl --disk-usage`
`Archived and active journals take up 56.0M on disk.`

- Меняем конфиг:

`vi /etc/systemd/journald.conf`
```
SystemMaxUse=50M
SystemMaxFileSize=12M
```
`systemctl restart systemd-journald`
