2019-07-20 10:26:52 +00:00
|
|
|
package sftpd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rand"
|
|
|
|
"crypto/rsa"
|
|
|
|
"crypto/x509"
|
|
|
|
"encoding/hex"
|
|
|
|
"encoding/json"
|
|
|
|
"encoding/pem"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
"net"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"strconv"
|
2019-08-24 12:41:15 +00:00
|
|
|
"strings"
|
2019-07-20 10:26:52 +00:00
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/drakkan/sftpgo/dataprovider"
|
|
|
|
"github.com/drakkan/sftpgo/logger"
|
2019-09-13 16:45:36 +00:00
|
|
|
"github.com/drakkan/sftpgo/metrics"
|
2019-07-20 10:26:52 +00:00
|
|
|
"github.com/drakkan/sftpgo/utils"
|
|
|
|
"github.com/pkg/sftp"
|
|
|
|
"golang.org/x/crypto/ssh"
|
|
|
|
)
|
|
|
|
|
2019-08-01 07:42:15 +00:00
|
|
|
const defaultPrivateKeyName = "id_rsa"
|
|
|
|
|
2019-11-12 06:37:47 +00:00
|
|
|
var sftpExtensions = []string{"posix-rename@openssh.com"}
|
|
|
|
|
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"`
|
2019-07-30 18:51:29 +00:00
|
|
|
// The port used for serving SFTP requests
|
2019-08-07 20:46:13 +00:00
|
|
|
BindPort int `json:"bind_port" mapstructure:"bind_port"`
|
2019-07-30 18:51:29 +00:00
|
|
|
// The address to listen on. A blank value means listen on all available network interfaces.
|
2019-08-07 20:46:13 +00:00
|
|
|
BindAddress string `json:"bind_address" mapstructure:"bind_address"`
|
2019-07-30 18:51:29 +00:00
|
|
|
// Maximum idle timeout as minutes. If a client is idle for a time that exceeds this setting it will be disconnected
|
2019-08-07 20:46:13 +00:00
|
|
|
IdleTimeout int `json:"idle_timeout" mapstructure:"idle_timeout"`
|
2019-07-30 18:51:29 +00:00
|
|
|
// Maximum number of authentication attempts permitted per connection.
|
|
|
|
// If set to a negative number, the number of attempts are unlimited.
|
|
|
|
// 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"`
|
2019-07-30 18:51:29 +00:00
|
|
|
// Umask for new files
|
2019-08-07 20:46:13 +00:00
|
|
|
Umask string `json:"umask" mapstructure:"umask"`
|
2019-08-04 07:37:58 +00:00
|
|
|
// UploadMode 0 means standard, the files are uploaded directly to the requested path.
|
|
|
|
// 1 means atomic: the files are uploaded to a temporary path and renamed to the requested path
|
|
|
|
// when the client ends the upload. Atomic mode avoid problems such as a web server that
|
|
|
|
// serves partial files when the files are being uploaded.
|
2019-10-09 15:33:30 +00:00
|
|
|
// In atomic mode if there is an upload error the temporary file is deleted and so the requested
|
|
|
|
// upload path will not contain a partial file.
|
|
|
|
// 2 means atomic with resume support: as atomic but if there is an upload error the temporary
|
|
|
|
// file is renamed to the requested path and not deleted, this way a client can reconnect and resume
|
|
|
|
// the upload.
|
2019-08-07 20:46:13 +00:00
|
|
|
UploadMode int `json:"upload_mode" mapstructure:"upload_mode"`
|
2019-07-30 18:51:29 +00:00
|
|
|
// Actions to execute on SFTP create, download, delete and rename
|
2019-08-07 20:46:13 +00:00
|
|
|
Actions Actions `json:"actions" mapstructure:"actions"`
|
2019-08-01 07:42:15 +00:00
|
|
|
// Keys are a list of host keys
|
2019-08-07 20:46:13 +00:00
|
|
|
Keys []Key `json:"keys" mapstructure:"keys"`
|
2019-08-24 12:41:15 +00:00
|
|
|
// IsSCPEnabled determines if experimental SCP support is enabled.
|
|
|
|
// We have our own SCP implementation since we can't rely on scp system
|
|
|
|
// command to properly 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
|
|
|
|
IsSCPEnabled bool `json:"enable_scp" mapstructure:"enable_scp"`
|
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"`
|
|
|
|
// 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-08-01 07:42:15 +00:00
|
|
|
}
|
|
|
|
|
2019-08-01 13:39:30 +00:00
|
|
|
// Key contains information about host keys
|
2019-08-01 07:42:15 +00:00
|
|
|
type Key struct {
|
2019-08-01 13:39:30 +00:00
|
|
|
// The private key path relative to the configuration directory or absolute
|
2019-08-07 20:46:13 +00:00
|
|
|
PrivateKey string `json:"private_key" mapstructure:"private_key"`
|
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)
|
|
|
|
}
|
|
|
|
|
2019-07-20 19:17:53 +00:00
|
|
|
// Initialize the SFTP server and add a persistent listener to handle inbound SFTP connections.
|
|
|
|
func (c Configuration) Initialize(configDir string) error {
|
2019-07-20 10:26:52 +00:00
|
|
|
umask, err := strconv.ParseUint(c.Umask, 8, 8)
|
|
|
|
if err == nil {
|
|
|
|
utils.SetUmask(int(umask), c.Umask)
|
|
|
|
} else {
|
2019-09-05 14:21:35 +00:00
|
|
|
logger.Warn(logSender, "", "error reading umask, please fix your config file: %v", err)
|
2019-07-31 06:14:31 +00:00
|
|
|
logger.WarnToConsole("error reading umask, please fix your config file: %v", err)
|
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
|
|
|
PasswordCallback: func(conn ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
|
|
|
|
sp, err := c.validatePasswordCredentials(conn, pass)
|
|
|
|
if err != nil {
|
2019-11-11 14:20:00 +00:00
|
|
|
return nil, &authenticationError{err: fmt.Sprintf("could not validate password credentials: %v", err)}
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return sp, nil
|
|
|
|
},
|
|
|
|
PublicKeyCallback: func(conn ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
|
|
|
|
sp, err := c.validatePublicKeyCredentials(conn, string(pubKey.Marshal()))
|
|
|
|
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
|
|
|
|
},
|
2019-07-26 11:35:43 +00:00
|
|
|
ServerVersion: "SSH-2.0-" + c.Banner,
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
2019-08-02 09:17:23 +00:00
|
|
|
err = c.checkHostKeys(configDir)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
2019-08-01 07:42:15 +00:00
|
|
|
for _, k := range c.Keys {
|
|
|
|
privateFile := k.PrivateKey
|
|
|
|
if !filepath.IsAbs(privateFile) {
|
|
|
|
privateFile = filepath.Join(configDir, privateFile)
|
|
|
|
}
|
2019-09-05 14:21:35 +00:00
|
|
|
logger.Info(logSender, "", "Loading private key: %s", privateFile)
|
2019-08-01 07:42:15 +00:00
|
|
|
|
|
|
|
privateBytes, err := ioutil.ReadFile(privateFile)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-07-20 10:26:52 +00:00
|
|
|
|
2019-08-01 07:42:15 +00:00
|
|
|
private, err := ssh.ParsePrivateKey(privateBytes)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-08-01 13:39:30 +00:00
|
|
|
// Add private key to the server configuration.
|
2019-08-01 07:42:15 +00:00
|
|
|
serverConfig.AddHostKey(private)
|
|
|
|
}
|
2019-07-20 10:26:52 +00:00
|
|
|
|
2019-09-03 10:08:09 +00:00
|
|
|
c.configureSecurityOptions(serverConfig)
|
|
|
|
c.configureLoginBanner(serverConfig, configDir)
|
2019-11-12 06:37:47 +00:00
|
|
|
c.configureSFTPExtensions()
|
2019-09-03 10:08:09 +00:00
|
|
|
|
2019-07-20 10:26:52 +00:00
|
|
|
listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", c.BindAddress, c.BindPort))
|
|
|
|
if err != nil {
|
2019-09-05 14:21:35 +00:00
|
|
|
logger.Warn(logSender, "", "error starting listener on address %s:%d: %v", c.BindAddress, c.BindPort, err)
|
2019-07-20 10:26:52 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-07-31 12:11:44 +00:00
|
|
|
actions = c.Actions
|
2019-08-04 07:37:58 +00:00
|
|
|
uploadMode = c.UploadMode
|
2019-09-05 14:21:35 +00:00
|
|
|
logger.Info(logSender, "", "server listener registered address: %v", listener.Addr().String())
|
2019-07-20 10:26:52 +00:00
|
|
|
if c.IdleTimeout > 0 {
|
|
|
|
startIdleTimer(time.Duration(c.IdleTimeout) * time.Minute)
|
|
|
|
}
|
|
|
|
|
|
|
|
for {
|
|
|
|
conn, _ := listener.Accept()
|
|
|
|
if conn != nil {
|
|
|
|
go c.AcceptInboundConnection(conn, serverConfig)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-03 10:08:09 +00:00
|
|
|
func (c Configuration) configureSecurityOptions(serverConfig *ssh.ServerConfig) {
|
|
|
|
if len(c.KexAlgorithms) > 0 {
|
|
|
|
serverConfig.KeyExchanges = c.KexAlgorithms
|
|
|
|
}
|
|
|
|
if len(c.Ciphers) > 0 {
|
|
|
|
serverConfig.Ciphers = c.Ciphers
|
|
|
|
}
|
|
|
|
if len(c.MACs) > 0 {
|
|
|
|
serverConfig.MACs = c.MACs
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c Configuration) configureLoginBanner(serverConfig *ssh.ServerConfig, configDir string) error {
|
|
|
|
var err error
|
|
|
|
if len(c.LoginBannerFile) > 0 {
|
|
|
|
bannerFilePath := c.LoginBannerFile
|
|
|
|
if !filepath.IsAbs(bannerFilePath) {
|
|
|
|
bannerFilePath = filepath.Join(configDir, bannerFilePath)
|
|
|
|
}
|
|
|
|
var banner []byte
|
|
|
|
banner, err = ioutil.ReadFile(bannerFilePath)
|
|
|
|
if err == nil {
|
|
|
|
serverConfig.BannerCallback = func(conn ssh.ConnMetadata) string {
|
|
|
|
return string(banner)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
logger.WarnToConsole("unable to read 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
|
|
|
}
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-11-12 06:37:47 +00:00
|
|
|
func (c Configuration) configureSFTPExtensions() error {
|
|
|
|
err := sftp.SetSFTPExtensions(sftpExtensions...)
|
|
|
|
if err != nil {
|
|
|
|
logger.WarnToConsole("unable to configure SFTP extensions: %v", err)
|
|
|
|
logger.Warn(logSender, "", "unable to configure SFTP extensions: %v", err)
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
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.
|
2019-07-20 10:26:52 +00:00
|
|
|
func (c Configuration) AcceptInboundConnection(conn net.Conn, config *ssh.ServerConfig) {
|
|
|
|
|
|
|
|
// 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
|
|
|
|
conn.SetDeadline(time.Now().Add(handshakeTimeout))
|
2019-11-11 14:20:00 +00:00
|
|
|
remoteAddr := conn.RemoteAddr()
|
2019-07-20 10:26:52 +00:00
|
|
|
sconn, chans, reqs, err := ssh.NewServerConn(conn, config)
|
|
|
|
if err != nil {
|
2019-09-05 14:21:35 +00:00
|
|
|
logger.Warn(logSender, "", "failed to accept an incoming connection: %v", err)
|
2019-11-11 14:20:00 +00:00
|
|
|
if _, ok := err.(*ssh.ServerAuthError); !ok {
|
|
|
|
logger.ConnectionFailedLog("", utils.GetIPFromRemoteAddress(remoteAddr.String()), "no_auth_tryed", err.Error())
|
|
|
|
}
|
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
|
|
|
|
conn.SetDeadline(time.Time{})
|
2019-07-20 10:26:52 +00:00
|
|
|
|
2019-08-24 12:41:15 +00:00
|
|
|
var user dataprovider.User
|
2019-09-05 19:35:53 +00:00
|
|
|
var loginType string
|
2019-08-24 12:41:15 +00:00
|
|
|
|
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
|
|
|
|
json.Unmarshal([]byte(sconn.Permissions.Extensions["user"]), &user)
|
2019-08-24 12:41:15 +00:00
|
|
|
|
2019-09-05 19:35:53 +00:00
|
|
|
loginType = sconn.Permissions.Extensions["login_type"]
|
2019-08-24 12:41:15 +00:00
|
|
|
connectionID := hex.EncodeToString(sconn.SessionID())
|
|
|
|
|
|
|
|
connection := Connection{
|
|
|
|
ID: connectionID,
|
|
|
|
User: user,
|
|
|
|
ClientVersion: string(sconn.ClientVersion()),
|
2019-11-11 14:20:00 +00:00
|
|
|
RemoteAddr: remoteAddr,
|
2019-08-24 12:41:15 +00:00
|
|
|
StartTime: time.Now(),
|
|
|
|
lastActivity: time.Now(),
|
|
|
|
lock: new(sync.Mutex),
|
2019-09-11 07:41:46 +00:00
|
|
|
netConn: conn,
|
2019-09-11 14:29:56 +00:00
|
|
|
channel: nil,
|
2019-08-24 12:41:15 +00:00
|
|
|
}
|
2019-11-11 14:20:00 +00:00
|
|
|
connection.Log(logger.LevelInfo, logSender, "User id: %d, logged in with: %#v, username: %#v, home_dir: %#v remote addr: %#v",
|
|
|
|
user.ID, loginType, user.Username, user.HomeDir, remoteAddr.String())
|
2019-08-24 12:41:15 +00:00
|
|
|
|
2019-07-20 10:26:52 +00:00
|
|
|
go ssh.DiscardRequests(reqs)
|
|
|
|
|
|
|
|
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" {
|
2019-09-06 13:19:01 +00:00
|
|
|
connection.Log(logger.LevelDebug, logSender, "received an unknown channel type: %v", newChannel.ChannelType())
|
2019-07-20 10:26:52 +00:00
|
|
|
newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
channel, requests, err := newChannel.Accept()
|
|
|
|
if err != nil {
|
2019-09-06 13:19:01 +00:00
|
|
|
connection.Log(logger.LevelWarn, logSender, "could not accept a channel: %v", err)
|
2019-07-20 10:26:52 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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)
|
|
|
|
go func(in <-chan *ssh.Request) {
|
|
|
|
for req := range in {
|
|
|
|
ok := false
|
|
|
|
|
|
|
|
switch req.Type {
|
|
|
|
case "subsystem":
|
|
|
|
if string(req.Payload[4:]) == "sftp" {
|
|
|
|
ok = true
|
2019-08-24 12:41:15 +00:00
|
|
|
connection.protocol = protocolSFTP
|
2019-09-11 14:29:56 +00:00
|
|
|
connection.channel = channel
|
2019-08-24 12:41:15 +00:00
|
|
|
go c.handleSftpConnection(channel, connection)
|
|
|
|
}
|
|
|
|
case "exec":
|
|
|
|
if c.IsSCPEnabled {
|
|
|
|
var msg execMsg
|
|
|
|
if err := ssh.Unmarshal(req.Payload, &msg); err == nil {
|
|
|
|
name, scpArgs, err := parseCommandPayload(msg.Command)
|
2019-09-10 16:47:21 +00:00
|
|
|
connection.Log(logger.LevelDebug, logSender, "new exec command: %#v args: %v user: %v, error: %v",
|
2019-10-25 16:37:12 +00:00
|
|
|
name, scpArgs, connection.User.Username, err)
|
2019-08-24 12:41:15 +00:00
|
|
|
if err == nil && name == "scp" && len(scpArgs) >= 2 {
|
|
|
|
ok = true
|
|
|
|
connection.protocol = protocolSCP
|
2019-09-11 14:29:56 +00:00
|
|
|
connection.channel = channel
|
2019-08-24 12:41:15 +00:00
|
|
|
scpCommand := scpCommand{
|
|
|
|
connection: connection,
|
|
|
|
args: scpArgs,
|
|
|
|
}
|
|
|
|
go scpCommand.handle()
|
|
|
|
}
|
|
|
|
}
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
req.Reply(ok, nil)
|
|
|
|
}
|
|
|
|
}(requests)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-11 14:29:56 +00:00
|
|
|
func (c Configuration) handleSftpConnection(channel ssh.Channel, connection Connection) {
|
2019-10-10 07:04:17 +00:00
|
|
|
addConnection(connection)
|
|
|
|
defer removeConnection(connection)
|
2019-08-24 12:41:15 +00:00
|
|
|
// Create a new handler for the currently logged in user's server.
|
|
|
|
handler := c.createHandler(connection)
|
2019-07-20 10:26:52 +00:00
|
|
|
|
2019-08-24 12:41:15 +00:00
|
|
|
// Create the server instance for the channel using the handler we created above.
|
|
|
|
server := sftp.NewRequestServer(channel, handler)
|
|
|
|
|
|
|
|
if err := server.Serve(); err == io.EOF {
|
2019-09-07 16:21:03 +00:00
|
|
|
connection.Log(logger.LevelDebug, logSender, "connection closed")
|
2019-08-24 12:41:15 +00:00
|
|
|
server.Close()
|
|
|
|
} else if err != nil {
|
2019-09-07 16:21:03 +00:00
|
|
|
connection.Log(logger.LevelWarn, logSender, "connection closed with error: %v", err)
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
2019-08-24 12:41:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c Configuration) createHandler(connection Connection) sftp.Handlers {
|
2019-07-20 10:26:52 +00:00
|
|
|
|
|
|
|
return sftp.Handlers{
|
|
|
|
FileGet: connection,
|
|
|
|
FilePut: connection,
|
|
|
|
FileCmd: connection,
|
|
|
|
FileList: connection,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-05 19:35:53 +00:00
|
|
|
func loginUser(user dataprovider.User, loginType string) (*ssh.Permissions, error) {
|
2019-07-20 10:26:52 +00:00
|
|
|
if !filepath.IsAbs(user.HomeDir) {
|
2019-09-05 21:42:00 +00:00
|
|
|
logger.Warn(logSender, "", "user %v has 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-10-24 16:50:35 +00:00
|
|
|
return nil, fmt.Errorf("cannot login user with invalid home dir: %v", user.HomeDir)
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
if _, err := os.Stat(user.HomeDir); os.IsNotExist(err) {
|
|
|
|
err := os.MkdirAll(user.HomeDir, 0777)
|
2019-09-09 10:58:07 +00:00
|
|
|
logger.Debug(logSender, "", "home directory %#v for user %v does not exist, try to create, mkdir error: %v",
|
|
|
|
user.HomeDir, user.Username, err)
|
2019-07-20 10:26:52 +00:00
|
|
|
if err == nil {
|
|
|
|
utils.SetPathPermissions(user.HomeDir, user.GetUID(), user.GetGID())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if user.MaxSessions > 0 {
|
|
|
|
activeSessions := getActiveSessions(user.Username)
|
|
|
|
if activeSessions >= user.MaxSessions {
|
2019-09-05 14:21:35 +00:00
|
|
|
logger.Debug(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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
json, err := json.Marshal(user)
|
|
|
|
if err != nil {
|
2019-09-05 14:21:35 +00:00
|
|
|
logger.Warn(logSender, "", "error serializing user info: %v, authentication rejected", err)
|
2019-07-20 10:26:52 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
p := &ssh.Permissions{}
|
|
|
|
p.Extensions = make(map[string]string)
|
|
|
|
p.Extensions["user"] = string(json)
|
2019-09-05 19:35:53 +00:00
|
|
|
p.Extensions["login_type"] = loginType
|
2019-07-20 10:26:52 +00:00
|
|
|
return p, nil
|
|
|
|
}
|
|
|
|
|
2019-08-02 09:17:23 +00:00
|
|
|
// If no host keys are defined we try to use or generate the default one.
|
|
|
|
func (c *Configuration) checkHostKeys(configDir string) error {
|
|
|
|
var err error
|
|
|
|
if len(c.Keys) == 0 {
|
|
|
|
autoFile := filepath.Join(configDir, defaultPrivateKeyName)
|
|
|
|
if _, err = os.Stat(autoFile); os.IsNotExist(err) {
|
2019-09-05 14:21:35 +00:00
|
|
|
logger.Info(logSender, "", "No host keys configured and %#v does not exist; creating new private key for server", autoFile)
|
|
|
|
logger.InfoToConsole("No host keys configured and %#v does not exist; creating new private key for server", autoFile)
|
2019-08-02 09:17:23 +00:00
|
|
|
err = c.generatePrivateKey(autoFile)
|
|
|
|
}
|
|
|
|
|
|
|
|
c.Keys = append(c.Keys, Key{PrivateKey: defaultPrivateKeyName})
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-07-20 10:26:52 +00:00
|
|
|
func (c Configuration) validatePublicKeyCredentials(conn ssh.ConnMetadata, pubKey string) (*ssh.Permissions, error) {
|
|
|
|
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
|
2019-07-20 10:26:52 +00:00
|
|
|
|
2019-09-13 16:45:36 +00:00
|
|
|
metrics.AddLoginAttempt(true)
|
2019-09-05 19:35:53 +00:00
|
|
|
if user, keyID, err = dataprovider.CheckUserAndPubKey(dataProvider, conn.User(), pubKey); err == nil {
|
2019-09-13 16:45:36 +00:00
|
|
|
sshPerm, err = loginUser(user, "public_key:"+keyID)
|
2019-11-11 14:20:00 +00:00
|
|
|
} else {
|
|
|
|
logger.ConnectionFailedLog(conn.User(), utils.GetIPFromRemoteAddress(conn.RemoteAddr().String()), "public_key", err.Error())
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
2019-09-13 16:45:36 +00:00
|
|
|
metrics.AddLoginResult(true, err)
|
|
|
|
return sshPerm, err
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c Configuration) validatePasswordCredentials(conn ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
|
|
|
|
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
|
|
|
|
2019-09-13 16:45:36 +00:00
|
|
|
metrics.AddLoginAttempt(false)
|
2019-07-20 10:26:52 +00:00
|
|
|
if user, err = dataprovider.CheckUserAndPass(dataProvider, conn.User(), string(pass)); err == nil {
|
2019-09-13 16:45:36 +00:00
|
|
|
sshPerm, err = loginUser(user, "password")
|
2019-11-11 14:20:00 +00:00
|
|
|
} else {
|
|
|
|
logger.ConnectionFailedLog(conn.User(), utils.GetIPFromRemoteAddress(conn.RemoteAddr().String()), "password", err.Error())
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
2019-09-13 16:45:36 +00:00
|
|
|
metrics.AddLoginResult(false, err)
|
|
|
|
return sshPerm, err
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Generates a private key that will be used by the SFTP server.
|
2019-08-01 07:42:15 +00:00
|
|
|
func (c Configuration) generatePrivateKey(file string) error {
|
2019-07-20 10:26:52 +00:00
|
|
|
key, err := rsa.GenerateKey(rand.Reader, 4096)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-08-01 07:42:15 +00:00
|
|
|
o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
|
2019-07-20 10:26:52 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer o.Close()
|
|
|
|
|
|
|
|
pkey := &pem.Block{
|
|
|
|
Type: "RSA PRIVATE KEY",
|
|
|
|
Bytes: x509.MarshalPKCS1PrivateKey(key),
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := pem.Encode(o, pkey); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2019-08-24 12:41:15 +00:00
|
|
|
|
|
|
|
func parseCommandPayload(command string) (string, []string, error) {
|
|
|
|
parts := strings.Split(command, " ")
|
|
|
|
if len(parts) < 2 {
|
|
|
|
return parts[0], []string{}, nil
|
|
|
|
}
|
|
|
|
return parts[0], parts[1:], nil
|
|
|
|
}
|