One place for hosting & domains

      OpenSSH

      How To Harden OpenSSH Client on Ubuntu 18.04


      The author selected the Electronic Frontier Foundation Inc to receive a donation as part of the Write for DOnations program.

      Introduction

      Linux servers are often administered remotely using SSH by connecting to an OpenSSH server, which is the default SSH server software used within Ubuntu, Debian, CentOS, FreeBSD, and most other Linux/BSD-based systems. Significant effort is put into securing the server-side aspect of SSH, as SSH acts as the entry into your server.

      However, it is also important to consider security on the client-side, such as OpenSSH client.

      OpenSSH client is the “client” side of SSH, also known as the ssh command. You can learn more about the SSH client-server model in SSH Essentials: Working with SSH Servers, Clients, and Keys.

      When hardening SSH at the server side, the primary objective is to make it harder for malicious actors to access your server. However, hardening at the client side is very different, as instead you are working to defend and protect your SSH connection and client from various different threats, including:

      • Attackers on the network, known as “person-in-the-middle” attacks.
      • Compromised or malicious servers sending malformed data packets, nefarious control sequences, or large amounts of data to overload your client.
      • Human error, such as mistyping server addresses or configuration values.

      In this tutorial, you will harden your OpenSSH client in order to help ensure that outgoing SSH connections are as secure as possible.

      Prerequisites

      To complete this tutorial, you will need:

      • A device that you use as an SSH client, for example:

      • An SSH server that you want to connect to, for example:

        • A cloud server
        • A public service such as GitHub or GitLab
        • A third-party device that you are permitted to access

      Once you have these ready, log in to your SSH client device as a non-root user to begin.

      Step 1 — General Hardening

      In this first step, you will implement some initial hardening configurations in order to improve the overall security of your SSH client.

      The exact hardening configuration that is most suitable for your client depends heavily on your own threat model and risk threshold. However, the configuration described in this step is a general, all-round secure configuration that should suit the majority of users.

      Many of the hardening configurations for OpenSSH client are implemented using the global OpenSSH client configuration file, which is located at /etc/ssh/ssh_config. In addition to this, some configurations may also be set using the local SSH configuration file for your user, located at ~/.ssh/config.

      Before continuing with this tutorial, it is recommended to take a backup of both of these files, so that you can restore them in the unlikely event that something goes wrong.

      Take a backup of the files using the following commands:

      • sudo cp /etc/ssh/ssh_config /etc/ssh/ssh_config.bak
      • cp ~/.ssh/config ~/.ssh/config.bak

      This will save a backup copy of the files in their default location, but with the .bak extension added.

      Note that your local SSH configuration file (~/.ssh/config) may not exist if you haven’t used it in the past. If this is the case, it can be safely ignored for now.

      You can now open the global configuration file using your favorite text editor to begin implementing the initial hardening measures:

      • sudo nano /etc/ssh/ssh_config

      Note: The OpenSSH client configuration file includes many default options and configurations. Depending on your existing client setup, some of the recommended hardening options may already have been set.

      When editing your configuration file, some options may be commented out by default using a single hash character (#) at the start of the line. To edit these options, or have the commented option be recognized, you’ll need to uncomment them by removing the hash.

      Firstly, you should disable X11 display forwarding over SSH by setting the following options:

      /etc/ssh/ssh_config

      ForwardX11 no
      ForwardX11Trusted no
      

      X11 forwarding allows for the display of remote graphical applications over an SSH connection, however this is rarely used in practice. By disabling it, you can prevent potentially malicious or compromised servers from attempting to forward an X11 session to your client, which in some cases can allow for filesystem permissions to be bypassed, or for local keystrokes to be monitored.

      Next, you can consider disabling SSH tunneling. SSH tunneling is quite widely used, so you may need to keep it enabled. However, if it isn’t required for your particular setup, you can safely disable it as a further hardening measure:

      /etc/ssh/ssh_config

      Tunnel no
      

      You should also consider disabling SSH agent forwarding if it isn’t required, in order to prevent servers from requesting to use your local SSH agent to authenticate onward SSH connections:

      /etc/ssh/ssh_config

      ForwardAgent no
      

      In the majority of cases, your SSH client will be configured to use password authentication or public-key authentication when connecting to servers. However, OpenSSH client also supports other authentication methods, some of which are enabled by default. If these are not required, they can be disabled to further reduce the potential attack surface of your client:

      /etc/ssh/ssh_config

      GSSAPIAuthentication no
      HostbasedAuthentication no
      

      If you’d like to know more about some of the additional authentication methods available within SSH, you may wish to review these resources:

      OpenSSH client allows you to automatically pass custom environment variables when connecting to servers, for example, to set a language preference or configure terminal settings. However, if this isn’t required in your setup, you can prevent any variables being sent by ensuring that the SendEnv option is commented out or completely removed:

      /etc/ssh/ssh_config

      # SendEnv
      

      Finally, you should ensure that strict host key checking is enabled, to ensure that you are appropriately warned when the host key/fingerprint of a remote server changes, or when connecting to a new server for the first time:

      /etc/ssh/ssh_config

      StrictHostKeyChecking ask
      

      This will prevent you from connecting to a server when the known host key has changed, which could mean that the server has been rebuilt or upgraded, or could be indicative of an ongoing person-in-the-middle attack.

      When connecting to a new server for the first time, your SSH client will ask you whether you want to accept the host key and save it in your ~/.ssh/known_hosts file. It’s important that you verify the host key before accepting it, which usually involves asking the server administrator or browsing the documentation for the service (in the case of GitHub/GitLab and other similar services).

      Save and exit the file.

      Now that you’ve completed your initial configuration file hardening, you should validate the syntax of your new configuration by running SSH in test mode:

      You can substitute the . with any hostname to test/simulate any settings contained within Match or Host blocks.

      If your configuration file has a valid syntax, the options that will apply to that specific connection will be printed out. In the event of a syntax error, there will be an output describing the issue.

      You do not need to restart any system services for your new configuration to take effect, although existing SSH sessions will need to be re-established if you want them to inherit the new settings.

      In this step, you completed some general hardening of your OpenSSH client configuration file. Next, you’ll restrict the ciphers that are available for use in SSH connections.

      Step 2 — Restricting Available Ciphers

      Next, you will configure the cipher suites available within your SSH client to disable support for those that are deprecated/legacy.

      Begin by opening your global configuration file in your text editor:

      • sudo nano /etc/ssh/ssh_config

      Next, ensure that the existing Ciphers configuration line is commented out by prefixing it with a single hash (#).

      Then, add the following to the top of the file:

      /etc/ssh/ssh_config

      Ciphers -arcfour*,-*cbc
      

      This will disable the legacy Arcfour ciphers, as well as all ciphers using Cipher Block Chaining (CBC), which is no longer recommended for use.

      If there is a requirement to connect to systems that only support these legacy ciphers, you can explicitly re-enable the required ciphers for specific hosts by using a Match block. For example, to enable the 3des-cbc cipher for a specific legacy host, the following configuration could be used:

      /etc/ssh/ssh_config

      Match host legacy-server.your-domain
        Ciphers +3des-cbc
      

      Save and exit the file.

      Finally, as you did in Step 1, you may wish to test your SSH client configuration again to check for any potential errors:

      If you have added a Match block to enable legacy ciphers for a specific host, you can also specifically target that configuration during the test by specifying the associated host address:

      • ssh -G legacy-server.your-domain

      You’ve secured the ciphers available to your SSH client. Next, you will review the access permissions for files used by your SSH client.

      Step 3 — Securing Configuration File and Private Key Permissions

      In this step, you’ll lock down the permissions for your SSH client configuration files and private keys to help prevent accidental or malicious changes, or private key disclosure. This is especially useful when using a shared client device between multiple users.

      By default on a fresh installation of Ubuntu, the OpenSSH client configuration file(s) are configured so that each user can only edit their own local configuration file (~/.ssh/config), and sudo/administrative access is required to edit the system-wide configuration (/etc/ssh/ssh_config).

      However, in some cases, especially on systems that have been in existence for a long time, these configuration file permissions may have been accidentally modified or adjusted, so it’s best to reset them to make sure that the configuration is secure.

      You can begin by checking the current permissions value for the system-wide OpenSSH client configuration file using the stat command, which you can use to show the status or files and/or filesystem objects:

      • stat -c "%a %A %U:%G" /etc/ssh/ssh_config

      You use the -c argument to specify a custom output format.

      Note: On some operating systems, such as macOS, you will need to use the -f option to specify a custom format rather than -c.

      In this case, the %A %a %U:%G option will print the permissions for the file in octal and human-readable format, as well as the user/group that owns the file.

      This will output something similar to the following:

      Output

      644 -rw-r--r-- root:root

      In this case, the permissions are correct, root owns the file entirely, and only root has permission to write to/modify it.

      Note: If you’d like to refresh your knowledge on Linux permissions before continuing, you may wish to review An Introduction to Linux Permissions.

      However, if your own output is different, you should reset the permissions back to the default using the following commands:

      • sudo chown root:root /etc/ssh/ssh_config
      • sudo chmod 644 /etc/ssh/ssh_config

      If you repeat the stat command from earlier in this step, you will now receive the correct values for your system-wide configuration file.

      Next, you can carry out the same checks for your own local SSH client configuration file, if you have one:

      • stat -c "%a %A %U:%G" ~/.ssh/config

      This will output something similar to the following:

      Output

      644 -rw--r--r-- user:user

      If the permissions for your own client configuration file permissions are any different, you should reset them using the following commands, similarly to earlier in the step:

      • chown user:user ~/.ssh/config
      • chmod 644 ~/.ssh/config

      Next, you can check the permissions for each of the SSH private keys that you have within your ~/.ssh directory, as these files should only be accessible by yourself, and not any other users on the system.

      Begin by printing the current permission and ownership values for each private key:

      • stat -c "%a %A %U:%G" ~/.ssh/id_rsa

      This will output something similar to the following:

      Output

      600 -rw------- user:user

      It is extremely important that you properly lock down the permissions for your private key files, as failing to do so could allow other users of your device to steal them and access the associated servers or remote user accounts.

      If the permissions aren’t properly configured, use the following commands on each private key file to reset them to the secure defaults:

      • chown user:user ~/.ssh/id_rsa
      • chmod 600 ~/.ssh/id_rsa

      In this step, you assessed and locked down the file permissions for your SSH client configuration files and private keys. Next, you will implement an outbound allowlist to limit which servers your client is able to connect to.

      Step 4 — Restricting Outgoing Connections Using a Host Allowlist

      In this final step, you will implement an outgoing allowlist in order to restrict the hosts that your SSH client is able to connect to. This is especially useful for shared/multi-user systems, as well as SSH jump hosts or bastion hosts.

      This security control is specifically designed to help protect against human error/mistakes, such as mistyped server addresses or hostnames. It can be easily bypassed by the user by editing their local configuration file, and so isn’t designed to act as a defense against malicious users/actors.

      If you want to restrict outbound connections at the network level, the correct way to do this is using firewall rules. This is beyond the scope of this tutorial, but you can check out UFW Essentials: Common Firewall Rules and Commands.

      However, if you want to add some additional fail-safes, then this security control may be of benefit to you.

      It works by using a wildcard rule within your SSH client configuration file to null route all outbound connections, apart from those to specific addresses or hostnames. This means that if you were ever to accidentally mistype a server address, or attempt to connect to a server that you’re not supposed to, the request would be stopped immediately, giving you the opportunity to realize your mistake and take corrective action.

      You can apply this at either the system-level (/etc/ssh/ssh_config) or using your local user configuration file (~/.ssh/config). In this example, we will use the local user configuration file.

      Begin by opening the file, creating it if it doesn’t already exist:

      At the bottom of the file, add the following content, substituting in your own list of allowed IP addresses and hostnames:

      ~/.ssh/config

      Match host !203.0.113.1,!192.0.2.1,!server1.your-domain,!github.com,*
        Hostname localhost
      

      You must prefix IP addresses or hostnames with an exclamation point (!), and use commas to separate each item in the list. The final list item should be a single asterisk (*) without a prefixed exclamation point.

      If you’re running an SSH server on your machine too, you may wish to use a hostname value other than localhost, as this will cause the null routed connections to be sent to your own local SSH server, which could be counterproductive or confusing. Any nullrouted hostname is acceptable, such as null, do-not-use, or disallowed-server.

      Save and close the file once you’ve made your changes.

      You can now test that the configuration is working by attempting to connect to a disallowed destination using your SSH client. For example:

      • ssh disallowed.your-domain

      If the configuration is working properly, you will immediately receive an error similar to the following:

      Output

      Cannot connect to localhost: connection refused

      However, when you attempt to connect to an allowed destination, the connection will succeed as normal.

      In this final step, you implemented some additional fail-safes to help protect against human error and mistakes when using your SSH client.

      Conclusion

      In this article you reviewed your OpenSSH client configuration and implemented various hardening measures.

      This will have improved the security of your outgoing SSH connections, as well as helping to ensure that your local configuration files cannot be accidentally or maliciously modified by other users.

      You may wish to review the manual pages for OpenSSH client and its associated configuration file to identify any potential further tweaks that you want to make:

      Finally, if you want to harden OpenSSH at the server side too, check out How To Harden OpenSSH on Ubuntu 18.04.



      Source link

      Härten von OpenSSH unter Ubuntu 18.04


      Der Autor wählte die Electronic Frontier Foundation Inc, um eine Spende im Rahmen des Programms Write for DOnations zu erhalten.

      Einführung

      Linux-Server werden oft über SSH aus der Ferne verwaltet, indem eine Verbindung mit einem OpenSSH-Server hergestellt wird. Das ist die SSH-Serversoftware, die in Ubuntu, Debian, CentOS, FreeBSD und den meisten anderen Linux/BSD-basierten Systemen verwendet wird.

      OpenSSH-Server ist die Serverseite von SSH, auch als SSH-Daemon oder sshd bekannt. Sie können über den OpenSSH-Client – den Befehl ssh – eine Verbindung zu einem OpenSSH-Server herstellen. Weitere Informationen über das Client-Server-Modell von SSH finden Sie in SSH-Grundlagen: Arbeiten mit SSH-Servern, Clients und Schlüsseln. Eine gute Sicherung Ihres OpenSSH-Servers ist sehr wichtig, da er als Eingangstür oder Zugang zu Ihrem Server fungiert.

      In diesem Tutorial härten Sie Ihren OpenSSH-Server durch verschiedene Konfigurationsoptionen, damit der Remotezugriff auf Ihren Server so sicher wie möglich ist.

      Voraussetzungen

      Um diesem Tutorial zu folgen, benötigen Sie:

      Sobald Sie diese zur Verfügung haben, melden Sie sich zunächst als non-root user auf Ihrem Server an.

      Schritt 1 — Allgemeines Härten

      In diesem ersten Schritt implementieren Sie einige anfängliche Härtungskonfigurationen, um die allgemeine Sicherheit Ihres SSH-Servers zu verbessern.

      Die für Ihren eigenen Server am besten geeignete Härtungskonfiguration hängt stark von Ihrem eigenen Gefahrenmodell und Ihrer Risikoschwelle ab. Die in diesem Schritt verwendete Konfiguration ist jedoch eine generell sichere Konfiguration, die für die Mehrheit der Server geeignet ist.

      Viele der von Ihnen implementierten Härtungskonfigurationen für OpenSSH verwenden die standardmäßige Konfigurationsdatei des OpenSSH-Servers, die sich unter /etc/ssh/sshd_config befindet. Bevor Sie mit diesem Tutorial fortfahren, empfiehlt sich ein Backup Ihrer vorhandenen Konfigurationsdatei, damit Sie sie in dem unwahrscheinlichen Fall, dass etwas schiefgeht, wiederherstellen können.

      Nehmen Sie mit dem folgenden Befehl ein Backup der Datei vor:

      • sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

      Dadurch wird eine Sicherungskopie der Datei unter /etc/ssh/sshd_config.bak. gespeichert.

      Bevor Sie Ihre Konfigurationsdatei bearbeiten, können Sie die aktuell festgelegten Optionen überprüfen. Dazu führen Sie folgenden Befehl aus:

      Dadurch wird OpenSSH-Server im erweiterten Testmodus ausgeführt, was die vollständige Konfigurationsdatei validiert und die effektiven Konfigurationswerte ausgibt.

      Sie können die Konfigurationsdatei nun mit Ihrem bevorzugten Texteditor öffnen, um mit der Implementierung der anfänglichen Härtungsmaßnahmen zu beginnen:

      • sudo nano /etc/ssh/sshd_config

      Anmerkung: Die Konfigurationsdatei des OpenSSH-Servers enthält viele standardmäßige Optionen und Konfigurationen. Je nach Ihrer vorhandenen Serverkonfiguration wurden möglicherweise bereits einige der Härtungsoptionen festgelegt.

      Bei der Bearbeitung Ihrer Konfigurationsdatei können standardmäßig einige Optionen mit einem einzelnen Hash-Zeichen (#) am Anfang der Zeile auskommentiert werden. Um diese Optionen zu bearbeiten oder die kommentierte Option anerkennen zu lassen, müssen Sie sie unkommentieren, indem Sie das Hash entfernen.

      Deaktivieren Sie zunächst die Anmeldung über SSH als root-Benutzer durch Festlegen der folgenden Option:

      sshd_config

      PermitRootLogin no
      

      Das ist sehr vorteilhaft, da es einen potenziellen Angreifer daran hindert, sich direkt als root anzumelden. Das unterstützt zudem gute betriebliche Sicherheitspraktiken wie das Operieren als nicht privilegierter Benutzer und die Verwendung von sudo, um Berechtigungen nur dann auszuweiten, wenn es unbedingt erforderlich ist.

      Als Nächstes können Sie die maximale Anzahl der Authentifizierungsversuche für eine bestimmte Anmeldesitzung begrenzen, indem Sie Folgendes konfigurieren:

      sshd_config

      MaxAuthTries 3
      

      Für die meisten Einstellungen ist ein Standardwert von 3 akzeptabel. Sie können diesen jedoch je nach Ihrer eigenen Risikoschwelle höher oder niedriger festlegen.

      Bei Bedarf können Sie auch eine reduzierte Anmeldefrist festlegen. Das ist die Zeitspanne, in der ein Benutzer die Authentifizierung abschließen muss, nachdem er sich mit Ihrem SSH-Server verbunden hat:

      sshd_config

      LoginGraceTime 20
      

      Die Konfigurationsdatei gibt diesen Wert in Sekunden an.

      Eine Einstellung auf einen niedrigeren Wert hilft, bestimmte Denial-of-Service-Angriffe zu verhindern, bei denen mehrere Authentifizierungssitzungen für einen längeren Zeitraum offen gehalten werden.

      Wenn Sie SSH-Schlüssel für die Authentifizierung konfiguriert haben anstatt Passwörter zu verwenden, deaktivieren Sie die SSH-Passwortauthentifizierung, um zu verhindern, dass geleakte Benutzerpasswörter einem Angreifer ermöglichen, sich anzumelden:

      sshd_config

      PasswordAuthentication no
      

      Als eine weitere Härtungsmaßnahme in Bezug auf Passwörter können Sie bei Bedarf auch die Authentifizierung mit leeren Passwörtern deaktivieren. Dadurch wird die Anmeldung verhindert, wenn das Passwort eines Benutzers auf einen blanken oder leeren Wert gesetzt ist:

      sshd_config

      PermitEmptyPasswords no
      

      In den meisten Anwendungsfällen wird SSH mit der Authentifizierung mit öffentlichen Schlüsseln als die einzige in Gebrauch befindliche Authentifizierungsmethode konfiguriert. Jedoch unterstützt OpenSSH-Server auch viele andere Authentifizierungsmethoden, von denen einige standardmäßig aktiviert sind. Wenn diese nicht erforderlich sind, können Sie sie deaktivieren, um die Angriffsoberfläche Ihres SSH-Servers weiter zu reduzieren:

      sshd_config

      ChallengeResponseAuthentication no
      KerberosAuthentication no
      GSSAPIAuthentication no
      

      Wenn Sie mehr über einige der in SSH verfügbaren zusätzlichen Authentifizierungsmethoden erfahren möchten, stehen Ihnen diese Ressourcen zur Verfügung:

      X11-Forwarding ermöglicht die Anzeige von entfernten grafischen Anwendungen über eine SSH-Verbindung, was jedoch selten in der Praxis verwendet wird. Es wird empfohlen, diese zu deaktivieren, wenn sie auf Ihrem Server nicht benötigt wird:

      sshd_config

      X11Forwarding no
      

      OpenSSH-Server ermöglicht es Verbindungsclients, benutzerdefinierte Umgebungsvariablen zu übergeben, d. h. einen $PATH festzulegen oder Terminaleinstellungen zu konfigurieren. Wie das X11-Forwarding werden diese jedoch generell nicht verwendet, sodass sie in den meisten Fällen deaktiviert werden können:

      sshd_config

      PermitUserEnvironment no
      

      Wenn Sie diese Option konfigurieren möchten, sollten Sie dabei sicherstellen, alle Referenzen zu AcceptEnv auszukommentieren, indem Sie am Anfang der Zeile ein Hash (#) hinzufügen.

      Als Nächstes können Sie verschiedene sonstige Optionen bezüglich Tunneling und Forwarding deaktivieren, wenn Sie diese nicht auf Ihrem Server verwenden:

      sshd_config

      AllowAgentForwarding no
      AllowTcpForwarding no
      PermitTunnel no
      

      Schließlich können Sie das standardmäßig aktivierte ausführliche SSH-Banner deaktivieren, da es verschiedene Informationen zu Ihrem System anzeigt, darunter die Betriebssystemversion:

      sshd_config

      DebianBanner no
      

      Beachten Sie, dass diese Option wahrscheinlich nicht in der Konfigurationsdatei vorhanden ist, sodass Sie sie möglicherweise manuell hinzufügen müssen. Speichern und schließen Sie die Datei, sobald Sie fertig sind.

      Validieren Sie nun die Syntax Ihrer neuen Konfiguration, indem Sie sshd im Testmodus ausführen:

      Wenn Ihre Konfigurationsdatei eine gültige Syntax hat, gibt es keine Ausgabe. Im Falle eines Syntaxfehlers gibt es eine Ausgabe, die das Problem beschreibt.

      Wenn Sie mit Ihrer Konfigurationsdatei zufrieden sind, können Sie sshd neu laden, um die neuen Einstellungen anzuwenden:

      In diesem Schritt haben Sie eine allgemeine Härtung der Konfigurationsdatei Ihres OpenSSH-Servers vorgenommen. Als Nächstes implementieren Sie eine Zulassungsliste für IP-Adressen, um weiter zu beschränken, wer sich bei Ihrem Server anmelden kann.

      Schritt 2 — Implementieren einer IP-Adressen-Zulassungsliste

      Sie können IP-Adressen-Zulassungslisten verwenden, um die Benutzer zu beschränken, die berechtigt sind, sich bei Ihrem Server auf Bais der einzelnen IP-Adressen anzumelden. In diesem Schritt konfigurieren Sie eine IP-Zulassungsliste für Ihren OpenSSH-Server.

      In vielen Fällen melden Sie sich nur von einer kleinen Anzahl bekannter, vertrauenswürdiger IP-Adressen auf Ihrem Server an. Beispiele sind Ihre private Internetverbindung, eine gemeinschaftliche VPN-Anwendung oder eine statische Jump Box oder ein statischer Bastion Host in einer Datenzentrale.

      Durch die Implementierung einer IP-Adressen-Zulassungsliste können Sie sicherstellen, dass sich Personen nur über eine der vorab zugelassenen IP-Adressen anmelden. Dadurch wird das Risiko eines unerwünschten Zugriffs in dem Fall, dass Ihre privaten Schlüssel und/oder Passwörter geleaked wurden, erheblich reduziert.

      Anmerkung: Bitte achten Sie darauf, die richtigen IP-Adressen zu identifizieren, die Sie Ihrer Zulassungsliste hinzufügen möchten, und stellen Sie sicher, dass es sich dabei nicht um schwebende oder dynamische Adressen handelt, die sich regelmäßig ändern können, wie es beispielsweise bei Internetdienstanbietern für Verbraucher häufig der Fall ist.

      Sie können die IP-Adresse identifizieren, mit der Sie sich derzeit mit Ihrem Server verbinden, indem Sie den Befehl w verwenden:

      Sie sehen eine Ausgabe, die der folgenden ähnelt:

      Output

      14:11:48 up 2 days, 12:25, 1 user, load average: 0.00, 0.00, 0.00 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT your_username pts/0 203.0.113.1 12:24 1.00s 0.20s 0.00s w

      Finden Sie Ihr Benutzerkonto in der Liste und notieren Sie sich die IP-Adresse der Verbindung. Hier verwenden wir die Beispiel-IP 203.0.113.1

      Um mit der Implementierung Ihrer IP-Adressen-Zulassungsliste zu beginnen, öffnen Sie die Konfigurationsdatei des OpenSSH-Servers mit Ihrem bevorzugten Texteditor:

      • sudo nano /etc/ssh/sshd_config

      Sie können IP-Adressen-Zulassungslisten mit der Konfigurationsanweisung AllowUsers implementieren, die Benutzerauthentifizierungen auf Basis des Benutzernamens und/oder der IP-Adresse beschränkt.

      Ihre eigenen Systemeinstellungen und -anforderungen bestimmen, welche spezifische Konfiguration am besten geeignet ist. Die folgenden Beispiele helfen Ihnen dabei, die am besten geeignete zu identifizieren:

      • Beschränken aller Benutzer auf eine bestimmte IP-Adresse:
      AllowUsers *@203.0.113.1
      
      AllowUsers *@203.0.113.0/24
      
      • Beschränken aller Benutzer auf einen bestimmten IP-Adressbereich (mit Wildcards):
      AllowUsers *@203.0.113.*
      
      • Beschränken aller Benutzer auf mehrere spezifische IP-Adressen und -bereiche:
      AllowUsers *@203.0.113.1 *@203.0.113.2 *@192.0.2.0/24 *@172.16.*.1
      
      • Deaktivieren aller Benutzer mit Ausnahme von benannten Benutzern von bestimmten IP-Adressen:
      AllowUsers sammy@203.0.113.1 alex@203.0.113.2<^>
      
      • Beschränken eines bestimmten Benutzers auf eine bestimmte IP-Adresse, während es allen anderen Benutzern weiterhin erlaubt ist, sich ohne Beschränkungen anzumelden:
      Match User ashley
        AllowUsers ashley@203.0.113.1
      

      Warnung: In einer OpenSSH-Konfigurationsdatei gelten alle Konfigurationen unter einem Match-Block nur für Verbindungen, die den Kriterien entsprechen, unabhängig von Einrückung oder Zeilenumbrüchen. Daher müssen Sie vorsichtig sein und sicherstellen, dass Konfigurationen, die zur globalen Anwendung bestimmt sind, nicht versehentlich in einen Match-Block eingestellt werden. Um das zu vermeiden, wird empfohlen, alle Match-Blocks an das untere Ende Ihrer Konfigurationsdatei zu setzen.

      Wenn Sie Ihre Konfiguration abgeschlossen haben, fügen Sie sie unten in Ihre OpenSSH-Server-Konfigurationsdatei ein:

      sshd_config

      AllowUsers *@203.0.113.1
      

      Speichern und schließen Sie die Datei. Anschließend testen Sie Ihre Konfigurationssyntax:

      Wenn keine Fehler gemeldet werden, können Sie OpenSSH-Server neu laden, um Ihre Konfiguration anzuwenden:

      In diesem Schritt haben Sie eine IP-Adressen-Zulassungsliste auf Ihrem OpenSSH-Server implementiert. Als Nächstes beschränken Sie die Shell eines Benutzers, um die Befehle, die er verwenden darf, einzugrenzen.

      Schritt 3 — Beschränken der Shell eines Benutzers

      In diesem Schritt sehen Sie sich die verschiedenen Optionen zur Beschränkung der Shell eines SSH-Benutzers an.

      Neben dem Remote-Shell-Zugriff eignet sich SSH auch hervorragend für die Übertragung von Dateien und anderen Daten, z. B. über SFTP. Es kann jedoch sein, dass Sie Benutzern nicht immer vollständigen Shell-Zugriff gewähren möchten, wenn sie nur in der Lage sein müssen, Datenübertragungen durchzuführen.

      Es gibt mehrere Konfigurationen im OpenSSH-Server, mit denen Sie die Shell-Umgebung für bestimmte Benutzer beschränken können. In dieser Anleitung werden wird diese zum Beispiel verwenden, um Nur-SFTP-Benutzer zu erstellen.

      Zunächst können Sie die Shell /usr/sbin/nologin verwenden, um interaktive Anmeldungen für bestimmte Benutzerkonten zu deaktivieren, während nicht-interaktive Sitzungen wie Dateiübertragungen, Tunneling usw. weiterhin funktionieren können.

      Um einen neuen Benutzer mit der nologin-Shell zu erstellen, verwenden Sie folgenden Befehl:

      • sudo adduser --shell /usr/sbin/nologin alex

      Alternativ können Sie die Shell eines vorhandenen Benutzers zu nologin ändern:

      • sudo usermod --shell /usr/sbin/nologin sammy

      Wenn Sie dann versuchen, sich interaktiv als einen dieser Benutzer anzumelden, wird die Anfrage abgelehnt:

      Sie sehen eine Ausgabe mit einer Meldung, die der folgenden ähnelt:

      Output

      This account is currently not available.

      Trotz der Ablehnungsmeldung zu interaktiven Anmeldungen werden andere Aktionen wie Dateiübertragungen weiterhin zugelassen.

      Als Nächstes sollten Sie die Verwendung der nologin-Shell mit einigen zusätzlichen Konfigurationsoptionen kombinieren, um die entsprechenden Benutzerkonten weiter zu beschränken.

      Öffnen Sie zunächst die Konfigurationsdatei des OpenSSH-Servers in Ihrem bevorzugten Texteditor:

      • sudo nano /etc/ssh/sshd_config

      Es gibt zwei Konfigurationsoptionen, die Sie gemeinsam implementieren können, um ein streng beschränktes Nur-SFTP-Benutzerkonto zu erstellen: ForceCommand internal-sftp und ChrootDirectory.

      Die Option ForceCommand innerhalb OpenSSH-Server zwingt einen Benutzer, einen bestimmten Befehl bei der Anmeldung auszuführen. Das kann für bestimmte Machine-to-Machine-Kommunikationen nützlich sein, oder um ein bestimmtes Programm zwangsweise zu starten.

      In diesem Fall ist der Befehl internal-sftp jedoch besonders nützlich. Dabei handelt es sich um eine spezielle Funktion des OpenSSH-Servers, die an Ort und Stelle einen grundlegenden SFTP-Daemon startet, der keine unterstützenden Systemdateien oder Konfiguration benötigt.

      Idealerweise kombinieren Sie diese mit der Option ChrootDirectory, die das erkannte Root-Verzeichnis für einen bestimmten Benutzer aufhebt bzw. ändert, wodurch dieser im Wesentlichen auf ein bestimmtes Verzeichnis im System beschränkt wird.

      Fügen Sie dazu den folgenden Konfigurationsabschnitt in Ihre OpenSSH-Server-Konfigurationsdatei ein:

      sshd_config

      Match User alex
        ForceCommand internal-sftp
        ChrootDirectory /home/alex/
      

      Warnung: Wie in Schritt 2 erwähnt, gelten in einer OpenSSH-Konfigurationsdatei alle Konfigurationen unter einem Match-Block nur für Verbindungen, die den Kriterien entsprechen, unabhängig von Einrückung oder Zeilenumbrüchen. Daher müssen Sie vorsichtig sein und sicherstellen, dass Konfigurationen, die zur globalen Anwendung bestimmt sind, nicht versehentlich in einen Match-Block eingestellt werden. Um das zu vermeiden, wird empfohlen, alle Match-Blocks an das untere Ende Ihrer Konfigurationsdatei zu stellen.

      Speichern und schließen Sie Ihre Konfigurationsdatei, und testen Sie die Konfiguration erneut:

      Wenn es keine Fehler gibt, können Sie dann Ihre Konfiguration anwenden:

      Dadurch wurde eine robuste Konfiguration für den Benutzer alex erstellt, bei der interaktive Anmeldungen deaktiviert sind, und alle SFTP-Aktivitäten sind auf das Stammverzeichnis des Benutzers beschränkt. Aus der Perspektive des Benutzers ist das Verzeichnis des Systems – d. h. / – ihr Stammverzeichnis. Er ist nicht in der Lage, das Dateisystem nach oben zu durchlaufen, um auf andere Bereiche zuzugreifen.

      Sie haben die nologin-Shell für einen Benutzer implementiert und dann eine Konfiguration erstellt, um den SFTP-Zugriff auf ein bestimmtes Verzeichnis zu beschränken.

      Schritt 4 — Erweiterte Härtung

      In diesem abschließenden Schritt implementieren Sie verschiedene zusätzliche Härtungsmaßnahmen, um den Zugriff auf Ihren SSH-Server so sicher wie möglich zu machen.

      Eine weniger bekannte Funktion des OpenSSH-Servers ist die Fähigkeit, Beschränkungen auf einer Pro-Schlüssel-Basis aufzuerlegen. Das sind Beschränkungen, die nur für bestimmte öffentliche Schlüssel gelten, die in der Datei .ssh/authorized_keys vorhanden sind. Das ist besonders nützlich, um den Zugriff bei Machine-to-Machine-Sitzungen zu kontrollieren und um auch Nicht-Sudo-Benutzern zu ermöglichen, die Beschränkungen für das eigene Benutzerkonto zu kontrollieren.

      Sie können die meisten dieser Beschränkungen auf System- oder Benutzerebene anwenden. Es ist jedoch immer noch von Vorteil, sie auch auf der Schlüsselebene zu implementieren, um eine tief greifende Abwehr und eine zusätzliche Ausfallsicherheit im Falle versehentlicher systemweiter Konfigurationsfehler zu gewährleisten.

      Anmerkung: Sie können diese zusätzlichen Sicherheitskonfigurationen nur implementieren, wenn Sie die SSH-Authentifizierung mit öffentlichen Schlüsseln verwenden. Wenn Sie nur Passwort-Authentifizierung verwenden oder über eine komplexere Einrichtung wie eine-SSH-Zertifizierungsstelle verfügen, können Sie diese leider nicht nutzen.

      Öffnen Sie zunächst Ihre .ssh/authorized_keys-Datei in Ihrem bevorzugten Texteditor:

      • nano ~/.ssh/authorized_keys

      Anmerkung: Da diese Konfigurationen auf einer Pro-Schlüssel-Basis gelten, müssen Sie jeden einzelnen Schlüssel, für den diese gelten sollen, innerhalb jeder einzelnen authorized_keys-Datei bearbeiten, für alle Benutzer auf Ihrem System. Normalerweise müssen Sie nur einen Schlüssel/eine Datei bearbeiten. aber es ist die Überlegung wert, wenn Sie über ein komplexes Mehrbenutzersystem verwenden.

      Nach dem Öffnen Ihrer authorized_keys-Datei sehen Sie, dass jede Zeile einen öffentlichen SSH-Schlüssel enthält, der höchstwahrscheinlich mit etwas Ähnlichem wie ssh-rsa AAAB... beginnt. Weitere Konfigurationsoptionen können am Anfang der Zeile hinzugefügt werden; diese gelten nur für erfolgreiche Authentifizierungen mit diesem bestimmten öffentlichen Schlüssel.

      Folgende Beschränkungsoptionen stehen zur Verfügung:

      • no-agent-forwarding: Deaktivieren des SSH-Agent-Forwardings.
      • no-port-forwarding: Deaktivieren des Port-Forwardings.
      • no-pty: Deaktivieren der Fähigkeit, einen tty zuzuweisen (d. h. eine Shell zu starten).
      • no-user-rc: Verhindern der Ausführung der Datei ~/.ssh/rc.
      • no-X11-forwarding: Deaktivieren des X11-Display-Forwardings.

      Sie können diese anwenden, um bestimmte SSH-Funktionen für bestimmte Schlüssel zu deaktivieren. Um zum Beispiel Agent-Forwarding und X11-Forwarding für einen Schlüssel zu deaktivieren, verwenden Sie die folgende Konfiguration:

      ~/.ssh/authorized_keys

      no-agent-forwarding,no-X11-forwarding ssh-rsa AAAB...
      

      Standardmäßig arbeiten diese Konfigurationen nach der Methode „standardmäßig zulassen, ausnahmsweise blockieren“. Es ist jedoch auch möglich, „standardmäßig blockieren, ausnahmsweise zulassen“ zu verwenden, was zur Gewährleistung der Sicherheit generell vorzuziehen ist.

      Hierzu können Sie die Option restrict verwenden, die implizit alle SSH-Funktionen für den spezifischen Schlüssel ablehnt und verlangt, dass diese nur dort neu aktiviert werden, wo sie unbedingt erforderlich sind. Sie können Funktionen mit denselben zuvor in dieser Anleitung beschriebenen Konfigurationsoptionen neu aktivieren, jedoch ohne das Präfix no-.

      Um z. B. alle SSH-Funktionen außer das X11-Display-Forwarding für einen bestimmten Schlüssel zu deaktivieren, können Sie die folgende Konfiguration verwenden:

      ~/.ssh/authorized_keys

      restrict,X11-forwarding ssh-rsa AAAB...
      

      Ziehen Sie auch die Verwendung der Option command in Betracht, die der in Schritt 3 beschriebenen Option ForceCommand sehr ähnelt. Sie bietet keinen direkten Vorteil, wenn Sie bereits ForceCommand nutzen, dient aber als eine gute tief greifende Abwehr für den unwahrscheinlichen Fall, dass die Hauptkonfigurationsdatei des OpenSSH-Servers überschrieben, bearbeitet etc. wird.

      Um beispielsweise Benutzer, die sich über einen bestimmten Schlüssel authentifizieren, zu zwingen, bei der Anmeldung einen bestimmten Befehl auszuführen, können Sie die folgende Konfiguration hinzufügen:

      ~/.ssh/authorized_keys

      command="top" ssh-rsa AAAB...
      

      Warnung: Die command-Konfigurationsoption fungiert lediglich als tief greifende Abwehrmethode. Sie sollte nicht als einzige Methode zur Beschränkung von Aktivitäten eines SSH-Benutzers genutzt werden, da es je nach Ihrer Arbeitsumgebung möglicherweise Wege gibt, sie zu überschreiben oder zu umgehen. Stattdessen sollten Sie die Konfiguration zusammen mit den anderen in diesem Artikel beschriebenen Kontrollen verwenden.

      Um schließlich die in Schritt 3 erstellten Pro-Schlüssel-Beschränkungen für den Nur-SFTP-Benutzer optimal zu nutzen, können Sie die folgende Konfiguration verwenden:

      ~/.ssh/authorized_keys

      restrict,command="false" ssh-rsa AAAB...
      

      Die Option restrict deaktiviert jeden interaktiven Zugriff. Die Option command="false" fungiert als zweite Verteidigungslinie für den Fall, dass die Option ForceCommand oder die nologin-Shell fehlschlagen sollten.

      Speichern und schließen Sie die Datei, um die Konfiguration anzuwenden. Diese wird sofort für alle neuen Anmeldungen wirksam. Daher müssen Sie OpenSSH nicht manuell neu laden.

      In diesem abschließenden Schritt haben Sie einige zusätzliche erweiterte Härtungsmaßnahmen für OpenSSH-Server implementiert, indem Sie die benutzerdefinierten Optionen in Ihrer .ssh/authorized_keys Datei verwendet haben.

      Zusammenfassung

      In diesem Artikel haben Sie die Konfiguration Ihres OpenSSH-Servers geprüft und verschiedene Härtungsmaßnahmen implementiert, um Ihren Server zu sichern.

      Dadurch wurde die Angriffsfläche Ihres Servers insgesamt verringert, indem nicht genutzte Funktionen deaktiviert und der Zugriff bestimmter Benutzer gesperrt wurde.

      Konsultieren Sie bei Bedarf auch die manuellen Seiten für OpenSSH-Server und die zugehörige Konfigurationsdatei, um mögliche weitere Optimierungen zu finden, die Sie eventuell vornehmen möchten.



      Source link

      Cómo endurecer OpenSSH en Ubuntu 18.04


      El autor seleccionó la Electronic Frontier Foundation Inc para recibir una donación como parte del programa Write for DOnations.

      Introducción

      Los servidores Linux suelen administrarse remotamente usando SSH mediante la conexión con un servidor OpenSSH, que es el software de servidor SSH predeterminado usado en Ubuntu, Debian, CentOS, y la mayoría de los otros sistemas basados en Linux/BSD.

      El servidor OpenSSH es la parte de servidor de SSH, también conocida como daemon SSH o sshd. Puede conectar con un servidor OpenSSH usando el cliente OpenSSH: el comando ssh. Puede obtener más información sobre el modelo cliente-servidor SSH en Puntos esenciales de SSH: Trabajar con servidores, clientes y claves SSH. Proteger de forma adecuada su servidor OpenSSH es muy importante, ya que actúa como la puerta principal o de entrada a su servidor.

      En este tutorial, endurecerá su servidor OpenSSH usando diferentes opciones de configuración para garantizar que el acceso remoto a su servidor sea tan seguro como sea posible.

      Requisitos previos

      Para completar este tutorial, necesitará lo siguiente:

      Una vez que tenga todo esto listo, para comenzar inicie sesión en su servidor como usuario no root.

      Paso 1: Endurecimiento general

      En este primer paso, implementará algunas configuraciones iniciales de endurecimiento para mejorar la seguridad general de su servidor SSH.

      La configuración de endurecimiento exacta más adecuada para su propio servidor depende en gran medida de su propio modelo de amenazas y nivel de riesgo. Sin embargo, la configuración que usará en este paso es una configuración segura general que será adecuada para la mayoría de los servidores.

      Muchas de las configuraciones de endurecimiento para OpenSSH las implementará usando el archivo de configuración estándar del servidor OpenSSH, que está ubicado en /etc/ssh/sshd_config. Antes de continuar con este tutorial, recomendamos que haga una copia de seguridad de su archivo de configuración existente, para que pueda restaurarlo en el improbable caso de que algo salga mal.

      Realice una copia de seguridad del archivo usando el siguiente comando:

      • sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

      Esto guardará una copia de seguridad del archivo en /etc/ssh/sshd_config.bak.

      Antes de editar su archivo de configuración, puede revisar las opciones que están establecidas actualmente. Para hacer esto, ejecute el siguiente comando:

      Esto ejecutará el servidor OpenSSH en modo de prueba ampliado, lo que validará el archivo de configuración completo e imprimirá los valores de configuración efectivos.

      Ahora puede abrir el archivo de configuración usando su editor de texto favorito para comenzar a implementar las medidas de endurecimiento iniciales:

      • sudo nano /etc/ssh/sshd_config

      Nota: El archivo de configuración del servidor OpenSSH incluye muchas opciones y configuraciones predeterminadas. Dependiendo de la configuración existente de su servidor, algunas de las opciones de endurecimiento recomendadas pueden haberse configurado ya.

      Cuando edite su archivo de configuración, algunas opciones pueden omitirse por defecto usando un carácter almohadilla único (#) al inicio de la línea. Para editar estas opciones, o que la opción omitida sea reconocida, deberá dejar de omitirlas eliminando la almohadilla.

      Primero, deshabilite el inicio de sesión a través de SSH como el usuario root estableciendo la siguiente opción:

      sshd_config

      PermitRootLogin no
      

      Esto es sumamente beneficioso, ya que evitará que un atacante potencial inicie sesión directamente como root. También alienta las buenas prácticas de seguridad operativas, como operar como usuario sin privilegios y usar sudo para escalar privilegios solo cuando sea absolutamente necesario.

      A continuación, puede limitar el número máximo de intentos de autenticación para una sesión de inicio de sesión concreta configurando lo siguiente:

      sshd_config

      MaxAuthTries 3
      

      Un valor estándar de 3 es aceptable para la mayoría de configuraciones, pero es posible que desee establecer esto más alto o más bajo dependiendo de su propio umbral de riesgo.

      Si es necesario, puede también establecer un periodo de gracia de inicio de sesión reducido, que es la cantidad de tiempo que un usuario tiene para completar la autenticación tras conectar inicialmente con su servidor SSH:

      sshd_config

      LoginGraceTime 20
      

      El archivo de configuración especifica este valor en segundos.

      Establecer esto a un valor inferior ayuda a evitar ciertos ataques de denegación de servicio, en los que múltiples sesiones de autenticación se mantienen abiertas durante un periodo de tiempo prolongado.

      Si ha configurado claves SSH para la autenticación, en vez de usar contraseñas, deshabilite la autenticación por contraseña SSH para evitar que las contraseñas de usuario filtradas permitan a un atacante iniciar sesión:

      sshd_config

      PasswordAuthentication no
      

      Como otra medida de endurecimiento relacionada con las contraseñas, es posible que también desee deshabilitar la autenticación con contraseñas vacías. Esto evitará los inicios de sesión si una contraseña de usuario se establece como un valor en blanco o vacío:

      sshd_config

      PermitEmptyPasswords no
      

      En la mayoría de los casos de uso, SSH se configurará con autenticación de clave pública como el único método de autenticación en uso. Sin embargo, el servidor OpenSSH también es compatible con muchos otros métodos de autenticación, algunos de los cuales están habilitados por defecto. Si estos no son necesarios, puede deshabilitarlos para reducir aún más la superficie de ataque de su servidor SSH:

      sshd_config

      ChallengeResponseAuthentication no
      KerberosAuthentication no
      GSSAPIAuthentication no
      

      Si desea obtener más información sobre otros métodos de autenticación disponibles en SSH, es posible que desee revisar estos recursos:

      El reenvío X11 permite mostrar aplicaciones gráficas remotas sobre una conexión SSH, pero esto apenas se usa en la práctica. Se recomienda deshabilitarlo si no es necesario en su servidor:

      sshd_config

      X11Forwarding no
      

      El servidor OpenSSH permite conectar clientes para pasar variables de entorno personalizadas, es decir, configurar un $PATH o configurar ajustes de terminal. Sin embargo, al igual que el reenvío X11, estos no se usan normalmente, así que pueden deshabilitarse en la mayoría de los casos:

      sshd_config

      PermitUserEnvironment no
      

      Si decide configurar esta opción, debería asegurarse de omitir cualquier referencia a AcceptEnv añadiendo una almohadilla (#) al principio de la línea.

      A continuación, puede deshabilitar varias opciones diversas relacionadas con la canalización y reenvío si no las va a usar en su servidor:

      sshd_config

      AllowAgentForwarding no
      AllowTcpForwarding no
      PermitTunnel no
      

      Finalmente, puede deshabilitar el banner textual SSH que está habilitado por defecto, ya que muestra diferentes informaciones sobre su sistema, como la versión del sistema operativo:

      sshd_config

      DebianBanner no
      

      Tenga en cuenta que esta opción probablemente no esté ya presente en el archivo de configuración, de forma que es posible que la tenga que añadir manualmente. Guarde y salga del archivo una vez que termine.

      Ahora, valide la sintaxis de su nueva configuración ejecutando sshd en modo de prueba:

      Si su archivo de configuración tiene una sintaxis válida, no habrá resultados. En el caso de que se produzca un error de sintaxis, verá un resultado describiendo el problema.

      Una vez satisfecho con su archivo de configuración, puede recargar sshd para aplicar los nuevos ajustes:

      En este paso, ha completado cierto endurecimiento general del archivo de configuración de su servidor OpenSSH. A continuación, implementará una lista de direcciones IP permitidas para restringir aún más quién puede iniciar sesión en su servidor.

      Paso 2: Implementar una lista de direcciones IP permitidas

      Puede usar listas de direcciones IP permitidas para limitar los usuarios autorizados a iniciar sesión en su servidor según la dirección IP. En este paso, configurará una lista de direcciones IP permitidas para su servidor OpenSSH.

      En muchos casos, solo iniciará sesión en su servidor desde un número pequeño de direcciones IP conocidas de confianza. Por ejemplo, la conexión a Internet de su casa, una aplicación VPN corporativa, un jump box estático o un bastion host en un centro de datos.

      Al implementar una lista de direcciones IP permitidas, puede garantizar que las personas solo podrán iniciar sesión desde una de las direcciones IP preaprobadas, reduciendo enormemente el riesgo de sufrir un problema de seguridad en caso de que sus claves o contraseñas privadas se filtren.

      Nota: Asegúrese de identificar las direcciones IP correctas que añadir a su lista, y asegúrese de que no son direcciones flotantes o dinámicas que puedan cambiar regularmente, por ejemplo como se ve a menudo en los proveedores de servicios de Internet para el consumidor.

      Puede identificar la dirección IP con la que está conectando actualmente a su servidor usando el comando w:

      Con esto, se mostrará algo similar a lo siguiente:

      Output

      14:11:48 up 2 days, 12:25, 1 user, load average: 0.00, 0.00, 0.00 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT your_username pts/0 203.0.113.1 12:24 1.00s 0.20s 0.00s w

      Busque su cuenta de usuario en la lista y anote la dirección IP de conexión. Aquí usamos la IP de ejemplo 203.0.113.1

      Para comenzar a implementar su lista de direcciones IP permitidas, abra el archivo de configuración del servidor OpenSSH en su editor de texto favorito:

      • sudo nano /etc/ssh/sshd_config

      Puede implementar listas de direcciones IP permitidas usando la directiva de configuración AllowUsers, que restringe las autenticaciones de usuarios según el nombre de usuario o la dirección IP.

      La configuración y requisitos de su sistema determinará qué configuración específica es la más apropiada. Los siguientes ejemplos ayudarán a identificar la más adecuada:

      • Restringir a todos los usuarios a una dirección IP específica:
      AllowUsers *@203.0.113.1
      
      AllowUsers *@203.0.113.0/24
      
      • Restringir a todos los usuarios a un rango específico de direcciones IP (usando comodines):
      AllowUsers *@203.0.113.*
      
      • Restringir a todos los usuarios a múltiples direcciones y rangos de IP específicos:
      AllowUsers *@203.0.113.1 *@203.0.113.2 *@192.0.2.0/24 *@172.16.*.1
      
      • No permitir a todos los usuarios excepto a los usuarios indicados desde direcciones IP específicas:
      AllowUsers sammy@203.0.113.1 alex@203.0.113.2<^>
      
      • Restringir a un usuario específico a una dirección IP específica, mientras se permite que todos los otros usuarios inicien sesión sin restricciones:
      Match User ashley
        AllowUsers ashley@203.0.113.1
      

      Advertencia: Dentro de un archivo de configuración OpenSSH, todas las configuraciones bajo un bloque Match solo se aplicarán a las conexiones que coinciden con el criterio, independientemente de la sangría o saltos de línea. Esto significa que debe tener cuidado y asegurarse de que las configuraciones destinadas a aplicarse globalmente no se pongan dentro de un bloque Match. Se recomienda poner todos los bloques Match en la parte inferior/al final de su archivo de configuración para evitar esto.

      Una vez que haya terminado su configuración, añádala a la parte inferior de su archivo de configuración del servidor OpenSSH:

      sshd_config

      AllowUsers *@203.0.113.1
      

      Guarde y cierre el archivo, y continúe a probar su sintaxis de configuración:

      Si no se reportan errores, puede volver a cargar el servidor OpenSSH para aplicar su configuración:

      En este paso, implementó una lista de direcciones IP permitidas en su servidor OpenSSH. A continuación, restringirá el shell de un usuario para limitar los comandos que se les permite usar.

      Paso 3: Restringir el shell de un usuario

      En este paso, verá las diferentes opciones para restringir el shell de un usuario SSH.

      Además de proporcionar acceso shell remoto, SSH también es ideal para transferir archivos y otros datos, por ejemplo, a través de SFTP. Sin embargo, es posible que no siempre quiera conceder acceso completo al shell a los usuarios cuando solo necesiten poder realizar transferencias de archivos.

      Existen múltiples configuraciones en el servidor OpenSSH que puede usar para restringir el entorno shell de los usuarios particulares. Por ejemplo, en este tutorial las usaremos para crear usuarios solo SFTP.

      Primero, puede usar el shell /usr/sbin/nologin para deshabilitar los inicios de sesión interactivos para ciertas cuentas de usuario, permitiendo al mismo tiempo que las sesiones no interactivas sigan funcionando, como transferencias de archivos, canalización, etc.

      Para crear un nuevo usuario con el shell nologin, utilice el siguiente comando:

      • sudo adduser --shell /usr/sbin/nologin alex

      Alternativamente, puede cambiar el shell de un usuario existente para que sea nologin:

      • sudo usermod --shell /usr/sbin/nologin sammy

      Si intenta iniciar sesión de forma interactiva como uno de estos usuarios, la solicitud se rechazará:

      Esto mostrará un resultado similar al siguiente mensaje:

      Output

      This account is currently not available.

      A pesar del mensaje de rechazo sobre los inicios de sesión interactivos, se seguirán permitiendo otras acciones como las transferencias de archivos.

      A continuación, debería combinar su uso de la shell nologin con algunas opciones de configuración adicionales para restringir aún más las cuentas de usuario relevantes.

      Comience abriendo el archivo de configuración del servidor OpenSSH en su editor de texto favorito de nuevo:

      • sudo nano /etc/ssh/sshd_config

      Hay dos opciones de configuración que puede implementar juntas para crear una cuenta de usuario solo SFTP altamente restringida: ForceCommand internal-sftp y ChrootDirectory.

      La opción ForceCommand en el servidor OpenSSH fuerza a un usuario a ejecutar un comando específico tras iniciar sesión. Esto puede ser útil para ciertas comunicaciones equipo a equipo o para iniciar de forma forzosa un programa concreto.

      Sin embargo, en este caso, el comando internal-sftp es particularmente útil. Esta es una función especial del servidor OpenSSH que inicia un daemon SFTP básico que no necesita ningún archivo de sistema o configuración de soporte.

      Esto debería combinarse idealmente con la opción ChrootDirectory, que anulará/cambiará el directorio raíz percibido para un usuario concreto, restringiéndolos esencialmente a un directorio específico en el sistema.

      Añada la siguiente sección de configuración a su archivo de configuración del servidor OpenSSH para esto:

      sshd_config

      Match User alex
        ForceCommand internal-sftp
        ChrootDirectory /home/alex/
      

      Advertencia: Como se ha indicado en el Paso 2, en un archivo de configuración OpenSSH, todas las configuraciones bajo un bloque Match solo se aplicarán a las conexiones que coinciden con el criterio, independientemente de la sangría o saltos de líneas. Esto significa que debe tener cuidado y asegurar que las configuraciones destinadas a aplicarse globalmente no se ponen dentro de un bloque Match. Se recomienda poner todos los bloques Match en la parte inferior/al final de su archivo de configuración para evitar esto.

      Guarde y cierre su archivo de configuración, y luego pruebe su configuración de nuevo:

      Si no hay errores, puede aplicar su configuración:

      Esto ha creado una configuración robusta para el usuario alex, donde los inicios de sesión interactivos se deshabilitan, y toda la actividad SFTP se restringe al directorio de inicio del usuario. Desde la perspectiva del usuario, la raíz del sistema, es decir, /, es el directorio de inicio y no podrá atravesar el sistema de archivos a otras áreas.

      Ha implementado el shell nologin para un usuario y luego ha creado una configuración para restringir el acceso SFTP a un directorio específico.

      Paso 4: Endurecimiento avanzado

      En este paso final, implementará varias medias de endurecimiento adicionales para hacer que el acceso a su servidor SSH sea tan seguro como se posible.

      Una función menos conocida del servidor OpenSSH es la capacidad para imponer restricciones según la clave, es decir, restricciones que se aplican solo a claves públicas específicas presentes en el archivo .ssh/authorized_keys. Esto es particularmente útil para controlar el acceso para las sesiones equipo a equipo, y para proporcionar la capacidad a los usuarios no sudo de controlar las restricciones para su propia cuenta de usuario.

      Puede aplicar la mayoría de estas restricciones a nivel de usuario o sistema también, sin embargo, es ventajoso implementarlas a nivel de clave también, para proporcionar defensa en profundidad y un mecanismo de seguridad adicional en caso de errores de configuración accidentales en todo el sistema.

      Nota: Solo puede implementar estas configuraciones de seguridad adicionales si está usando la autenticación SSH de clave pública. Si solo está usando la autenticación con contraseña, o tiene una configuración más compleja como una autoridad de certificado SSH, desafortunadamente estas no serán utilizables.

      Comience abriendo su archivo .ssh/autorized_keys en su editor de texto favorito:

      • nano ~/.ssh/authorized_keys

      Nota: Ya que estas configuraciones se aplican por clave, deberá editar cada clave individual en cada archivo individual authorized_keys al que desee aplicarlas, para todos los usuarios en su sistema. Normalmente, solo necesitará editar un archivo de claves, pero merece la pena considerarlo si tiene un sistema complejo multi usuario.

      Una vez que haya abierto su archivo authorized_keys, verá que cada línea contiene una clave pública SSH, que probablemente comenzará con algo como ssh-rsa AAAB.... Pueden añadirse opciones de configuración adicionales al principio de la línea, y estas solo se aplicarán para las autenticaciones correctas contra esa clave pública específica.

      Las siguientes opciones de restricción están disponibles:

      • no-agent-forwarding: Desactivar el reenvío de agente SSH.
      • no-port-forwarding: Deshabilitar el reenvío de puerto SSH.
      • no-pty: Deshabilitar la capacidad de asignar un tty (es decir, inicial un shell).
      • no-user-rc: Evitar la ejecución del archivo ~/.ssh/rc.
      • no-X11-forwarding: Deshabilitar el reenvío de pantalla X11.

      Puede aplicar estas configuraciones para deshabilitar funciones SSH específicas para claves específicas. Por ejemplo, para deshabilitar el reenvío de agente y el reenvío de X11 para una clave, usaría la siguiente configuración:

      ~/.ssh/authorized_keys

      no-agent-forwarding,no-X11-forwarding ssh-rsa AAAB...
      

      Por defecto, estas configuraciones funcionan usando una metodología “permitir por defecto, bloque por excepción”; sin embargo, también es posible usar “bloque por defecto, permitir por excepción” lo cual es generalmente preferible para garantizar la seguridad.

      Puede hacer esto usando la opción restrict, que implícitamente denegará todas las funciones SSH para la clave específica, requiriendo que se vuelvan a habilitar explícitamente solo cuando sea absolutamente necesario. Puede volver a habilitar las funciones usando las mismas opciones de configuración descritas anteriormente en este tutorial, pero sin el prefijo no-.

      Por ejemplo, para deshabilitar todas las funciones SSH para una clave concreta, aparte del reenvío de pantalla X11, puede usar la siguiente configuración:

      ~/.ssh/authorized_keys

      restrict,X11-forwarding ssh-rsa AAAB...
      

      Es posible que desee considerar usar la opción command, que es muy similar a la opción ForceCommand descrita en el Paso 3. Esto no le ofrece un beneficio directo si ya está usando ForceCommand, pero es una nueva defensa en profundidad que implementar, en el improbable evento de que se sobrescriba, edite, etc., el archivo de configuración de su servidor Open SSH principal.

      Por ejemplo, para forzar que los usuarios autentiquen contra una clave específica para ejecutar un comando específico tras el inicio de sesión, puede añadir la siguiente configuración:

      ~/.ssh/authorized_keys

      command="top" ssh-rsa AAAB...
      

      Advertencia: La opción de configuración command actúa puramente como un método de defensa en profundidad y no debería depender de ella únicamente para restringir las actividades de un usuario SSH, ya que existen potencialmente formas de anular u omitirla dependiendo de su entorno. En vez de eso, debería usar la configuración en tándem con los otros controles descritos en este artículo.

      Finalmente, para usar mejor las restricciones por clave para el usuario solo SFTP que creó en el Paso 3, puede usar la siguiente configuración:

      ~/.ssh/authorized_keys

      restrict,command="false" ssh-rsa AAAB...
      

      La opción restrict deshabilitará todo el acceso interactivo, y la opción command="false" actúa como una segunda línea de defensa en el caso de que fallaran la opción ForceCommand o el shell nologin.

      Guarde y cierre el archivo para aplicar la configuración. Esto tendrá efecto de inmediato para todos los nuevos inicios de sesión, de forma que no es necesario que vuelva a cargar OpenSSH manualmente.

      En este paso final, implementó algunas medidas de endurecimiento avanzadas adicionales para el servidor OpenSSH usando las opciones personalizadas en sus archivos .ssh/authorized_keys.

      Conclusión

      En este artículo, ha revisado la configuración de su servidor OpenSSH y ha implementado varias medidas de endurecimiento para ayudar a proteger su servidor.

      Esto reducirá la superficie general de ataque de su servidor deshabilitando las funciones no utilizadas y bloqueando el acceso por parte de usuarios específicos.

      Es posible que desee revisar las páginas del manual para el servidor OpenSSH y su archivo de configuración asociado para identificar cualquier ajuste potencial adicional que desee realizar.



      Source link