Невозможно получить доступ к SSH из WAN, хотя сам сервер доступен

Невозможно получить доступ к SSH из WAN, хотя сам сервер доступен

У меня есть сервер в локальной сети, который я использую для работы по SSH. У меня нет проблем с подключением к нему из локальной сети. Проблема возникает, когда я пытаюсь подключиться к нему извне. Я настроил переадресацию портов для порта 2209 (это мой пользовательский порт SSH), а также веб-портов. Мне удалось подключиться к нему один раз, когда я его настраивал, но примерно через неделю соединение продолжает прерываться по тайм-ауту.

В то же время я могу открыть веб-страницу с сервера, так что порт 80 работает нормально. На самом деле это просто порт 2209. Я подтвердил, что переадресация портов верна, этот порт настроен как исключение в брандмауэре Windows, и правило включено. Однако соединение истекает по тайм-ауту.

Пожалуйста, дайте мне знать, если вам нужны скриншоты или логи, я могу предоставить. Я не уверен, какая информация нужна для лучшей оценки.

UPD 1: Люди в комментариях указали на запуск ssh с опцией -vvv, вот логи:

❯ ssh -vvv -p 2209 andrey@<ip>

OpenSSH_7.6p1 Ubuntu-4ubuntu0.3, OpenSSL 1.0.2n  7 Dec 2017
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolving "<ip>" port 2209
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to <ip> [<ip>] port 2209.
debug1: connect to address <ip> port 2209: Resource temporarily unavailable
ssh: connect to host <ip> port 2209: Resource temporarily unavailable

В то же время подключение внутри локальной сети абсолютно нормальное. Как и подключение к HTTP сервера из глобальной сети.

А вот моя конфигурация SSH:

❯ cat /etc/ssh/sshd_config

#       $OpenBSD: sshd_config,v 1.103 2018/04/09 20:41:22 tj Exp $

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

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

# 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 2209
#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 prohibit-password
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

#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 yes
#PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication 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 ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication 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 ChallengeResponseAuthentication 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 /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# 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

И /etc/ssh/sshd_config.dпусто, так что это единственная конфигурация.

UPD 2: Я понял, что не упомянул, что именно я настроил. Это машина Windows, но SSH находится внутри WSL. Поэтому мне нужно пройти через брандмауэр Windows, чтобы получить доступ к SSH.

решение1

Как и во всех случаях с этой штукой, меня не блокировала какая-то странная таинственная сила. Я смотрел на переадресацию портов в маршрутизаторе и брандмауэр в Windows. Но, покопавшись в настройках маршрутизатора, я обнаружил, что у него очень минимальный брандмауэр, который не делал почти ничего, кроме как блокировал пинг из WAN. Думаю, все мои клиенты SSH использовали пинг в качестве первого шага, и если он не удавался, они не подключались.

Все это к тому, что если у вас возникла похожая проблема, просто проверьте свой сервер.инастройки маршрутизатора для всех опций.

Связанный контент