wings/sftp/server.go

398 lines
11 KiB
Go
Raw Permalink Normal View History

package sftp
import (
2021-07-17 23:22:13 +00:00
"bytes"
2021-02-02 04:59:17 +00:00
"context"
2021-07-17 23:22:13 +00:00
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"io"
"io/ioutil"
"net"
"os"
"path"
2021-02-02 04:59:17 +00:00
"regexp"
2021-01-10 23:06:06 +00:00
"strconv"
"strings"
2021-01-10 01:22:39 +00:00
"emperror.dev/errors"
2021-01-10 01:22:39 +00:00
"github.com/apex/log"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
"github.com/pterodactyl/wings/config"
2021-02-02 04:59:17 +00:00
"github.com/pterodactyl/wings/remote"
"github.com/pterodactyl/wings/server"
)
2021-02-02 04:59:17 +00:00
// Usernames all follow the same format, so don't even bother hitting the API if the username is not
// at least in the expected format. This is very basic protection against random bots finding the SFTP
// server and sending a flood of usernames.
var validUsernameRegexp = regexp.MustCompile(`^(?i)(.+)\.([a-z0-9]{8})$`)
//goland:noinspection GoNameStartsWithPackageName
type SFTPServer struct {
2021-01-26 04:28:24 +00:00
manager *server.Manager
2021-01-10 23:06:06 +00:00
BasePath string
ReadOnly bool
Listen string
}
2021-01-26 04:28:24 +00:00
func New(m *server.Manager) *SFTPServer {
cfg := config.Get().System
return &SFTPServer{
2021-01-26 04:28:24 +00:00
manager: m,
2021-01-10 23:06:06 +00:00
BasePath: cfg.Data,
ReadOnly: cfg.Sftp.ReadOnly,
Listen: cfg.Sftp.Address + ":" + strconv.Itoa(cfg.Sftp.Port),
}
}
// Run starts the SFTP server and add a persistent listener to handle inbound
// SFTP connections. This will automatically generate an ED25519 key if one does
// not already exist on the system for host key verification purposes.
func (c *SFTPServer) Run() error {
2021-07-17 23:22:13 +00:00
keys, err := c.loadPrivateKeys()
if err != nil {
return err
}
2019-12-07 23:53:07 +00:00
2021-01-10 23:06:06 +00:00
conf := &ssh.ServerConfig{
2021-07-17 23:22:13 +00:00
NoClientAuth: false,
MaxAuthTries: 6,
PasswordCallback: c.passwordCallback,
PublicKeyCallback: c.publicKeyCallback,
}
for _, k := range keys {
conf.AddHostKey(k)
2021-01-10 23:06:06 +00:00
}
2019-12-08 01:35:45 +00:00
2021-01-10 23:06:06 +00:00
listener, err := net.Listen("tcp", c.Listen)
if err != nil {
return err
2019-12-08 01:35:45 +00:00
}
2021-01-10 23:06:06 +00:00
log.WithField("listen", c.Listen).Info("sftp server listening for connections")
for {
2021-01-10 23:06:06 +00:00
if conn, _ := listener.Accept(); conn != nil {
go func(conn net.Conn) {
defer conn.Close()
c.AcceptInbound(conn, conf)
}(conn)
}
}
}
2021-01-10 23:06:06 +00:00
// Handles an inbound connection to the instance and determines if we should serve the
// request or not.
2021-01-26 04:28:24 +00:00
func (c *SFTPServer) AcceptInbound(conn net.Conn, config *ssh.ServerConfig) {
// Before beginning a handshake must be performed on the incoming net.Conn
sconn, chans, reqs, err := ssh.NewServerConn(conn, config)
if err != nil {
return
2019-12-08 01:35:45 +00:00
}
defer sconn.Close()
go ssh.DiscardRequests(reqs)
2021-01-10 23:06:06 +00:00
for ch := range chans {
// If its not a session channel we just move on because its not something we
// know how to handle at this point.
2021-01-10 23:06:06 +00:00
if ch.ChannelType() != "session" {
2021-07-17 23:22:13 +00:00
_ = ch.Reject(ssh.UnknownChannelType, "unknown channel type")
continue
}
2021-01-10 23:06:06 +00:00
channel, requests, err := ch.Accept()
if err != nil {
continue
}
go func(in <-chan *ssh.Request) {
for req := range in {
2021-01-10 23:06:06 +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)
2021-07-17 23:22:13 +00:00
_ = req.Reply(req.Type == "subsystem" && string(req.Payload[4:]) == "sftp", nil)
}
}(requests)
2021-01-10 23:06:06 +00:00
// If no UUID has been set on this inbound request then we can assume we
// have screwed up something in the authentication code. This is a sanity
// check, but should never be encountered (ideally...).
//
// This will also attempt to match a specific server out of the global server
// store and return nil if there is no match.
uuid := sconn.Permissions.Extensions["uuid"]
2021-01-26 04:28:24 +00:00
srv := c.manager.Find(func(s *server.Server) bool {
2021-01-10 23:06:06 +00:00
if uuid == "" {
return false
}
return s.ID() == uuid
2021-01-10 23:06:06 +00:00
})
if srv == nil {
2021-07-17 23:22:13 +00:00
_ = conn.Close()
continue
}
2021-01-10 23:06:06 +00:00
// Spin up a SFTP server instance for the authenticated user's server allowing
// them access to the underlying filesystem.
handler := sftp.NewRequestServer(channel, NewHandler(sconn, srv).Handlers())
if err := handler.Serve(); err == io.EOF {
2021-07-17 23:22:13 +00:00
_ = handler.Close()
}
}
}
func (c *SFTPServer) loadPrivateKeys() ([]ssh.Signer, error) {
if _, err := os.Stat(path.Join(c.BasePath, ".sftp/id_rsa")); err != nil {
if !os.IsNotExist(err) {
return nil, err
}
if err := c.generateRSAPrivateKey(); err != nil {
return nil, err
}
}
rsaBytes, err := ioutil.ReadFile(path.Join(c.BasePath, ".sftp/id_rsa"))
if err != nil {
return nil, errors.Wrap(err, "sftp/server: could not read private key file")
}
rsaPrivateKey, err := ssh.ParsePrivateKey(rsaBytes)
if err != nil {
return nil, err
}
if _, err := os.Stat(path.Join(c.BasePath, ".sftp/id_ecdsa")); err != nil {
if !os.IsNotExist(err) {
return nil, err
}
if err := c.generateECDSAPrivateKey(); err != nil {
return nil, err
}
}
ecdsaBytes, err := ioutil.ReadFile(path.Join(c.BasePath, ".sftp/id_ecdsa"))
if err != nil {
return nil, errors.Wrap(err, "sftp/server: could not read private key file")
}
ecdsaPrivateKey, err := ssh.ParsePrivateKey(ecdsaBytes)
if err != nil {
return nil, err
}
if _, err := os.Stat(path.Join(c.BasePath, ".sftp/id_ed25519")); err != nil {
if !os.IsNotExist(err) {
return nil, err
}
2021-07-17 23:22:13 +00:00
if err := c.generateEd25519PrivateKey(); err != nil {
return nil, err
}
}
ed25519Bytes, err := ioutil.ReadFile(path.Join(c.BasePath, ".sftp/id_ed25519"))
if err != nil {
return nil, errors.Wrap(err, "sftp/server: could not read private key file")
}
2021-07-17 23:22:13 +00:00
ed25519PrivateKey, err := ssh.ParsePrivateKey(ed25519Bytes)
if err != nil {
return nil, err
}
return []ssh.Signer{
rsaPrivateKey,
ecdsaPrivateKey,
ed25519PrivateKey,
}, nil
}
2021-07-17 23:22:13 +00:00
// generateRSAPrivateKey generates a RSA-4096 private key that will be used by the SFTP server.
func (c *SFTPServer) generateRSAPrivateKey() error {
key, err := rsa.GenerateKey(rand.Reader, 4096)
2019-12-08 01:35:45 +00:00
if err != nil {
2021-07-17 23:22:13 +00:00
return err
}
2022-01-18 20:12:09 +00:00
if err := os.MkdirAll(path.Dir(c.PrivateKeyPath("rsa")), 0o755); err != nil {
2021-01-10 23:06:06 +00:00
return errors.Wrap(err, "sftp/server: could not create .sftp directory")
2019-12-08 01:35:45 +00:00
}
2022-01-18 20:12:09 +00:00
o, err := os.OpenFile(c.PrivateKeyPath("rsa"), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600)
if err != nil {
2021-07-17 23:22:13 +00:00
return err
}
defer o.Close()
2019-12-08 01:35:45 +00:00
2021-07-17 23:22:13 +00:00
if err := pem.Encode(o, &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
2021-07-17 23:22:13 +00:00
}); err != nil {
return err
}
return nil
}
// generateECDSAPrivateKey generates a ECDSA-P256 private key that will be used by the SFTP server.
func (c *SFTPServer) generateECDSAPrivateKey() error {
key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
if err != nil {
return err
}
2022-01-18 20:12:09 +00:00
if err := os.MkdirAll(path.Dir(c.PrivateKeyPath("ecdsa")), 0o755); err != nil {
2021-07-17 23:22:13 +00:00
return errors.Wrap(err, "sftp/server: could not create .sftp directory")
}
2022-01-18 20:12:09 +00:00
o, err := os.OpenFile(c.PrivateKeyPath("ecdsa"), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600)
2021-07-17 23:22:13 +00:00
if err != nil {
return err
}
defer o.Close()
privBytes, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
return err
}
if err := pem.Encode(o, &pem.Block{
Type: "PRIVATE KEY",
Bytes: privBytes,
}); err != nil {
return err
}
return nil
}
2022-01-18 20:12:09 +00:00
// generateEd25519PrivateKey generates an ed25519 private key that will be used by the SFTP server.
2021-07-17 23:22:13 +00:00
func (c *SFTPServer) generateEd25519PrivateKey() error {
_, key, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return err
}
2022-01-18 20:12:09 +00:00
if err := os.MkdirAll(path.Dir(c.PrivateKeyPath("ed25519")), 0o755); err != nil {
2021-07-17 23:22:13 +00:00
return errors.Wrap(err, "sftp/server: could not create .sftp directory")
}
2022-01-18 20:12:09 +00:00
o, err := os.OpenFile(c.PrivateKeyPath("ed25519"), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600)
2021-07-17 23:22:13 +00:00
if err != nil {
return err
}
defer o.Close()
privBytes, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
return err
}
if err := pem.Encode(o, &pem.Block{
Type: "PRIVATE KEY",
Bytes: privBytes,
}); err != nil {
return err
}
return nil
}
2022-01-18 20:12:09 +00:00
// PrivateKeyPath returns the path the host private key for this server instance.
func (c *SFTPServer) PrivateKeyPath(name string) string {
return path.Join(c.BasePath, ".sftp", "id_"+name)
}
// A function capable of validating user credentials with the Panel API.
func (c *SFTPServer) passwordCallback(conn ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
2021-02-02 04:59:17 +00:00
request := remote.SftpAuthRequest{
User: conn.User(),
Pass: string(pass),
IP: conn.RemoteAddr().String(),
SessionID: conn.SessionID(),
ClientVersion: conn.ClientVersion(),
2021-07-17 23:22:13 +00:00
Type: "password",
}
logger := log.WithFields(log.Fields{"subsystem": "sftp", "username": conn.User(), "ip": conn.RemoteAddr().String()})
logger.Debug("validating credentials for SFTP connection")
2021-02-02 04:59:17 +00:00
if !validUsernameRegexp.MatchString(request.User) {
logger.Warn("failed to validate user credentials (invalid format)")
return nil, &remote.SftpInvalidCredentialsError{}
}
2021-07-17 23:22:13 +00:00
if len(pass) < 1 {
logger.Warn("failed to validate user credentials (invalid format)")
return nil, &remote.SftpInvalidCredentialsError{}
}
2021-02-02 04:59:17 +00:00
resp, err := c.manager.Client().ValidateSftpCredentials(context.Background(), request)
if err != nil {
2021-02-02 05:32:34 +00:00
if _, ok := err.(*remote.SftpInvalidCredentialsError); ok {
logger.Warn("failed to validate user credentials (invalid username or password)")
} else {
2021-01-10 23:12:13 +00:00
logger.WithField("error", err).Error("encountered an error while trying to validate user credentials")
}
return nil, err
}
logger.WithField("server", resp.Server).Debug("credentials validated and matched to server instance")
sshPerm := &ssh.Permissions{
Extensions: map[string]string{
"uuid": resp.Server,
"user": conn.User(),
"permissions": strings.Join(resp.Permissions, ","),
},
}
return sshPerm, nil
}
2021-07-17 23:22:13 +00:00
func (c *SFTPServer) publicKeyCallback(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
request := remote.SftpAuthRequest{
User: conn.User(),
Pass: "KEKW",
IP: conn.RemoteAddr().String(),
SessionID: conn.SessionID(),
ClientVersion: conn.ClientVersion(),
Type: "publicKey",
}
logger := log.WithFields(log.Fields{"subsystem": "sftp", "username": conn.User(), "ip": conn.RemoteAddr().String()})
logger.Debug("validating public key for SFTP connection")
if !validUsernameRegexp.MatchString(request.User) {
logger.Warn("failed to validate user credentials (invalid format)")
return nil, &remote.SftpInvalidCredentialsError{}
}
resp, err := c.manager.Client().ValidateSftpCredentials(context.Background(), request)
if err != nil {
if _, ok := err.(*remote.SftpInvalidCredentialsError); ok {
logger.Warn("failed to validate user credentials (invalid username or password)")
} else {
logger.WithField("error", err).Error("encountered an error while trying to validate user credentials")
}
return nil, err
}
if len(resp.SSHKeys) < 1 {
return nil, &remote.SftpInvalidCredentialsError{}
}
for _, k := range resp.SSHKeys {
storedPublicKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(k))
if err != nil {
return nil, err
}
if !bytes.Equal(key.Marshal(), storedPublicKey.Marshal()) {
continue
}
return &ssh.Permissions{
Extensions: map[string]string{
"uuid": resp.Server,
"user": conn.User(),
"permissions": strings.Join(resp.Permissions, ","),
},
}, nil
}
return nil, &remote.SftpInvalidCredentialsError{}
}