2019-07-20 10:26:52 +00:00
|
|
|
package sftpd
|
|
|
|
|
|
|
|
import (
|
2020-05-15 18:08:53 +00:00
|
|
|
"bytes"
|
2019-07-20 10:26:52 +00:00
|
|
|
"encoding/hex"
|
|
|
|
"encoding/json"
|
2022-03-24 21:03:17 +00:00
|
|
|
"errors"
|
2019-07-20 10:26:52 +00:00
|
|
|
"fmt"
|
|
|
|
"io"
|
2022-05-09 17:09:43 +00:00
|
|
|
"io/fs"
|
2019-07-20 10:26:52 +00:00
|
|
|
"net"
|
|
|
|
"os"
|
2021-07-28 22:32:55 +00:00
|
|
|
"path"
|
2019-07-20 10:26:52 +00:00
|
|
|
"path/filepath"
|
2020-10-31 10:02:04 +00:00
|
|
|
"runtime/debug"
|
2020-04-01 21:25:23 +00:00
|
|
|
"strings"
|
2022-03-31 19:49:06 +00:00
|
|
|
"sync"
|
2019-07-20 10:26:52 +00:00
|
|
|
"time"
|
|
|
|
|
2020-05-06 17:36:34 +00:00
|
|
|
"github.com/pkg/sftp"
|
|
|
|
"golang.org/x/crypto/ssh"
|
|
|
|
|
2021-06-26 05:31:41 +00:00
|
|
|
"github.com/drakkan/sftpgo/v2/common"
|
|
|
|
"github.com/drakkan/sftpgo/v2/dataprovider"
|
|
|
|
"github.com/drakkan/sftpgo/v2/logger"
|
2021-07-11 13:26:51 +00:00
|
|
|
"github.com/drakkan/sftpgo/v2/metric"
|
|
|
|
"github.com/drakkan/sftpgo/v2/util"
|
2021-06-26 05:31:41 +00:00
|
|
|
"github.com/drakkan/sftpgo/v2/vfs"
|
2019-07-20 10:26:52 +00:00
|
|
|
)
|
|
|
|
|
2020-02-16 17:17:39 +00:00
|
|
|
const (
|
2020-10-19 12:30:40 +00:00
|
|
|
defaultPrivateRSAKeyName = "id_rsa"
|
|
|
|
defaultPrivateECDSAKeyName = "id_ecdsa"
|
|
|
|
defaultPrivateEd25519KeyName = "id_ed25519"
|
|
|
|
sourceAddressCriticalOption = "source-address"
|
2020-02-16 17:17:39 +00:00
|
|
|
)
|
2019-08-01 07:42:15 +00:00
|
|
|
|
2020-02-28 23:02:06 +00:00
|
|
|
var (
|
2022-04-04 16:52:19 +00:00
|
|
|
sftpExtensions = []string{"statvfs@openssh.com"}
|
|
|
|
supportedHostKeyAlgos = []string{
|
|
|
|
ssh.CertAlgoRSASHA512v01, ssh.CertAlgoRSASHA256v01,
|
|
|
|
ssh.CertAlgoRSAv01, ssh.CertAlgoDSAv01, ssh.CertAlgoECDSA256v01,
|
|
|
|
ssh.CertAlgoECDSA384v01, ssh.CertAlgoECDSA521v01, ssh.CertAlgoED25519v01,
|
|
|
|
ssh.KeyAlgoECDSA256, ssh.KeyAlgoECDSA384, ssh.KeyAlgoECDSA521,
|
|
|
|
ssh.KeyAlgoRSASHA512, ssh.KeyAlgoRSASHA256,
|
|
|
|
ssh.KeyAlgoRSA, ssh.KeyAlgoDSA,
|
|
|
|
ssh.KeyAlgoED25519,
|
|
|
|
}
|
|
|
|
preferredHostKeyAlgos = []string{
|
|
|
|
ssh.CertAlgoRSASHA512v01, ssh.CertAlgoRSASHA256v01,
|
|
|
|
ssh.CertAlgoECDSA256v01,
|
|
|
|
ssh.CertAlgoECDSA384v01, ssh.CertAlgoECDSA521v01, ssh.CertAlgoED25519v01,
|
|
|
|
ssh.KeyAlgoECDSA256, ssh.KeyAlgoECDSA384, ssh.KeyAlgoECDSA521,
|
|
|
|
ssh.KeyAlgoRSASHA512, ssh.KeyAlgoRSASHA256,
|
|
|
|
ssh.KeyAlgoED25519,
|
|
|
|
}
|
2022-01-06 17:09:49 +00:00
|
|
|
supportedKexAlgos = []string{
|
2022-03-18 20:52:00 +00:00
|
|
|
"curve25519-sha256", "curve25519-sha256@libssh.org",
|
2022-01-06 17:09:49 +00:00
|
|
|
"ecdh-sha2-nistp256", "ecdh-sha2-nistp384", "ecdh-sha2-nistp521",
|
2022-03-18 20:52:00 +00:00
|
|
|
"diffie-hellman-group14-sha256", "diffie-hellman-group16-sha512",
|
|
|
|
"diffie-hellman-group18-sha512", "diffie-hellman-group14-sha1",
|
|
|
|
"diffie-hellman-group1-sha1",
|
2022-01-06 17:09:49 +00:00
|
|
|
}
|
|
|
|
supportedCiphers = []string{
|
|
|
|
"aes128-gcm@openssh.com", "aes256-gcm@openssh.com",
|
|
|
|
"chacha20-poly1305@openssh.com",
|
|
|
|
"aes128-ctr", "aes192-ctr", "aes256-ctr",
|
|
|
|
"aes128-cbc", "aes192-cbc", "aes256-cbc",
|
|
|
|
"3des-cbc",
|
|
|
|
"arcfour", "arcfour128", "arcfour256",
|
|
|
|
}
|
|
|
|
supportedMACs = []string{
|
|
|
|
"hmac-sha2-256-etm@openssh.com", "hmac-sha2-256",
|
|
|
|
"hmac-sha2-512-etm@openssh.com", "hmac-sha2-512",
|
|
|
|
"hmac-sha1", "hmac-sha1-96",
|
|
|
|
}
|
2022-03-31 19:49:06 +00:00
|
|
|
|
|
|
|
revokedCertManager = revokedCertificates{
|
|
|
|
certs: map[string]bool{},
|
|
|
|
}
|
2020-02-28 23:02:06 +00:00
|
|
|
)
|
2019-11-12 06:37:47 +00:00
|
|
|
|
2020-12-23 15:12:30 +00:00
|
|
|
// Binding defines the configuration for a network listener
|
|
|
|
type Binding struct {
|
|
|
|
// The address to listen on. A blank value means listen on all available network interfaces.
|
|
|
|
Address string `json:"address" mapstructure:"address"`
|
|
|
|
// The port used for serving requests
|
|
|
|
Port int `json:"port" mapstructure:"port"`
|
2020-12-24 17:48:06 +00:00
|
|
|
// Apply the proxy configuration, if any, for this binding
|
2020-12-23 15:12:30 +00:00
|
|
|
ApplyProxyConfig bool `json:"apply_proxy_config" mapstructure:"apply_proxy_config"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetAddress returns the binding address
|
|
|
|
func (b *Binding) GetAddress() string {
|
|
|
|
return fmt.Sprintf("%s:%d", b.Address, b.Port)
|
|
|
|
}
|
|
|
|
|
|
|
|
// IsValid returns true if the binding port is > 0
|
|
|
|
func (b *Binding) IsValid() bool {
|
|
|
|
return b.Port > 0
|
|
|
|
}
|
|
|
|
|
|
|
|
// HasProxy returns true if the proxy protocol is active for this binding
|
|
|
|
func (b *Binding) HasProxy() bool {
|
|
|
|
return b.ApplyProxyConfig && common.Config.ProxyProtocol > 0
|
|
|
|
}
|
|
|
|
|
2019-07-30 18:51:29 +00:00
|
|
|
// Configuration for the SFTP server
|
2019-07-20 10:26:52 +00:00
|
|
|
type Configuration struct {
|
2019-07-30 18:51:29 +00:00
|
|
|
// Identification string used by the server
|
2019-08-07 20:46:13 +00:00
|
|
|
Banner string `json:"banner" mapstructure:"banner"`
|
2020-12-23 15:12:30 +00:00
|
|
|
// Addresses and ports to bind to
|
|
|
|
Bindings []Binding `json:"bindings" mapstructure:"bindings"`
|
2019-07-30 18:51:29 +00:00
|
|
|
// Maximum number of authentication attempts permitted per connection.
|
2020-03-03 22:25:23 +00:00
|
|
|
// If set to a negative number, the number of attempts is unlimited.
|
2019-07-30 18:51:29 +00:00
|
|
|
// If set to zero, the number of attempts are limited to 6.
|
2019-08-07 20:46:13 +00:00
|
|
|
MaxAuthTries int `json:"max_auth_tries" mapstructure:"max_auth_tries"`
|
2020-05-16 21:26:44 +00:00
|
|
|
// HostKeys define the daemon's private host keys.
|
|
|
|
// Each host key can be defined as a path relative to the configuration directory or an absolute one.
|
|
|
|
// If empty or missing, the daemon will search or try to generate "id_rsa" and "id_ecdsa" host keys
|
|
|
|
// inside the configuration directory.
|
|
|
|
HostKeys []string `json:"host_keys" mapstructure:"host_keys"`
|
2022-04-01 06:03:56 +00:00
|
|
|
// HostCertificates defines public host certificates.
|
|
|
|
// Each certificate can be defined as a path relative to the configuration directory or an absolute one.
|
|
|
|
// Certificate's public key must match a private host key otherwise it will be silently ignored.
|
|
|
|
HostCertificates []string `json:"host_certificates" mapstructure:"host_certificates"`
|
2022-04-04 16:52:19 +00:00
|
|
|
// HostKeyAlgorithms lists the public key algorithms that the server will accept for host
|
|
|
|
// key authentication.
|
|
|
|
HostKeyAlgorithms []string `json:"host_key_algorithms" mapstructure:"host_key_algorithms"`
|
2019-09-03 10:08:09 +00:00
|
|
|
// KexAlgorithms specifies the available KEX (Key Exchange) algorithms in
|
|
|
|
// preference order.
|
|
|
|
KexAlgorithms []string `json:"kex_algorithms" mapstructure:"kex_algorithms"`
|
|
|
|
// Ciphers specifies the ciphers allowed
|
|
|
|
Ciphers []string `json:"ciphers" mapstructure:"ciphers"`
|
|
|
|
// MACs Specifies the available MAC (message authentication code) algorithms
|
|
|
|
// in preference order
|
|
|
|
MACs []string `json:"macs" mapstructure:"macs"`
|
2020-05-15 18:08:53 +00:00
|
|
|
// TrustedUserCAKeys specifies a list of public keys paths of certificate authorities
|
|
|
|
// that are trusted to sign user certificates for authentication.
|
|
|
|
// The paths can be absolute or relative to the configuration directory
|
|
|
|
TrustedUserCAKeys []string `json:"trusted_user_ca_keys" mapstructure:"trusted_user_ca_keys"`
|
2022-03-31 19:49:06 +00:00
|
|
|
// Path to a file containing the revoked user certificates.
|
|
|
|
// This file must contain a JSON list with the public key fingerprints of the revoked certificates.
|
|
|
|
// Example content:
|
|
|
|
// ["SHA256:bsBRHC/xgiqBJdSuvSTNpJNLTISP/G356jNMCRYC5Es","SHA256:119+8cL/HH+NLMawRsJx6CzPF1I3xC+jpM60bQHXGE8"]
|
|
|
|
RevokedUserCertsFile string `json:"revoked_user_certs_file" mapstructure:"revoked_user_certs_file"`
|
2019-09-03 10:08:09 +00:00
|
|
|
// LoginBannerFile the contents of the specified file, if any, are sent to
|
|
|
|
// the remote user before authentication is allowed.
|
|
|
|
LoginBannerFile string `json:"login_banner_file" mapstructure:"login_banner_file"`
|
2019-11-18 22:30:37 +00:00
|
|
|
// List of enabled SSH commands.
|
|
|
|
// We support the following SSH commands:
|
|
|
|
// - "scp". SCP is an experimental feature, we have our own SCP implementation since
|
|
|
|
// we can't rely on scp system command to proper handle permissions, quota and
|
|
|
|
// user's home dir restrictions.
|
|
|
|
// The SCP protocol is quite simple but there is no official docs about it,
|
|
|
|
// so we need more testing and feedbacks before enabling it by default.
|
|
|
|
// We may not handle some borderline cases or have sneaky bugs.
|
|
|
|
// Please do accurate tests yourself before enabling SCP and let us known
|
|
|
|
// if something does not work as expected for your use cases.
|
|
|
|
// SCP between two remote hosts is supported using the `-3` scp option.
|
|
|
|
// - "md5sum", "sha1sum", "sha256sum", "sha384sum", "sha512sum". Useful to check message
|
|
|
|
// digests for uploaded files. These commands are implemented inside SFTPGo so they
|
|
|
|
// work even if the matching system commands are not available, for example on Windows.
|
|
|
|
// - "cd", "pwd". Some mobile SFTP clients does not support the SFTP SSH_FXP_REALPATH and so
|
|
|
|
// they use "cd" and "pwd" SSH commands to get the initial directory.
|
|
|
|
// Currently `cd` do nothing and `pwd` always returns the "/" path.
|
|
|
|
//
|
|
|
|
// The following SSH commands are enabled by default: "md5sum", "sha1sum", "cd", "pwd".
|
|
|
|
// "*" enables all supported SSH commands.
|
|
|
|
EnabledSSHCommands []string `json:"enabled_ssh_commands" mapstructure:"enabled_ssh_commands"`
|
2021-09-04 10:11:04 +00:00
|
|
|
// KeyboardInteractiveAuthentication specifies whether keyboard interactive authentication is allowed.
|
|
|
|
// If no keyboard interactive hook or auth plugin is defined the default is to prompt for the user password and then the
|
|
|
|
// one time authentication code, if defined.
|
|
|
|
KeyboardInteractiveAuthentication bool `json:"keyboard_interactive_authentication" mapstructure:"keyboard_interactive_authentication"`
|
2020-04-01 21:25:23 +00:00
|
|
|
// Absolute path to an external program or an HTTP URL to invoke for keyboard interactive authentication.
|
|
|
|
// Leave empty to disable this authentication mode.
|
|
|
|
KeyboardInteractiveHook string `json:"keyboard_interactive_auth_hook" mapstructure:"keyboard_interactive_auth_hook"`
|
2020-09-01 17:34:40 +00:00
|
|
|
// PasswordAuthentication specifies whether password authentication is allowed.
|
|
|
|
PasswordAuthentication bool `json:"password_authentication" mapstructure:"password_authentication"`
|
2021-07-29 18:12:23 +00:00
|
|
|
// Virtual root folder prefix to include in all file operations (ex: /files).
|
|
|
|
// The virtual paths used for per-directory permissions, file patterns etc. must not include the folder prefix.
|
|
|
|
// The prefix is only applied to SFTP requests, SCP and other SSH commands will be automatically disabled if
|
|
|
|
// you configure a prefix.
|
|
|
|
// This setting can help some migrations from OpenSSH. It is not recommended for general usage.
|
2021-07-28 22:32:55 +00:00
|
|
|
FolderPrefix string `json:"folder_prefix" mapstructure:"folder_prefix"`
|
|
|
|
certChecker *ssh.CertChecker
|
|
|
|
parsedUserCAKeys []ssh.PublicKey
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
2019-11-11 14:20:00 +00:00
|
|
|
type authenticationError struct {
|
|
|
|
err string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *authenticationError) Error() string {
|
|
|
|
return fmt.Sprintf("Authentication error: %s", e.err)
|
|
|
|
}
|
|
|
|
|
2020-12-23 15:12:30 +00:00
|
|
|
// ShouldBind returns true if there is at least a valid binding
|
|
|
|
func (c *Configuration) ShouldBind() bool {
|
|
|
|
for _, binding := range c.Bindings {
|
|
|
|
if binding.IsValid() {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2022-01-06 17:09:49 +00:00
|
|
|
func (c *Configuration) getServerConfig() *ssh.ServerConfig {
|
2019-07-20 10:26:52 +00:00
|
|
|
serverConfig := &ssh.ServerConfig{
|
|
|
|
NoClientAuth: false,
|
2019-07-21 10:02:24 +00:00
|
|
|
MaxAuthTries: c.MaxAuthTries,
|
2019-07-20 10:26:52 +00:00
|
|
|
PublicKeyCallback: func(conn ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
|
2020-05-15 18:08:53 +00:00
|
|
|
sp, err := c.validatePublicKeyCredentials(conn, pubKey)
|
2020-04-09 21:32:42 +00:00
|
|
|
if err == ssh.ErrPartialSuccess {
|
2020-05-16 13:15:32 +00:00
|
|
|
return sp, err
|
2020-04-09 21:32:42 +00:00
|
|
|
}
|
2019-07-20 10:26:52 +00:00
|
|
|
if err != nil {
|
2019-11-11 14:20:00 +00:00
|
|
|
return nil, &authenticationError{err: fmt.Sprintf("could not validate public key credentials: %v", err)}
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return sp, nil
|
|
|
|
},
|
2020-04-09 21:32:42 +00:00
|
|
|
NextAuthMethodsCallback: func(conn ssh.ConnMetadata) []string {
|
|
|
|
var nextMethods []string
|
2022-04-25 13:49:11 +00:00
|
|
|
user, err := dataprovider.GetUserWithGroupSettings(conn.User())
|
2020-04-09 21:32:42 +00:00
|
|
|
if err == nil {
|
2020-09-01 17:34:40 +00:00
|
|
|
nextMethods = user.GetNextAuthMethods(conn.PartialSuccessMethods(), c.PasswordAuthentication)
|
2020-04-09 21:32:42 +00:00
|
|
|
}
|
|
|
|
return nextMethods
|
|
|
|
},
|
|
|
|
ServerVersion: fmt.Sprintf("SSH-2.0-%v", c.Banner),
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
2020-09-01 17:34:40 +00:00
|
|
|
if c.PasswordAuthentication {
|
2020-09-01 17:26:33 +00:00
|
|
|
serverConfig.PasswordCallback = func(conn ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
|
|
|
|
sp, err := c.validatePasswordCredentials(conn, pass)
|
|
|
|
if err != nil {
|
|
|
|
return nil, &authenticationError{err: fmt.Sprintf("could not validate password credentials: %v", err)}
|
|
|
|
}
|
|
|
|
|
|
|
|
return sp, nil
|
|
|
|
}
|
2022-02-26 15:43:29 +00:00
|
|
|
serviceStatus.Authentications = append(serviceStatus.Authentications, dataprovider.LoginMethodPassword)
|
2020-09-01 17:26:33 +00:00
|
|
|
}
|
2022-02-26 15:43:29 +00:00
|
|
|
serviceStatus.Authentications = append(serviceStatus.Authentications, dataprovider.SSHLoginMethodPublicKey)
|
2020-09-01 17:26:33 +00:00
|
|
|
|
2022-01-06 17:09:49 +00:00
|
|
|
return serverConfig
|
|
|
|
}
|
|
|
|
|
2022-02-26 15:43:29 +00:00
|
|
|
func (c *Configuration) updateSupportedAuthentications() {
|
|
|
|
serviceStatus.Authentications = util.RemoveDuplicates(serviceStatus.Authentications)
|
|
|
|
|
2022-05-19 17:49:51 +00:00
|
|
|
if util.Contains(serviceStatus.Authentications, dataprovider.LoginMethodPassword) &&
|
|
|
|
util.Contains(serviceStatus.Authentications, dataprovider.SSHLoginMethodPublicKey) {
|
2022-02-26 15:43:29 +00:00
|
|
|
serviceStatus.Authentications = append(serviceStatus.Authentications, dataprovider.SSHLoginMethodKeyAndPassword)
|
|
|
|
}
|
|
|
|
|
2022-05-19 17:49:51 +00:00
|
|
|
if util.Contains(serviceStatus.Authentications, dataprovider.SSHLoginMethodKeyboardInteractive) &&
|
|
|
|
util.Contains(serviceStatus.Authentications, dataprovider.SSHLoginMethodPublicKey) {
|
2022-02-26 15:43:29 +00:00
|
|
|
serviceStatus.Authentications = append(serviceStatus.Authentications, dataprovider.SSHLoginMethodKeyAndKeyboardInt)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-06 17:09:49 +00:00
|
|
|
// Initialize the SFTP server and add a persistent listener to handle inbound SFTP connections.
|
|
|
|
func (c *Configuration) Initialize(configDir string) error {
|
2022-02-26 15:43:29 +00:00
|
|
|
serviceStatus.Authentications = nil
|
2022-01-06 17:09:49 +00:00
|
|
|
serverConfig := c.getServerConfig()
|
|
|
|
|
2020-12-23 15:12:30 +00:00
|
|
|
if !c.ShouldBind() {
|
|
|
|
return common.ErrNoBinding
|
|
|
|
}
|
|
|
|
|
2020-07-24 21:39:38 +00:00
|
|
|
if err := c.checkAndLoadHostKeys(configDir, serverConfig); err != nil {
|
2020-12-08 10:18:34 +00:00
|
|
|
serviceStatus.HostKeys = nil
|
2020-05-15 18:08:53 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-07-24 21:39:38 +00:00
|
|
|
if err := c.initializeCertChecker(configDir); err != nil {
|
2019-08-02 09:17:23 +00:00
|
|
|
return err
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
2020-04-30 12:23:55 +00:00
|
|
|
sftp.SetSFTPExtensions(sftpExtensions...) //nolint:errcheck // we configure valid SFTP Extensions so we cannot get an error
|
|
|
|
|
2022-01-06 17:09:49 +00:00
|
|
|
if err := c.configureSecurityOptions(serverConfig); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-01-21 09:54:05 +00:00
|
|
|
c.configureKeyboardInteractiveAuth(serverConfig)
|
2019-09-03 10:08:09 +00:00
|
|
|
c.configureLoginBanner(serverConfig, configDir)
|
2019-11-18 22:30:37 +00:00
|
|
|
c.checkSSHCommands()
|
2021-07-28 22:32:55 +00:00
|
|
|
c.checkFolderPrefix()
|
2019-09-03 10:08:09 +00:00
|
|
|
|
2020-12-23 18:53:07 +00:00
|
|
|
exitChannel := make(chan error, 1)
|
2020-12-23 15:12:30 +00:00
|
|
|
serviceStatus.Bindings = nil
|
|
|
|
|
|
|
|
for _, binding := range c.Bindings {
|
|
|
|
if !binding.IsValid() {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
serviceStatus.Bindings = append(serviceStatus.Bindings, binding)
|
|
|
|
|
|
|
|
go func(binding Binding) {
|
2020-12-23 18:53:07 +00:00
|
|
|
addr := binding.GetAddress()
|
2021-07-11 13:26:51 +00:00
|
|
|
util.CheckTCP4Port(binding.Port)
|
2020-12-23 18:53:07 +00:00
|
|
|
listener, err := net.Listen("tcp", addr)
|
|
|
|
if err != nil {
|
|
|
|
logger.Warn(logSender, "", "error starting listener on address %v: %v", addr, err)
|
|
|
|
exitChannel <- err
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-08-05 16:38:15 +00:00
|
|
|
if binding.ApplyProxyConfig && common.Config.ProxyProtocol > 0 {
|
2020-12-23 18:53:07 +00:00
|
|
|
proxyListener, err := common.Config.GetProxyListener(listener)
|
|
|
|
if err != nil {
|
|
|
|
logger.Warn(logSender, "", "error enabling proxy listener: %v", err)
|
|
|
|
exitChannel <- err
|
|
|
|
return
|
|
|
|
}
|
2021-08-05 16:38:15 +00:00
|
|
|
listener = proxyListener
|
2020-12-23 18:53:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
exitChannel <- c.serve(listener, serverConfig)
|
2020-12-23 15:12:30 +00:00
|
|
|
}(binding)
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
2020-12-23 15:12:30 +00:00
|
|
|
|
|
|
|
serviceStatus.IsActive = true
|
2021-01-18 12:24:38 +00:00
|
|
|
serviceStatus.SSHCommands = c.EnabledSSHCommands
|
2022-02-26 15:43:29 +00:00
|
|
|
c.updateSupportedAuthentications()
|
2020-12-23 15:12:30 +00:00
|
|
|
|
|
|
|
return <-exitChannel
|
|
|
|
}
|
|
|
|
|
2020-12-23 18:53:07 +00:00
|
|
|
func (c *Configuration) serve(listener net.Listener, serverConfig *ssh.ServerConfig) error {
|
|
|
|
logger.Info(logSender, "", "server listener registered, address: %v", listener.Addr().String())
|
|
|
|
var tempDelay time.Duration // how long to sleep on accept failure
|
2019-07-20 10:26:52 +00:00
|
|
|
|
2020-12-23 18:53:07 +00:00
|
|
|
for {
|
|
|
|
conn, err := listener.Accept()
|
2020-12-23 15:12:30 +00:00
|
|
|
if err != nil {
|
2022-03-17 13:59:02 +00:00
|
|
|
// see https://github.com/golang/go/blob/4aa1efed4853ea067d665a952eee77c52faac774/src/net/http/server.go#L3046
|
|
|
|
if ne, ok := err.(net.Error); ok && ne.Temporary() { //nolint:staticcheck
|
2020-12-23 18:53:07 +00:00
|
|
|
if tempDelay == 0 {
|
|
|
|
tempDelay = 5 * time.Millisecond
|
|
|
|
} else {
|
|
|
|
tempDelay *= 2
|
|
|
|
}
|
|
|
|
if max := 1 * time.Second; tempDelay > max {
|
|
|
|
tempDelay = max
|
|
|
|
}
|
|
|
|
logger.Warn(logSender, "", "accept error: %v; retrying in %v", err, tempDelay)
|
|
|
|
time.Sleep(tempDelay)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
logger.Warn(logSender, "", "unrecoverable accept error: %v", err)
|
2020-12-23 15:12:30 +00:00
|
|
|
return err
|
|
|
|
}
|
2022-03-17 13:59:02 +00:00
|
|
|
tempDelay = 0
|
2020-12-23 18:53:07 +00:00
|
|
|
|
|
|
|
go c.AcceptInboundConnection(conn, serverConfig)
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-06 17:09:49 +00:00
|
|
|
func (c *Configuration) configureSecurityOptions(serverConfig *ssh.ServerConfig) error {
|
2022-04-04 16:52:19 +00:00
|
|
|
if len(c.HostKeyAlgorithms) == 0 {
|
|
|
|
c.HostKeyAlgorithms = preferredHostKeyAlgos
|
|
|
|
} else {
|
|
|
|
c.HostKeyAlgorithms = util.RemoveDuplicates(c.HostKeyAlgorithms)
|
|
|
|
}
|
|
|
|
for _, hostKeyAlgo := range c.HostKeyAlgorithms {
|
2022-05-19 17:49:51 +00:00
|
|
|
if !util.Contains(supportedHostKeyAlgos, hostKeyAlgo) {
|
2022-04-04 16:52:19 +00:00
|
|
|
return fmt.Errorf("unsupported host key algorithm %#v", hostKeyAlgo)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
serverConfig.HostKeyAlgorithms = c.HostKeyAlgorithms
|
|
|
|
|
2019-09-03 10:08:09 +00:00
|
|
|
if len(c.KexAlgorithms) > 0 {
|
2022-01-06 17:09:49 +00:00
|
|
|
c.KexAlgorithms = util.RemoveDuplicates(c.KexAlgorithms)
|
|
|
|
for _, kex := range c.KexAlgorithms {
|
2022-05-19 17:49:51 +00:00
|
|
|
if !util.Contains(supportedKexAlgos, kex) {
|
2022-01-06 17:09:49 +00:00
|
|
|
return fmt.Errorf("unsupported key-exchange algorithm %#v", kex)
|
|
|
|
}
|
|
|
|
}
|
2019-09-03 10:08:09 +00:00
|
|
|
serverConfig.KeyExchanges = c.KexAlgorithms
|
|
|
|
}
|
|
|
|
if len(c.Ciphers) > 0 {
|
2022-01-06 17:09:49 +00:00
|
|
|
c.Ciphers = util.RemoveDuplicates(c.Ciphers)
|
|
|
|
for _, cipher := range c.Ciphers {
|
2022-05-19 17:49:51 +00:00
|
|
|
if !util.Contains(supportedCiphers, cipher) {
|
2022-01-06 17:09:49 +00:00
|
|
|
return fmt.Errorf("unsupported cipher %#v", cipher)
|
|
|
|
}
|
|
|
|
}
|
2019-09-03 10:08:09 +00:00
|
|
|
serverConfig.Ciphers = c.Ciphers
|
|
|
|
}
|
|
|
|
if len(c.MACs) > 0 {
|
2022-01-06 17:09:49 +00:00
|
|
|
c.MACs = util.RemoveDuplicates(c.MACs)
|
|
|
|
for _, mac := range c.MACs {
|
2022-05-19 17:49:51 +00:00
|
|
|
if !util.Contains(supportedMACs, mac) {
|
2022-01-06 17:09:49 +00:00
|
|
|
return fmt.Errorf("unsupported MAC algorithm %#v", mac)
|
|
|
|
}
|
|
|
|
}
|
2019-09-03 10:08:09 +00:00
|
|
|
serverConfig.MACs = c.MACs
|
|
|
|
}
|
2022-01-06 17:09:49 +00:00
|
|
|
return nil
|
2019-09-03 10:08:09 +00:00
|
|
|
}
|
|
|
|
|
2020-11-14 18:19:41 +00:00
|
|
|
func (c *Configuration) configureLoginBanner(serverConfig *ssh.ServerConfig, configDir string) {
|
2019-09-03 10:08:09 +00:00
|
|
|
if len(c.LoginBannerFile) > 0 {
|
|
|
|
bannerFilePath := c.LoginBannerFile
|
|
|
|
if !filepath.IsAbs(bannerFilePath) {
|
|
|
|
bannerFilePath = filepath.Join(configDir, bannerFilePath)
|
|
|
|
}
|
2021-02-25 20:53:04 +00:00
|
|
|
bannerContent, err := os.ReadFile(bannerFilePath)
|
2019-09-03 10:08:09 +00:00
|
|
|
if err == nil {
|
2020-04-09 21:32:42 +00:00
|
|
|
banner := string(bannerContent)
|
2019-09-03 10:08:09 +00:00
|
|
|
serverConfig.BannerCallback = func(conn ssh.ConnMetadata) string {
|
2020-04-30 12:23:55 +00:00
|
|
|
return banner
|
2019-09-03 10:08:09 +00:00
|
|
|
}
|
|
|
|
} else {
|
2020-07-29 19:56:56 +00:00
|
|
|
logger.WarnToConsole("unable to read SFTPD login banner file: %v", err)
|
2019-09-05 14:21:35 +00:00
|
|
|
logger.Warn(logSender, "", "unable to read login banner file: %v", err)
|
2019-09-03 10:08:09 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-14 18:19:41 +00:00
|
|
|
func (c *Configuration) configureKeyboardInteractiveAuth(serverConfig *ssh.ServerConfig) {
|
2021-09-04 10:11:04 +00:00
|
|
|
if !c.KeyboardInteractiveAuthentication {
|
2020-01-21 09:54:05 +00:00
|
|
|
return
|
|
|
|
}
|
2021-08-08 15:09:48 +00:00
|
|
|
if c.KeyboardInteractiveHook != "" {
|
|
|
|
if !strings.HasPrefix(c.KeyboardInteractiveHook, "http") {
|
|
|
|
if !filepath.IsAbs(c.KeyboardInteractiveHook) {
|
|
|
|
logger.WarnToConsole("invalid keyboard interactive authentication program: %#v must be an absolute path",
|
|
|
|
c.KeyboardInteractiveHook)
|
|
|
|
logger.Warn(logSender, "", "invalid keyboard interactive authentication program: %#v must be an absolute path",
|
|
|
|
c.KeyboardInteractiveHook)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
_, err := os.Stat(c.KeyboardInteractiveHook)
|
|
|
|
if err != nil {
|
|
|
|
logger.WarnToConsole("invalid keyboard interactive authentication program:: %v", err)
|
|
|
|
logger.Warn(logSender, "", "invalid keyboard interactive authentication program:: %v", err)
|
|
|
|
return
|
|
|
|
}
|
2020-04-01 21:25:23 +00:00
|
|
|
}
|
2020-01-21 09:54:05 +00:00
|
|
|
}
|
|
|
|
serverConfig.KeyboardInteractiveCallback = func(conn ssh.ConnMetadata, client ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) {
|
|
|
|
sp, err := c.validateKeyboardInteractiveCredentials(conn, client)
|
|
|
|
if err != nil {
|
|
|
|
return nil, &authenticationError{err: fmt.Sprintf("could not validate keyboard interactive credentials: %v", err)}
|
|
|
|
}
|
|
|
|
|
|
|
|
return sp, nil
|
|
|
|
}
|
2022-02-26 15:43:29 +00:00
|
|
|
|
|
|
|
serviceStatus.Authentications = append(serviceStatus.Authentications, dataprovider.SSHLoginMethodKeyboardInteractive)
|
2020-01-21 09:54:05 +00:00
|
|
|
}
|
|
|
|
|
2021-01-02 13:05:09 +00:00
|
|
|
func canAcceptConnection(ip string) bool {
|
|
|
|
if common.IsBanned(ip) {
|
|
|
|
logger.Log(logger.LevelDebug, common.ProtocolSSH, "", "connection refused, ip %#v is banned", ip)
|
|
|
|
return false
|
|
|
|
}
|
2021-05-08 17:45:21 +00:00
|
|
|
if !common.Connections.IsNewConnectionAllowed(ip) {
|
2022-03-17 21:10:52 +00:00
|
|
|
logger.Log(logger.LevelDebug, common.ProtocolSSH, "", fmt.Sprintf("connection not allowed from ip %#v", ip))
|
2021-01-02 13:05:09 +00:00
|
|
|
return false
|
|
|
|
}
|
2021-04-19 06:14:04 +00:00
|
|
|
_, err := common.LimitRate(common.ProtocolSSH, ip)
|
|
|
|
if err != nil {
|
2021-04-18 10:31:06 +00:00
|
|
|
return false
|
|
|
|
}
|
2021-01-21 08:28:41 +00:00
|
|
|
if err := common.Config.ExecutePostConnectHook(ip, common.ProtocolSSH); err != nil {
|
|
|
|
return false
|
|
|
|
}
|
2021-01-02 13:05:09 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2019-07-30 18:51:29 +00:00
|
|
|
// AcceptInboundConnection handles an inbound connection to the server instance and determines if the request should be served or not.
|
2020-11-14 18:19:41 +00:00
|
|
|
func (c *Configuration) AcceptInboundConnection(conn net.Conn, config *ssh.ServerConfig) {
|
2020-10-31 10:02:04 +00:00
|
|
|
defer func() {
|
|
|
|
if r := recover(); r != nil {
|
2022-04-28 10:55:01 +00:00
|
|
|
logger.Error(logSender, "", "panic in AcceptInboundConnection: %#v stack trace: %v", r, string(debug.Stack()))
|
2020-10-31 10:02:04 +00:00
|
|
|
}
|
|
|
|
}()
|
2021-04-20 16:12:16 +00:00
|
|
|
|
2021-07-11 13:26:51 +00:00
|
|
|
ipAddr := util.GetIPFromRemoteAddress(conn.RemoteAddr().String())
|
2021-05-08 17:45:21 +00:00
|
|
|
common.Connections.AddClientConnection(ipAddr)
|
|
|
|
defer common.Connections.RemoveClientConnection(ipAddr)
|
|
|
|
|
2021-01-02 13:05:09 +00:00
|
|
|
if !canAcceptConnection(ipAddr) {
|
2020-12-15 18:29:30 +00:00
|
|
|
conn.Close()
|
|
|
|
return
|
|
|
|
}
|
2019-07-20 10:26:52 +00:00
|
|
|
// Before beginning a handshake must be performed on the incoming net.Conn
|
2019-10-09 17:07:35 +00:00
|
|
|
// we'll set a Deadline for handshake to complete, the default is 2 minutes as OpenSSH
|
2020-04-30 12:23:55 +00:00
|
|
|
conn.SetDeadline(time.Now().Add(handshakeTimeout)) //nolint:errcheck
|
2021-01-21 08:28:41 +00:00
|
|
|
|
2019-07-20 10:26:52 +00:00
|
|
|
sconn, chans, reqs, err := ssh.NewServerConn(conn, config)
|
|
|
|
if err != nil {
|
2020-08-06 19:20:31 +00:00
|
|
|
logger.Debug(logSender, "", "failed to accept an incoming connection: %v", err)
|
2021-01-02 13:05:09 +00:00
|
|
|
checkAuthError(ipAddr, err)
|
2019-07-20 10:26:52 +00:00
|
|
|
return
|
|
|
|
}
|
2019-10-09 17:07:35 +00:00
|
|
|
// handshake completed so remove the deadline, we'll use IdleTimeout configuration from now on
|
2020-04-30 12:23:55 +00:00
|
|
|
conn.SetDeadline(time.Time{}) //nolint:errcheck
|
2019-07-20 10:26:52 +00:00
|
|
|
|
2020-09-18 08:52:53 +00:00
|
|
|
defer conn.Close()
|
|
|
|
|
2019-08-24 12:41:15 +00:00
|
|
|
var user dataprovider.User
|
|
|
|
|
2019-10-09 17:07:35 +00:00
|
|
|
// Unmarshal cannot fails here and even if it fails we'll have a user with no permissions
|
2020-05-15 18:08:53 +00:00
|
|
|
json.Unmarshal([]byte(sconn.Permissions.Extensions["sftpgo_user"]), &user) //nolint:errcheck
|
2019-08-24 12:41:15 +00:00
|
|
|
|
2020-05-15 18:08:53 +00:00
|
|
|
loginType := sconn.Permissions.Extensions["sftpgo_login_method"]
|
2019-08-24 12:41:15 +00:00
|
|
|
connectionID := hex.EncodeToString(sconn.SessionID())
|
|
|
|
|
2021-03-21 18:15:47 +00:00
|
|
|
if err = user.CheckFsRoot(connectionID); err != nil {
|
|
|
|
errClose := user.CloseFs()
|
|
|
|
logger.Warn(logSender, connectionID, "unable to check fs root: %v close fs error: %v", err, errClose)
|
2020-01-19 06:41:05 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-03-21 18:15:47 +00:00
|
|
|
defer user.CloseFs() //nolint:errcheck
|
|
|
|
|
2021-11-29 09:15:46 +00:00
|
|
|
logger.Log(logger.LevelInfo, common.ProtocolSSH, connectionID,
|
|
|
|
"User %#v logged in with %#v, from ip %#v, client version %#v", user.Username, loginType,
|
|
|
|
ipAddr, string(sconn.ClientVersion()))
|
2021-08-19 13:51:43 +00:00
|
|
|
dataprovider.UpdateLastLogin(&user)
|
2019-08-24 12:41:15 +00:00
|
|
|
|
2020-09-18 16:15:28 +00:00
|
|
|
sshConnection := common.NewSSHConnection(connectionID, conn)
|
|
|
|
common.Connections.AddSSHConnection(sshConnection)
|
|
|
|
|
|
|
|
defer common.Connections.RemoveSSHConnection(connectionID)
|
|
|
|
|
2019-07-20 10:26:52 +00:00
|
|
|
go ssh.DiscardRequests(reqs)
|
|
|
|
|
2020-09-18 16:15:28 +00:00
|
|
|
channelCounter := int64(0)
|
2019-07-20 10:26:52 +00:00
|
|
|
for newChannel := range chans {
|
|
|
|
// If its not a session channel we just move on because its not something we
|
|
|
|
// know how to handle at this point.
|
|
|
|
if newChannel.ChannelType() != "session" {
|
2020-09-18 08:52:53 +00:00
|
|
|
logger.Log(logger.LevelDebug, common.ProtocolSSH, connectionID, "received an unknown channel type: %v",
|
|
|
|
newChannel.ChannelType())
|
2020-04-30 12:23:55 +00:00
|
|
|
newChannel.Reject(ssh.UnknownChannelType, "unknown channel type") //nolint:errcheck
|
2019-07-20 10:26:52 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
channel, requests, err := newChannel.Accept()
|
|
|
|
if err != nil {
|
2020-09-18 08:52:53 +00:00
|
|
|
logger.Log(logger.LevelWarn, common.ProtocolSSH, connectionID, "could not accept a channel: %v", err)
|
2019-07-20 10:26:52 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2020-09-18 08:52:53 +00:00
|
|
|
channelCounter++
|
2020-09-18 16:15:28 +00:00
|
|
|
sshConnection.UpdateLastActivity()
|
2019-07-20 10:26:52 +00:00
|
|
|
// Channels have a type that is dependent on the protocol. For SFTP this is "subsystem"
|
|
|
|
// with a payload that (should) be "sftp". Discard anything else we receive ("pty", "shell", etc)
|
2020-09-18 16:15:28 +00:00
|
|
|
go func(in <-chan *ssh.Request, counter int64) {
|
2019-07-20 10:26:52 +00:00
|
|
|
for req := range in {
|
|
|
|
ok := false
|
2022-03-24 21:03:17 +00:00
|
|
|
connID := fmt.Sprintf("%s_%d", connectionID, counter)
|
2019-07-20 10:26:52 +00:00
|
|
|
|
|
|
|
switch req.Type {
|
|
|
|
case "subsystem":
|
|
|
|
if string(req.Payload[4:]) == "sftp" {
|
2021-03-21 18:15:47 +00:00
|
|
|
ok = true
|
2022-04-14 17:07:41 +00:00
|
|
|
connection := &Connection{
|
2021-07-24 18:11:17 +00:00
|
|
|
BaseConnection: common.NewBaseConnection(connID, common.ProtocolSFTP, conn.LocalAddr().String(),
|
|
|
|
conn.RemoteAddr().String(), user),
|
|
|
|
ClientVersion: string(sconn.ClientVersion()),
|
|
|
|
RemoteAddr: conn.RemoteAddr(),
|
|
|
|
LocalAddr: conn.LocalAddr(),
|
|
|
|
channel: channel,
|
2021-07-31 07:42:23 +00:00
|
|
|
folderPrefix: c.FolderPrefix,
|
2020-09-18 08:52:53 +00:00
|
|
|
}
|
2022-04-14 17:07:41 +00:00
|
|
|
go c.handleSftpConnection(channel, connection)
|
2021-03-21 18:15:47 +00:00
|
|
|
}
|
|
|
|
case "exec":
|
|
|
|
// protocol will be set later inside processSSHCommand it could be SSH or SCP
|
|
|
|
connection := Connection{
|
2021-07-24 18:11:17 +00:00
|
|
|
BaseConnection: common.NewBaseConnection(connID, "sshd_exec", conn.LocalAddr().String(),
|
|
|
|
conn.RemoteAddr().String(), user),
|
|
|
|
ClientVersion: string(sconn.ClientVersion()),
|
|
|
|
RemoteAddr: conn.RemoteAddr(),
|
|
|
|
LocalAddr: conn.LocalAddr(),
|
|
|
|
channel: channel,
|
2021-07-31 07:42:23 +00:00
|
|
|
folderPrefix: c.FolderPrefix,
|
2020-09-18 08:52:53 +00:00
|
|
|
}
|
2021-03-21 18:15:47 +00:00
|
|
|
ok = processSSHCommand(req.Payload, &connection, c.EnabledSSHCommands)
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
2021-01-21 08:28:41 +00:00
|
|
|
if req.WantReply {
|
|
|
|
req.Reply(ok, nil) //nolint:errcheck
|
|
|
|
}
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
2020-09-18 08:52:53 +00:00
|
|
|
}(requests, channelCounter)
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-14 18:19:41 +00:00
|
|
|
func (c *Configuration) handleSftpConnection(channel ssh.Channel, connection *Connection) {
|
2020-10-31 10:02:04 +00:00
|
|
|
defer func() {
|
|
|
|
if r := recover(); r != nil {
|
2022-04-28 10:55:01 +00:00
|
|
|
logger.Error(logSender, "", "panic in handleSftpConnection: %#v stack trace: %v", r, string(debug.Stack()))
|
2020-10-31 10:02:04 +00:00
|
|
|
}
|
|
|
|
}()
|
2022-04-14 17:07:41 +00:00
|
|
|
if err := common.Connections.Add(connection); err != nil {
|
|
|
|
errClose := connection.Disconnect()
|
|
|
|
logger.Info(logSender, "", "unable to add connection: %v, close err: %v", err, errClose)
|
|
|
|
return
|
|
|
|
}
|
2020-07-29 19:56:56 +00:00
|
|
|
defer common.Connections.Remove(connection.GetID())
|
2020-07-24 21:39:38 +00:00
|
|
|
|
2019-08-24 12:41:15 +00:00
|
|
|
// Create the server instance for the channel using the handler we created above.
|
2022-03-03 11:44:56 +00:00
|
|
|
server := sftp.NewRequestServer(channel, c.createHandlers(connection), sftp.WithRSAllocator(),
|
|
|
|
sftp.WithStartDirectory(connection.User.Filters.StartDirectory))
|
2019-08-24 12:41:15 +00:00
|
|
|
|
2020-11-15 21:04:48 +00:00
|
|
|
defer server.Close()
|
2019-08-24 12:41:15 +00:00
|
|
|
if err := server.Serve(); err == io.EOF {
|
2019-11-15 11:15:07 +00:00
|
|
|
exitStatus := sshSubsystemExitStatus{Status: uint32(0)}
|
|
|
|
_, err = channel.SendRequest("exit-status", false, ssh.Marshal(&exitStatus))
|
2021-12-02 18:36:42 +00:00
|
|
|
connection.Log(logger.LevelInfo, "connection closed, sent exit status %+v error: %v", exitStatus, err)
|
2019-08-24 12:41:15 +00:00
|
|
|
} else if err != nil {
|
2021-12-16 18:53:00 +00:00
|
|
|
connection.Log(logger.LevelError, "connection closed with error: %v", err)
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
2019-08-24 12:41:15 +00:00
|
|
|
}
|
|
|
|
|
2021-07-29 18:12:23 +00:00
|
|
|
func (c *Configuration) createHandlers(connection *Connection) sftp.Handlers {
|
|
|
|
if c.FolderPrefix != "" {
|
|
|
|
prefixMiddleware := newPrefixMiddleware(c.FolderPrefix, connection)
|
|
|
|
|
|
|
|
return sftp.Handlers{
|
|
|
|
FileGet: prefixMiddleware,
|
|
|
|
FilePut: prefixMiddleware,
|
|
|
|
FileCmd: prefixMiddleware,
|
|
|
|
FileList: prefixMiddleware,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return sftp.Handlers{
|
|
|
|
FileGet: connection,
|
|
|
|
FilePut: connection,
|
|
|
|
FileCmd: connection,
|
|
|
|
FileList: connection,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-02 13:05:09 +00:00
|
|
|
func checkAuthError(ip string, err error) {
|
|
|
|
if authErrors, ok := err.(*ssh.ServerAuthError); ok {
|
|
|
|
// check public key auth errors here
|
|
|
|
for _, err := range authErrors.Errors {
|
|
|
|
if err != nil {
|
|
|
|
// these checks should be improved, we should check for error type and not error strings
|
|
|
|
if strings.Contains(err.Error(), "public key credentials") {
|
|
|
|
event := common.HostEventLoginFailed
|
|
|
|
if strings.Contains(err.Error(), "not found") {
|
|
|
|
event = common.HostEventUserNotFound
|
|
|
|
}
|
|
|
|
common.AddDefenderEvent(ip, event)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
2020-12-15 18:29:30 +00:00
|
|
|
logger.ConnectionFailedLog("", ip, dataprovider.LoginMethodNoAuthTryed, common.ProtocolSSH, err.Error())
|
2021-07-11 13:26:51 +00:00
|
|
|
metric.AddNoAuthTryed()
|
2021-01-02 13:05:09 +00:00
|
|
|
common.AddDefenderEvent(ip, common.HostEventNoLoginTried)
|
2021-01-26 17:05:44 +00:00
|
|
|
dataprovider.ExecutePostLoginHook(&dataprovider.User{}, dataprovider.LoginMethodNoAuthTryed, ip, common.ProtocolSSH, err)
|
2020-12-15 18:29:30 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-16 18:11:36 +00:00
|
|
|
func loginUser(user *dataprovider.User, loginMethod, publicKey string, conn ssh.ConnMetadata) (*ssh.Permissions, error) {
|
2020-04-09 21:32:42 +00:00
|
|
|
connectionID := ""
|
|
|
|
if conn != nil {
|
|
|
|
connectionID = hex.EncodeToString(conn.SessionID())
|
|
|
|
}
|
2019-07-20 10:26:52 +00:00
|
|
|
if !filepath.IsAbs(user.HomeDir) {
|
2020-04-09 21:32:42 +00:00
|
|
|
logger.Warn(logSender, connectionID, "user %#v has an invalid home dir: %#v. Home dir must be an absolute path, login not allowed",
|
2019-07-20 10:26:52 +00:00
|
|
|
user.Username, user.HomeDir)
|
2019-11-15 11:15:07 +00:00
|
|
|
return nil, fmt.Errorf("cannot login user with invalid home dir: %#v", user.HomeDir)
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
2022-05-19 17:49:51 +00:00
|
|
|
if util.Contains(user.Filters.DeniedProtocols, common.ProtocolSSH) {
|
2021-12-02 18:36:42 +00:00
|
|
|
logger.Info(logSender, connectionID, "cannot login user %#v, protocol SSH is not allowed", user.Username)
|
2021-03-21 18:15:47 +00:00
|
|
|
return nil, fmt.Errorf("protocol SSH is not allowed for user %#v", user.Username)
|
2020-08-17 10:49:20 +00:00
|
|
|
}
|
2019-07-20 10:26:52 +00:00
|
|
|
if user.MaxSessions > 0 {
|
2020-07-24 21:39:38 +00:00
|
|
|
activeSessions := common.Connections.GetActiveSessions(user.Username)
|
2019-07-20 10:26:52 +00:00
|
|
|
if activeSessions >= user.MaxSessions {
|
2021-12-02 18:36:42 +00:00
|
|
|
logger.Info(logSender, "", "authentication refused for user: %#v, too many open sessions: %v/%v", user.Username,
|
2019-07-20 10:26:52 +00:00
|
|
|
activeSessions, user.MaxSessions)
|
2019-10-24 16:50:35 +00:00
|
|
|
return nil, fmt.Errorf("too many open sessions: %v", activeSessions)
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
}
|
2022-03-06 15:57:13 +00:00
|
|
|
if !user.IsLoginMethodAllowed(loginMethod, common.ProtocolSSH, conn.PartialSuccessMethods()) {
|
2021-12-02 18:36:42 +00:00
|
|
|
logger.Info(logSender, connectionID, "cannot login user %#v, login method %#v is not allowed",
|
|
|
|
user.Username, loginMethod)
|
2021-03-21 18:15:47 +00:00
|
|
|
return nil, fmt.Errorf("login method %#v is not allowed for user %#v", loginMethod, user.Username)
|
2020-06-10 07:11:32 +00:00
|
|
|
}
|
2022-03-06 15:57:13 +00:00
|
|
|
if user.MustSetSecondFactorForProtocol(common.ProtocolSSH) {
|
|
|
|
logger.Info(logSender, connectionID, "cannot login user %#v, second factor authentication is not set",
|
|
|
|
user.Username)
|
|
|
|
return nil, fmt.Errorf("second factor authentication is not set for user %#v", user.Username)
|
|
|
|
}
|
2020-04-09 21:32:42 +00:00
|
|
|
remoteAddr := conn.RemoteAddr().String()
|
2020-02-19 21:39:30 +00:00
|
|
|
if !user.IsLoginFromAddrAllowed(remoteAddr) {
|
2021-12-02 18:36:42 +00:00
|
|
|
logger.Info(logSender, connectionID, "cannot login user %#v, remote address is not allowed: %v",
|
|
|
|
user.Username, remoteAddr)
|
2021-03-21 18:15:47 +00:00
|
|
|
return nil, fmt.Errorf("login for user %#v is not allowed from this address: %v", user.Username, remoteAddr)
|
2019-12-30 17:37:50 +00:00
|
|
|
}
|
2019-07-20 10:26:52 +00:00
|
|
|
|
|
|
|
json, err := json.Marshal(user)
|
|
|
|
if err != nil {
|
2020-04-09 21:32:42 +00:00
|
|
|
logger.Warn(logSender, connectionID, "error serializing user info: %v, authentication rejected", err)
|
2019-07-20 10:26:52 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
2022-03-06 15:57:13 +00:00
|
|
|
if publicKey != "" {
|
2020-02-19 21:39:30 +00:00
|
|
|
loginMethod = fmt.Sprintf("%v: %v", loginMethod, publicKey)
|
|
|
|
}
|
2019-07-20 10:26:52 +00:00
|
|
|
p := &ssh.Permissions{}
|
|
|
|
p.Extensions = make(map[string]string)
|
2020-05-15 18:08:53 +00:00
|
|
|
p.Extensions["sftpgo_user"] = string(json)
|
|
|
|
p.Extensions["sftpgo_login_method"] = loginMethod
|
2019-07-20 10:26:52 +00:00
|
|
|
return p, nil
|
|
|
|
}
|
|
|
|
|
2019-11-18 22:30:37 +00:00
|
|
|
func (c *Configuration) checkSSHCommands() {
|
2022-05-19 17:49:51 +00:00
|
|
|
if util.Contains(c.EnabledSSHCommands, "*") {
|
2019-11-18 22:30:37 +00:00
|
|
|
c.EnabledSSHCommands = GetSupportedSSHCommands()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
sshCommands := []string{}
|
|
|
|
for _, command := range c.EnabledSSHCommands {
|
2022-05-19 17:49:51 +00:00
|
|
|
if util.Contains(supportedSSHCommands, command) {
|
2019-11-18 22:30:37 +00:00
|
|
|
sshCommands = append(sshCommands, command)
|
|
|
|
} else {
|
|
|
|
logger.Warn(logSender, "", "unsupported ssh command: %#v ignored", command)
|
|
|
|
logger.WarnToConsole("unsupported ssh command: %#v ignored", command)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
c.EnabledSSHCommands = sshCommands
|
2021-07-28 22:32:55 +00:00
|
|
|
logger.Debug(logSender, "", "enabled SSH commands %v", c.EnabledSSHCommands)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Configuration) checkFolderPrefix() {
|
|
|
|
if c.FolderPrefix != "" {
|
|
|
|
c.FolderPrefix = path.Join("/", c.FolderPrefix)
|
2021-07-29 18:12:23 +00:00
|
|
|
if c.FolderPrefix == "/" {
|
|
|
|
c.FolderPrefix = ""
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if c.FolderPrefix != "" {
|
|
|
|
c.EnabledSSHCommands = nil
|
|
|
|
logger.Debug(logSender, "", "folder prefix %#v configured, SSH commands are disabled", c.FolderPrefix)
|
2021-07-28 22:32:55 +00:00
|
|
|
}
|
2019-11-18 22:30:37 +00:00
|
|
|
}
|
|
|
|
|
2020-10-19 12:30:40 +00:00
|
|
|
func (c *Configuration) generateDefaultHostKeys(configDir string) error {
|
|
|
|
var err error
|
|
|
|
defaultHostKeys := []string{defaultPrivateRSAKeyName, defaultPrivateECDSAKeyName, defaultPrivateEd25519KeyName}
|
|
|
|
for _, k := range defaultHostKeys {
|
|
|
|
autoFile := filepath.Join(configDir, k)
|
2022-05-09 17:09:43 +00:00
|
|
|
if _, err = os.Stat(autoFile); errors.Is(err, fs.ErrNotExist) {
|
2020-10-19 12:30:40 +00:00
|
|
|
logger.Info(logSender, "", "No host keys configured and %#v does not exist; try to create a new host key", autoFile)
|
|
|
|
logger.InfoToConsole("No host keys configured and %#v does not exist; try to create a new host key", autoFile)
|
|
|
|
if k == defaultPrivateRSAKeyName {
|
2021-07-11 13:26:51 +00:00
|
|
|
err = util.GenerateRSAKeys(autoFile)
|
2020-10-19 12:30:40 +00:00
|
|
|
} else if k == defaultPrivateECDSAKeyName {
|
2021-07-11 13:26:51 +00:00
|
|
|
err = util.GenerateECDSAKeys(autoFile)
|
2020-10-19 12:30:40 +00:00
|
|
|
} else {
|
2021-07-11 13:26:51 +00:00
|
|
|
err = util.GenerateEd25519Keys(autoFile)
|
2020-10-19 12:30:40 +00:00
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
logger.Warn(logSender, "", "error creating host key %#v: %v", autoFile, err)
|
|
|
|
logger.WarnToConsole("error creating host key %#v: %v", autoFile, err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
c.HostKeys = append(c.HostKeys, k)
|
|
|
|
}
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-06-08 16:45:04 +00:00
|
|
|
func (c *Configuration) checkHostKeyAutoGeneration(configDir string) error {
|
|
|
|
for _, k := range c.HostKeys {
|
|
|
|
if filepath.IsAbs(k) {
|
2022-05-09 17:09:43 +00:00
|
|
|
if _, err := os.Stat(k); errors.Is(err, fs.ErrNotExist) {
|
2020-06-08 16:45:04 +00:00
|
|
|
keyName := filepath.Base(k)
|
|
|
|
switch keyName {
|
|
|
|
case defaultPrivateRSAKeyName:
|
|
|
|
logger.Info(logSender, "", "try to create non-existent host key %#v", k)
|
|
|
|
logger.InfoToConsole("try to create non-existent host key %#v", k)
|
2021-07-11 13:26:51 +00:00
|
|
|
err = util.GenerateRSAKeys(k)
|
2020-06-08 16:45:04 +00:00
|
|
|
if err != nil {
|
2020-10-05 12:16:57 +00:00
|
|
|
logger.Warn(logSender, "", "error creating host key %#v: %v", k, err)
|
|
|
|
logger.WarnToConsole("error creating host key %#v: %v", k, err)
|
2020-06-08 16:45:04 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
case defaultPrivateECDSAKeyName:
|
|
|
|
logger.Info(logSender, "", "try to create non-existent host key %#v", k)
|
|
|
|
logger.InfoToConsole("try to create non-existent host key %#v", k)
|
2021-07-11 13:26:51 +00:00
|
|
|
err = util.GenerateECDSAKeys(k)
|
2020-06-08 16:45:04 +00:00
|
|
|
if err != nil {
|
2020-10-05 12:16:57 +00:00
|
|
|
logger.Warn(logSender, "", "error creating host key %#v: %v", k, err)
|
|
|
|
logger.WarnToConsole("error creating host key %#v: %v", k, err)
|
2020-06-08 16:45:04 +00:00
|
|
|
return err
|
|
|
|
}
|
2020-10-19 12:30:40 +00:00
|
|
|
case defaultPrivateEd25519KeyName:
|
|
|
|
logger.Info(logSender, "", "try to create non-existent host key %#v", k)
|
|
|
|
logger.InfoToConsole("try to create non-existent host key %#v", k)
|
2021-07-11 13:26:51 +00:00
|
|
|
err = util.GenerateEd25519Keys(k)
|
2020-10-19 12:30:40 +00:00
|
|
|
if err != nil {
|
|
|
|
logger.Warn(logSender, "", "error creating host key %#v: %v", k, err)
|
|
|
|
logger.WarnToConsole("error creating host key %#v: %v", k, err)
|
|
|
|
return err
|
|
|
|
}
|
2020-06-08 16:45:04 +00:00
|
|
|
default:
|
|
|
|
logger.Warn(logSender, "", "non-existent host key %#v will not be created", k)
|
|
|
|
logger.WarnToConsole("non-existent host key %#v will not be created", k)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-05-16 21:26:44 +00:00
|
|
|
if len(c.HostKeys) == 0 {
|
2020-10-19 12:30:40 +00:00
|
|
|
if err := c.generateDefaultHostKeys(configDir); err != nil {
|
|
|
|
return err
|
2019-08-02 09:17:23 +00:00
|
|
|
}
|
|
|
|
}
|
2020-06-08 16:45:04 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// If no host keys are defined we try to use or generate the default ones.
|
|
|
|
func (c *Configuration) checkAndLoadHostKeys(configDir string, serverConfig *ssh.ServerConfig) error {
|
|
|
|
if err := c.checkHostKeyAutoGeneration(configDir); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-04-01 06:03:56 +00:00
|
|
|
hostCertificates, err := c.loadHostCertificates(configDir)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-12-08 10:18:34 +00:00
|
|
|
serviceStatus.HostKeys = nil
|
|
|
|
for _, hostKey := range c.HostKeys {
|
2021-07-11 13:26:51 +00:00
|
|
|
if !util.IsFileInputValid(hostKey) {
|
2020-10-21 12:27:58 +00:00
|
|
|
logger.Warn(logSender, "", "unable to load invalid host key %#v", hostKey)
|
|
|
|
logger.WarnToConsole("unable to load invalid host key %#v", hostKey)
|
2020-05-16 13:15:32 +00:00
|
|
|
continue
|
|
|
|
}
|
2020-05-16 21:26:44 +00:00
|
|
|
if !filepath.IsAbs(hostKey) {
|
|
|
|
hostKey = filepath.Join(configDir, hostKey)
|
2020-04-09 21:32:42 +00:00
|
|
|
}
|
2020-10-21 12:27:58 +00:00
|
|
|
logger.Info(logSender, "", "Loading private host key %#v", hostKey)
|
2020-04-09 21:32:42 +00:00
|
|
|
|
2021-02-25 20:53:04 +00:00
|
|
|
privateBytes, err := os.ReadFile(hostKey)
|
2020-04-09 21:32:42 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
private, err := ssh.ParsePrivateKey(privateBytes)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-12-08 10:18:34 +00:00
|
|
|
k := HostKey{
|
|
|
|
Path: hostKey,
|
|
|
|
Fingerprint: ssh.FingerprintSHA256(private.PublicKey()),
|
|
|
|
}
|
|
|
|
serviceStatus.HostKeys = append(serviceStatus.HostKeys, k)
|
2020-10-21 12:27:58 +00:00
|
|
|
logger.Info(logSender, "", "Host key %#v loaded, type %#v, fingerprint %#v", hostKey,
|
2020-12-08 10:18:34 +00:00
|
|
|
private.PublicKey().Type(), k.Fingerprint)
|
2020-04-09 21:32:42 +00:00
|
|
|
|
|
|
|
// Add private key to the server configuration.
|
|
|
|
serverConfig.AddHostKey(private)
|
2022-04-01 06:03:56 +00:00
|
|
|
for _, cert := range hostCertificates {
|
|
|
|
signer, err := ssh.NewCertSigner(cert, private)
|
|
|
|
if err == nil {
|
|
|
|
serverConfig.AddHostKey(signer)
|
|
|
|
logger.Info(logSender, "", "Host certificate loaded for host key %#v, fingerprint %#v",
|
|
|
|
hostKey, ssh.FingerprintSHA256(signer.PublicKey()))
|
|
|
|
}
|
|
|
|
}
|
2020-04-09 21:32:42 +00:00
|
|
|
}
|
2021-04-01 16:53:48 +00:00
|
|
|
var fp []string
|
|
|
|
for idx := range serviceStatus.HostKeys {
|
|
|
|
h := &serviceStatus.HostKeys[idx]
|
|
|
|
fp = append(fp, h.Fingerprint)
|
|
|
|
}
|
|
|
|
vfs.SetSFTPFingerprints(fp)
|
2020-02-16 17:17:39 +00:00
|
|
|
return nil
|
2019-08-02 09:17:23 +00:00
|
|
|
}
|
|
|
|
|
2022-04-01 06:03:56 +00:00
|
|
|
func (c *Configuration) loadHostCertificates(configDir string) ([]*ssh.Certificate, error) {
|
|
|
|
var certs []*ssh.Certificate
|
|
|
|
for _, certPath := range c.HostCertificates {
|
|
|
|
if !util.IsFileInputValid(certPath) {
|
|
|
|
logger.Warn(logSender, "", "unable to load invalid host certificate %#v", certPath)
|
|
|
|
logger.WarnToConsole("unable to load invalid host certificate %#v", certPath)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if !filepath.IsAbs(certPath) {
|
|
|
|
certPath = filepath.Join(configDir, certPath)
|
|
|
|
}
|
|
|
|
certBytes, err := os.ReadFile(certPath)
|
|
|
|
if err != nil {
|
|
|
|
return certs, fmt.Errorf("unable to load host certificate %#v: %w", certPath, err)
|
|
|
|
}
|
|
|
|
parsed, _, _, _, err := ssh.ParseAuthorizedKey(certBytes)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("unable to parse host certificate %#v: %w", certPath, err)
|
|
|
|
}
|
|
|
|
cert, ok := parsed.(*ssh.Certificate)
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("the file %#v is not an SSH certificate", certPath)
|
|
|
|
}
|
|
|
|
if cert.CertType != ssh.HostCert {
|
|
|
|
return nil, fmt.Errorf("the file %#v is not an host certificate", certPath)
|
|
|
|
}
|
|
|
|
certs = append(certs, cert)
|
|
|
|
}
|
|
|
|
return certs, nil
|
|
|
|
}
|
|
|
|
|
2020-05-15 18:08:53 +00:00
|
|
|
func (c *Configuration) initializeCertChecker(configDir string) error {
|
|
|
|
for _, keyPath := range c.TrustedUserCAKeys {
|
2021-07-11 13:26:51 +00:00
|
|
|
if !util.IsFileInputValid(keyPath) {
|
2022-04-01 06:03:56 +00:00
|
|
|
logger.Warn(logSender, "", "unable to load invalid trusted user CA key %#v", keyPath)
|
|
|
|
logger.WarnToConsole("unable to load invalid trusted user CA key %#v", keyPath)
|
2020-05-16 13:15:32 +00:00
|
|
|
continue
|
|
|
|
}
|
2020-05-15 18:08:53 +00:00
|
|
|
if !filepath.IsAbs(keyPath) {
|
|
|
|
keyPath = filepath.Join(configDir, keyPath)
|
|
|
|
}
|
2021-02-25 20:53:04 +00:00
|
|
|
keyBytes, err := os.ReadFile(keyPath)
|
2020-05-15 18:08:53 +00:00
|
|
|
if err != nil {
|
|
|
|
logger.Warn(logSender, "", "error loading trusted user CA key %#v: %v", keyPath, err)
|
|
|
|
logger.WarnToConsole("error loading trusted user CA key %#v: %v", keyPath, err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
parsedKey, _, _, _, err := ssh.ParseAuthorizedKey(keyBytes)
|
|
|
|
if err != nil {
|
|
|
|
logger.Warn(logSender, "", "error parsing trusted user CA key %#v: %v", keyPath, err)
|
|
|
|
logger.WarnToConsole("error parsing trusted user CA key %#v: %v", keyPath, err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
c.parsedUserCAKeys = append(c.parsedUserCAKeys, parsedKey)
|
|
|
|
}
|
|
|
|
c.certChecker = &ssh.CertChecker{
|
|
|
|
SupportedCriticalOptions: []string{
|
|
|
|
sourceAddressCriticalOption,
|
|
|
|
},
|
|
|
|
IsUserAuthority: func(k ssh.PublicKey) bool {
|
|
|
|
for _, key := range c.parsedUserCAKeys {
|
|
|
|
if bytes.Equal(k.Marshal(), key.Marshal()) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
},
|
|
|
|
}
|
2022-03-31 19:49:06 +00:00
|
|
|
if c.RevokedUserCertsFile != "" {
|
|
|
|
if !util.IsFileInputValid(c.RevokedUserCertsFile) {
|
|
|
|
return fmt.Errorf("invalid revoked user certificate: %#v", c.RevokedUserCertsFile)
|
|
|
|
}
|
|
|
|
if !filepath.IsAbs(c.RevokedUserCertsFile) {
|
|
|
|
c.RevokedUserCertsFile = filepath.Join(configDir, c.RevokedUserCertsFile)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
revokedCertManager.filePath = c.RevokedUserCertsFile
|
|
|
|
return revokedCertManager.load()
|
2020-05-15 18:08:53 +00:00
|
|
|
}
|
|
|
|
|
2020-11-14 18:19:41 +00:00
|
|
|
func (c *Configuration) validatePublicKeyCredentials(conn ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
|
2019-07-20 10:26:52 +00:00
|
|
|
var err error
|
|
|
|
var user dataprovider.User
|
2019-09-05 19:35:53 +00:00
|
|
|
var keyID string
|
2019-09-13 16:45:36 +00:00
|
|
|
var sshPerm *ssh.Permissions
|
2020-05-15 18:08:53 +00:00
|
|
|
var certPerm *ssh.Permissions
|
2019-07-20 10:26:52 +00:00
|
|
|
|
2020-04-09 21:32:42 +00:00
|
|
|
connectionID := hex.EncodeToString(conn.SessionID())
|
2020-02-19 21:39:30 +00:00
|
|
|
method := dataprovider.SSHLoginMethodPublicKey
|
2021-07-11 13:26:51 +00:00
|
|
|
ipAddr := util.GetIPFromRemoteAddress(conn.RemoteAddr().String())
|
2020-05-15 18:08:53 +00:00
|
|
|
cert, ok := pubKey.(*ssh.Certificate)
|
2022-03-31 19:49:06 +00:00
|
|
|
var certFingerprint string
|
2020-05-15 18:08:53 +00:00
|
|
|
if ok {
|
2022-03-31 19:49:06 +00:00
|
|
|
certFingerprint = ssh.FingerprintSHA256(cert.Key)
|
2020-05-15 18:08:53 +00:00
|
|
|
if cert.CertType != ssh.UserCert {
|
|
|
|
err = fmt.Errorf("ssh: cert has type %d", cert.CertType)
|
2021-01-26 17:05:44 +00:00
|
|
|
user.Username = conn.User()
|
|
|
|
updateLoginMetrics(&user, ipAddr, method, err)
|
2020-05-15 18:08:53 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if !c.certChecker.IsUserAuthority(cert.SignatureKey) {
|
2022-03-24 21:03:17 +00:00
|
|
|
err = errors.New("ssh: certificate signed by unrecognized authority")
|
2021-01-26 17:05:44 +00:00
|
|
|
user.Username = conn.User()
|
|
|
|
updateLoginMetrics(&user, ipAddr, method, err)
|
2020-05-15 18:08:53 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
2022-03-31 16:16:50 +00:00
|
|
|
if len(cert.ValidPrincipals) == 0 {
|
2022-03-31 19:49:06 +00:00
|
|
|
err = fmt.Errorf("ssh: certificate %s has no valid principals, user: \"%s\"", certFingerprint, conn.User())
|
|
|
|
user.Username = conn.User()
|
|
|
|
updateLoginMetrics(&user, ipAddr, method, err)
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if revokedCertManager.isRevoked(certFingerprint) {
|
|
|
|
err = fmt.Errorf("ssh: certificate %s is revoked", certFingerprint)
|
2022-03-31 16:16:50 +00:00
|
|
|
user.Username = conn.User()
|
|
|
|
updateLoginMetrics(&user, ipAddr, method, err)
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-05-15 18:08:53 +00:00
|
|
|
if err := c.certChecker.CheckCert(conn.User(), cert); err != nil {
|
2021-01-26 17:05:44 +00:00
|
|
|
user.Username = conn.User()
|
|
|
|
updateLoginMetrics(&user, ipAddr, method, err)
|
2020-05-15 18:08:53 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
certPerm = &cert.Permissions
|
|
|
|
}
|
2022-03-31 16:16:50 +00:00
|
|
|
if user, keyID, err = dataprovider.CheckUserAndPubKey(conn.User(), pubKey.Marshal(), ipAddr, common.ProtocolSSH, ok); err == nil {
|
|
|
|
if ok {
|
2022-03-31 19:49:06 +00:00
|
|
|
keyID = fmt.Sprintf("%s: ID: %s, serial: %v, CA %s %s", certFingerprint,
|
2022-03-31 16:16:50 +00:00
|
|
|
cert.KeyId, cert.Serial, cert.Type(), ssh.FingerprintSHA256(cert.SignatureKey))
|
|
|
|
}
|
2020-04-09 21:32:42 +00:00
|
|
|
if user.IsPartialAuth(method) {
|
|
|
|
logger.Debug(logSender, connectionID, "user %#v authenticated with partial success", conn.User())
|
2020-05-16 13:15:32 +00:00
|
|
|
return certPerm, ssh.ErrPartialSuccess
|
2020-04-09 21:32:42 +00:00
|
|
|
}
|
2021-02-16 18:11:36 +00:00
|
|
|
sshPerm, err = loginUser(&user, method, keyID, conn)
|
2020-05-15 18:08:53 +00:00
|
|
|
if err == nil && certPerm != nil {
|
|
|
|
// if we have a SSH user cert we need to merge certificate permissions with our ones
|
|
|
|
// we only set Extensions, so CriticalOptions are always the ones from the certificate
|
|
|
|
sshPerm.CriticalOptions = certPerm.CriticalOptions
|
|
|
|
if certPerm.Extensions != nil {
|
|
|
|
for k, v := range certPerm.Extensions {
|
|
|
|
sshPerm.Extensions[k] = v
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-02-19 21:39:30 +00:00
|
|
|
}
|
2021-01-26 17:05:44 +00:00
|
|
|
user.Username = conn.User()
|
|
|
|
updateLoginMetrics(&user, ipAddr, method, err)
|
2019-09-13 16:45:36 +00:00
|
|
|
return sshPerm, err
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
2020-11-14 18:19:41 +00:00
|
|
|
func (c *Configuration) validatePasswordCredentials(conn ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
|
2019-07-20 10:26:52 +00:00
|
|
|
var err error
|
|
|
|
var user dataprovider.User
|
2019-09-13 16:45:36 +00:00
|
|
|
var sshPerm *ssh.Permissions
|
2019-07-20 10:26:52 +00:00
|
|
|
|
2020-08-12 14:15:12 +00:00
|
|
|
method := dataprovider.LoginMethodPassword
|
2020-04-09 21:32:42 +00:00
|
|
|
if len(conn.PartialSuccessMethods()) == 1 {
|
|
|
|
method = dataprovider.SSHLoginMethodKeyAndPassword
|
|
|
|
}
|
2021-07-11 13:26:51 +00:00
|
|
|
ipAddr := util.GetIPFromRemoteAddress(conn.RemoteAddr().String())
|
2020-08-12 14:15:12 +00:00
|
|
|
if user, err = dataprovider.CheckUserAndPass(conn.User(), string(pass), ipAddr, common.ProtocolSSH); err == nil {
|
2021-02-16 18:11:36 +00:00
|
|
|
sshPerm, err = loginUser(&user, method, "", conn)
|
2020-02-19 21:39:30 +00:00
|
|
|
}
|
2021-01-26 17:05:44 +00:00
|
|
|
user.Username = conn.User()
|
|
|
|
updateLoginMetrics(&user, ipAddr, method, err)
|
2020-01-21 09:54:05 +00:00
|
|
|
return sshPerm, err
|
|
|
|
}
|
|
|
|
|
2020-11-14 18:19:41 +00:00
|
|
|
func (c *Configuration) validateKeyboardInteractiveCredentials(conn ssh.ConnMetadata, client ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) {
|
2020-01-21 09:54:05 +00:00
|
|
|
var err error
|
|
|
|
var user dataprovider.User
|
|
|
|
var sshPerm *ssh.Permissions
|
|
|
|
|
2020-02-19 21:39:30 +00:00
|
|
|
method := dataprovider.SSHLoginMethodKeyboardInteractive
|
2020-04-09 21:32:42 +00:00
|
|
|
if len(conn.PartialSuccessMethods()) == 1 {
|
|
|
|
method = dataprovider.SSHLoginMethodKeyAndKeyboardInt
|
|
|
|
}
|
2021-07-11 13:26:51 +00:00
|
|
|
ipAddr := util.GetIPFromRemoteAddress(conn.RemoteAddr().String())
|
2020-08-12 14:15:12 +00:00
|
|
|
if user, err = dataprovider.CheckKeyboardInteractiveAuth(conn.User(), c.KeyboardInteractiveHook, client,
|
|
|
|
ipAddr, common.ProtocolSSH); err == nil {
|
2021-02-16 18:11:36 +00:00
|
|
|
sshPerm, err = loginUser(&user, method, "", conn)
|
2020-02-19 21:39:30 +00:00
|
|
|
}
|
2021-01-26 17:05:44 +00:00
|
|
|
user.Username = conn.User()
|
|
|
|
updateLoginMetrics(&user, ipAddr, method, err)
|
2020-05-15 18:08:53 +00:00
|
|
|
return sshPerm, err
|
|
|
|
}
|
|
|
|
|
2021-01-26 17:05:44 +00:00
|
|
|
func updateLoginMetrics(user *dataprovider.User, ip, method string, err error) {
|
2021-07-11 13:26:51 +00:00
|
|
|
metric.AddLoginAttempt(method)
|
2020-02-19 21:39:30 +00:00
|
|
|
if err != nil {
|
2021-01-26 17:05:44 +00:00
|
|
|
logger.ConnectionFailedLog(user.Username, ip, method, common.ProtocolSSH, err.Error())
|
2021-01-02 13:05:09 +00:00
|
|
|
if method != dataprovider.SSHLoginMethodPublicKey {
|
|
|
|
// some clients try all available public keys for a user, we
|
|
|
|
// record failed login key auth only once for session if the
|
|
|
|
// authentication fails in checkAuthError
|
|
|
|
event := common.HostEventLoginFailed
|
2021-07-11 13:26:51 +00:00
|
|
|
if _, ok := err.(*util.RecordNotFoundError); ok {
|
2021-01-02 13:05:09 +00:00
|
|
|
event = common.HostEventUserNotFound
|
|
|
|
}
|
|
|
|
common.AddDefenderEvent(ip, event)
|
|
|
|
}
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
2021-07-11 13:26:51 +00:00
|
|
|
metric.AddLoginResult(method, err)
|
2021-01-26 17:05:44 +00:00
|
|
|
dataprovider.ExecutePostLoginHook(user, method, ip, common.ProtocolSSH, err)
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
2022-03-31 19:49:06 +00:00
|
|
|
|
|
|
|
type revokedCertificates struct {
|
|
|
|
filePath string
|
|
|
|
mu sync.RWMutex
|
|
|
|
certs map[string]bool
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *revokedCertificates) load() error {
|
|
|
|
if r.filePath == "" {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
logger.Debug(logSender, "", "loading revoked user certificate file %#v", r.filePath)
|
|
|
|
info, err := os.Stat(r.filePath)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("unable to load revoked user certificate file %#v: %w", r.filePath, err)
|
|
|
|
}
|
|
|
|
maxSize := int64(1048576 * 5) // 5MB
|
|
|
|
if info.Size() > maxSize {
|
|
|
|
return fmt.Errorf("unable to load revoked user certificate file %#v size too big: %v/%v bytes",
|
|
|
|
r.filePath, info.Size(), maxSize)
|
|
|
|
}
|
|
|
|
content, err := os.ReadFile(r.filePath)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("unable to read revoked user certificate file %#v: %w", r.filePath, err)
|
|
|
|
}
|
|
|
|
var certs []string
|
|
|
|
err = json.Unmarshal(content, &certs)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("unable to parse revoked user certificate file %#v: %w", r.filePath, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
r.mu.Lock()
|
|
|
|
defer r.mu.Unlock()
|
|
|
|
|
|
|
|
r.certs = map[string]bool{}
|
|
|
|
for _, fp := range certs {
|
|
|
|
r.certs[fp] = true
|
|
|
|
}
|
|
|
|
logger.Debug(logSender, "", "revoked user certificate file %#v loaded, entries: %v", r.filePath, len(r.certs))
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *revokedCertificates) isRevoked(fp string) bool {
|
|
|
|
r.mu.RLock()
|
|
|
|
defer r.mu.RUnlock()
|
|
|
|
|
|
|
|
return r.certs[fp]
|
|
|
|
}
|
|
|
|
|
|
|
|
// Reload reloads the list of revoked user certificates
|
|
|
|
func Reload() error {
|
|
|
|
return revokedCertManager.load()
|
|
|
|
}
|