2020-08-11 21:56:10 +00:00
|
|
|
package webdavd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"crypto/tls"
|
2021-01-03 16:03:04 +00:00
|
|
|
"crypto/x509"
|
2020-08-11 21:56:10 +00:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
2021-01-03 09:38:28 +00:00
|
|
|
"log"
|
2020-08-11 21:56:10 +00:00
|
|
|
"net/http"
|
|
|
|
"path"
|
|
|
|
"path/filepath"
|
2020-10-31 10:02:04 +00:00
|
|
|
"runtime/debug"
|
2020-08-11 21:56:10 +00:00
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
2021-02-04 08:06:41 +00:00
|
|
|
"github.com/go-chi/chi/middleware"
|
2020-08-15 13:55:20 +00:00
|
|
|
"github.com/rs/cors"
|
2020-08-11 21:56:10 +00:00
|
|
|
"github.com/rs/xid"
|
|
|
|
"golang.org/x/net/webdav"
|
|
|
|
|
|
|
|
"github.com/drakkan/sftpgo/common"
|
|
|
|
"github.com/drakkan/sftpgo/dataprovider"
|
|
|
|
"github.com/drakkan/sftpgo/logger"
|
|
|
|
"github.com/drakkan/sftpgo/metrics"
|
|
|
|
"github.com/drakkan/sftpgo/utils"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
err401 = errors.New("Unauthorized")
|
|
|
|
xForwardedFor = http.CanonicalHeaderKey("X-Forwarded-For")
|
|
|
|
xRealIP = http.CanonicalHeaderKey("X-Real-IP")
|
|
|
|
)
|
|
|
|
|
|
|
|
type webDavServer struct {
|
|
|
|
config *Configuration
|
2021-01-03 08:51:54 +00:00
|
|
|
binding Binding
|
2020-08-11 21:56:10 +00:00
|
|
|
}
|
|
|
|
|
2021-01-03 08:51:54 +00:00
|
|
|
func (s *webDavServer) listenAndServe() error {
|
2021-02-04 08:06:41 +00:00
|
|
|
compressor := middleware.NewCompressor(5, "text/*")
|
|
|
|
handler := compressor.Handler(s)
|
2020-08-11 21:56:10 +00:00
|
|
|
httpServer := &http.Server{
|
2021-01-03 08:51:54 +00:00
|
|
|
Addr: s.binding.GetAddress(),
|
2020-08-11 21:56:10 +00:00
|
|
|
ReadHeaderTimeout: 30 * time.Second,
|
|
|
|
IdleTimeout: 120 * time.Second,
|
|
|
|
MaxHeaderBytes: 1 << 16, // 64KB
|
2021-01-03 09:38:28 +00:00
|
|
|
ErrorLog: log.New(&logger.StdLoggerWrapper{Sender: logSender}, "", 0),
|
2020-08-11 21:56:10 +00:00
|
|
|
}
|
2020-08-15 13:55:20 +00:00
|
|
|
if s.config.Cors.Enabled {
|
|
|
|
c := cors.New(cors.Options{
|
|
|
|
AllowedOrigins: s.config.Cors.AllowedOrigins,
|
|
|
|
AllowedMethods: s.config.Cors.AllowedMethods,
|
|
|
|
AllowedHeaders: s.config.Cors.AllowedHeaders,
|
|
|
|
ExposedHeaders: s.config.Cors.ExposedHeaders,
|
|
|
|
MaxAge: s.config.Cors.MaxAge,
|
|
|
|
AllowCredentials: s.config.Cors.AllowCredentials,
|
|
|
|
OptionsPassthrough: true,
|
|
|
|
})
|
2021-02-04 08:06:41 +00:00
|
|
|
handler = c.Handler(handler)
|
2020-08-15 13:55:20 +00:00
|
|
|
}
|
2021-02-04 08:06:41 +00:00
|
|
|
httpServer.Handler = handler
|
2021-01-03 08:51:54 +00:00
|
|
|
if certMgr != nil && s.binding.EnableHTTPS {
|
|
|
|
serviceStatus.Bindings = append(serviceStatus.Bindings, s.binding)
|
2020-08-11 21:56:10 +00:00
|
|
|
httpServer.TLSConfig = &tls.Config{
|
2021-01-03 08:51:54 +00:00
|
|
|
GetCertificate: certMgr.GetCertificateFunc(),
|
2020-08-15 11:02:25 +00:00
|
|
|
MinVersion: tls.VersionTLS12,
|
2020-08-11 21:56:10 +00:00
|
|
|
}
|
2021-01-03 08:51:54 +00:00
|
|
|
if s.binding.ClientAuthType == 1 {
|
|
|
|
httpServer.TLSConfig.ClientCAs = certMgr.GetRootCAs()
|
2020-12-28 18:48:23 +00:00
|
|
|
httpServer.TLSConfig.ClientAuth = tls.RequireAndVerifyClientCert
|
2021-01-03 16:03:04 +00:00
|
|
|
httpServer.TLSConfig.VerifyConnection = s.verifyTLSConnection
|
2020-12-28 18:48:23 +00:00
|
|
|
}
|
2021-01-03 08:51:54 +00:00
|
|
|
logger.Info(logSender, "", "starting HTTPS serving, binding: %v", s.binding.GetAddress())
|
2020-08-11 21:56:10 +00:00
|
|
|
return httpServer.ListenAndServeTLS("", "")
|
|
|
|
}
|
2021-01-03 08:51:54 +00:00
|
|
|
s.binding.EnableHTTPS = false
|
|
|
|
serviceStatus.Bindings = append(serviceStatus.Bindings, s.binding)
|
|
|
|
logger.Info(logSender, "", "starting HTTP serving, binding: %v", s.binding.GetAddress())
|
2020-08-11 21:56:10 +00:00
|
|
|
return httpServer.ListenAndServe()
|
|
|
|
}
|
|
|
|
|
2021-01-03 16:03:04 +00:00
|
|
|
func (s *webDavServer) verifyTLSConnection(state tls.ConnectionState) error {
|
|
|
|
if certMgr != nil {
|
|
|
|
var clientCrt *x509.Certificate
|
|
|
|
var clientCrtName string
|
|
|
|
if len(state.PeerCertificates) > 0 {
|
|
|
|
clientCrt = state.PeerCertificates[0]
|
|
|
|
clientCrtName = clientCrt.Subject.String()
|
|
|
|
}
|
|
|
|
if len(state.VerifiedChains) == 0 {
|
|
|
|
logger.Warn(logSender, "", "TLS connection cannot be verified: unable to get verification chain")
|
|
|
|
return errors.New("TLS connection cannot be verified: unable to get verification chain")
|
|
|
|
}
|
|
|
|
for _, verifiedChain := range state.VerifiedChains {
|
|
|
|
var caCrt *x509.Certificate
|
|
|
|
if len(verifiedChain) > 0 {
|
|
|
|
caCrt = verifiedChain[len(verifiedChain)-1]
|
|
|
|
}
|
|
|
|
if certMgr.IsRevoked(clientCrt, caCrt) {
|
|
|
|
logger.Debug(logSender, "", "tls handshake error, client certificate %#v has been revoked", clientCrtName)
|
|
|
|
return common.ErrCrtRevoked
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-02-04 06:12:04 +00:00
|
|
|
// returns true if we have to handle a HEAD response, for a directory, ourself
|
|
|
|
func (s *webDavServer) checkRequestMethod(ctx context.Context, r *http.Request, connection *Connection) bool {
|
2020-12-06 07:19:41 +00:00
|
|
|
// see RFC4918, section 9.4
|
2021-02-03 21:36:13 +00:00
|
|
|
if r.Method == http.MethodGet || r.Method == http.MethodHead {
|
2021-02-04 06:12:04 +00:00
|
|
|
p := path.Clean(r.URL.Path)
|
2020-12-06 07:19:41 +00:00
|
|
|
info, err := connection.Stat(ctx, p)
|
|
|
|
if err == nil && info.IsDir() {
|
2021-02-03 21:36:13 +00:00
|
|
|
if r.Method == http.MethodHead {
|
|
|
|
return true
|
|
|
|
}
|
2020-12-06 07:19:41 +00:00
|
|
|
r.Method = "PROPFIND"
|
|
|
|
if r.Header.Get("Depth") == "" {
|
|
|
|
r.Header.Add("Depth", "1")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-02-03 21:36:13 +00:00
|
|
|
return false
|
2020-12-06 07:19:41 +00:00
|
|
|
}
|
|
|
|
|
2020-08-11 21:56:10 +00:00
|
|
|
// ServeHTTP implements the http.Handler interface
|
|
|
|
func (s *webDavServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
2020-10-31 10:02:04 +00:00
|
|
|
defer func() {
|
|
|
|
if r := recover(); r != nil {
|
|
|
|
logger.Error(logSender, "", "panic in ServeHTTP: %#v stack strace: %v", r, string(debug.Stack()))
|
|
|
|
http.Error(w, common.ErrGenericFailure.Error(), http.StatusInternalServerError)
|
|
|
|
}
|
|
|
|
}()
|
2020-12-15 18:29:30 +00:00
|
|
|
if !common.Connections.IsNewConnectionAllowed() {
|
|
|
|
logger.Log(logger.LevelDebug, common.ProtocolFTP, "", "connection refused, configured limit reached")
|
|
|
|
http.Error(w, common.ErrConnectionDenied.Error(), http.StatusServiceUnavailable)
|
|
|
|
return
|
|
|
|
}
|
2020-08-11 21:56:10 +00:00
|
|
|
checkRemoteAddress(r)
|
2021-01-02 13:05:09 +00:00
|
|
|
ipAddr := utils.GetIPFromRemoteAddress(r.RemoteAddr)
|
|
|
|
if common.IsBanned(ipAddr) {
|
2020-08-11 21:56:10 +00:00
|
|
|
http.Error(w, common.ErrConnectionDenied.Error(), http.StatusForbidden)
|
|
|
|
return
|
|
|
|
}
|
2021-01-02 13:05:09 +00:00
|
|
|
if err := common.Config.ExecutePostConnectHook(ipAddr, common.ProtocolWebDAV); err != nil {
|
|
|
|
http.Error(w, common.ErrConnectionDenied.Error(), http.StatusForbidden)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
user, _, lockSystem, err := s.authenticate(r, ipAddr)
|
2020-08-11 21:56:10 +00:00
|
|
|
if err != nil {
|
|
|
|
w.Header().Set("WWW-Authenticate", "Basic realm=\"SFTPGo WebDAV\"")
|
|
|
|
http.Error(w, err401.Error(), http.StatusUnauthorized)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-01-26 17:05:44 +00:00
|
|
|
connectionID, err := s.validateUser(&user, r)
|
2020-08-11 21:56:10 +00:00
|
|
|
if err != nil {
|
2021-01-26 17:05:44 +00:00
|
|
|
updateLoginMetrics(&user, ipAddr, err)
|
2020-08-11 21:56:10 +00:00
|
|
|
http.Error(w, err.Error(), http.StatusForbidden)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
fs, err := user.GetFilesystem(connectionID)
|
|
|
|
if err != nil {
|
2021-01-26 17:05:44 +00:00
|
|
|
updateLoginMetrics(&user, ipAddr, err)
|
2020-08-11 21:56:10 +00:00
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-01-26 17:05:44 +00:00
|
|
|
updateLoginMetrics(&user, ipAddr, err)
|
2020-08-11 21:56:10 +00:00
|
|
|
|
|
|
|
ctx := context.WithValue(r.Context(), requestIDKey, connectionID)
|
|
|
|
ctx = context.WithValue(ctx, requestStartKey, time.Now())
|
|
|
|
|
|
|
|
connection := &Connection{
|
|
|
|
BaseConnection: common.NewBaseConnection(connectionID, common.ProtocolWebDAV, user, fs),
|
|
|
|
request: r,
|
|
|
|
}
|
|
|
|
common.Connections.Add(connection)
|
|
|
|
defer common.Connections.Remove(connection.GetID())
|
|
|
|
|
2020-11-30 20:46:34 +00:00
|
|
|
dataprovider.UpdateLastLogin(user) //nolint:errcheck
|
2020-08-11 21:56:10 +00:00
|
|
|
|
2021-02-04 06:12:04 +00:00
|
|
|
if s.checkRequestMethod(ctx, r, connection) {
|
2021-02-03 21:36:13 +00:00
|
|
|
w.Header().Set("Content-Type", "text/xml; charset=utf-8")
|
|
|
|
w.WriteHeader(http.StatusMultiStatus)
|
|
|
|
w.Write([]byte("")) //nolint:errcheck
|
|
|
|
return
|
|
|
|
}
|
2020-08-11 21:56:10 +00:00
|
|
|
|
|
|
|
handler := webdav.Handler{
|
|
|
|
FileSystem: connection,
|
2020-11-04 18:11:40 +00:00
|
|
|
LockSystem: lockSystem,
|
2020-08-11 21:56:10 +00:00
|
|
|
Logger: writeLog,
|
|
|
|
}
|
|
|
|
handler.ServeHTTP(w, r.WithContext(ctx))
|
|
|
|
}
|
|
|
|
|
2021-01-02 13:05:09 +00:00
|
|
|
func (s *webDavServer) authenticate(r *http.Request, ip string) (dataprovider.User, bool, webdav.LockSystem, error) {
|
2020-08-11 21:56:10 +00:00
|
|
|
var user dataprovider.User
|
|
|
|
var err error
|
|
|
|
username, password, ok := r.BasicAuth()
|
|
|
|
if !ok {
|
2020-11-04 18:11:40 +00:00
|
|
|
return user, false, nil, err401
|
2020-08-31 17:25:17 +00:00
|
|
|
}
|
2020-11-04 21:29:25 +00:00
|
|
|
result, ok := dataprovider.GetCachedWebDAVUser(username)
|
|
|
|
if ok {
|
|
|
|
cachedUser := result.(*dataprovider.CachedUser)
|
|
|
|
if cachedUser.IsExpired() {
|
|
|
|
dataprovider.RemoveCachedWebDAVUser(username)
|
|
|
|
} else {
|
2021-01-05 08:50:22 +00:00
|
|
|
if password != "" && cachedUser.Password == password {
|
2020-11-04 21:29:25 +00:00
|
|
|
return cachedUser.User, true, cachedUser.LockSystem, nil
|
2020-08-31 17:25:17 +00:00
|
|
|
}
|
2021-01-26 17:05:44 +00:00
|
|
|
updateLoginMetrics(&cachedUser.User, ip, dataprovider.ErrInvalidCredentials)
|
2020-11-04 21:29:25 +00:00
|
|
|
return user, false, nil, dataprovider.ErrInvalidCredentials
|
2020-08-31 17:25:17 +00:00
|
|
|
}
|
2020-08-11 21:56:10 +00:00
|
|
|
}
|
2021-01-02 13:05:09 +00:00
|
|
|
user, err = dataprovider.CheckUserAndPass(username, password, ip, common.ProtocolWebDAV)
|
2020-08-11 21:56:10 +00:00
|
|
|
if err != nil {
|
2021-01-26 17:05:44 +00:00
|
|
|
user.Username = username
|
|
|
|
updateLoginMetrics(&user, ip, err)
|
2020-11-04 18:11:40 +00:00
|
|
|
return user, false, nil, err
|
|
|
|
}
|
|
|
|
lockSystem := webdav.NewMemLS()
|
2020-11-04 21:29:25 +00:00
|
|
|
if password != "" {
|
2020-11-04 18:11:40 +00:00
|
|
|
cachedUser := &dataprovider.CachedUser{
|
|
|
|
User: user,
|
|
|
|
Password: password,
|
|
|
|
LockSystem: lockSystem,
|
2020-08-31 17:25:17 +00:00
|
|
|
}
|
2020-11-04 18:11:40 +00:00
|
|
|
if s.config.Cache.Users.ExpirationTime > 0 {
|
|
|
|
cachedUser.Expiration = time.Now().Add(time.Duration(s.config.Cache.Users.ExpirationTime) * time.Minute)
|
2020-08-31 17:25:17 +00:00
|
|
|
}
|
2020-11-04 18:11:40 +00:00
|
|
|
dataprovider.CacheWebDAVUser(cachedUser, s.config.Cache.Users.MaxSize)
|
2020-12-12 09:31:09 +00:00
|
|
|
if user.FsConfig.Provider != dataprovider.SFTPFilesystemProvider {
|
|
|
|
// for sftp fs check root path does nothing so don't open a useless SFTP connection
|
|
|
|
tempFs, err := user.GetFilesystem("temp")
|
|
|
|
if err == nil {
|
|
|
|
tempFs.CheckRootPath(user.Username, user.UID, user.GID)
|
|
|
|
tempFs.Close()
|
|
|
|
}
|
2020-12-06 07:19:41 +00:00
|
|
|
}
|
2020-08-11 21:56:10 +00:00
|
|
|
}
|
2020-12-06 07:19:41 +00:00
|
|
|
return user, false, lockSystem, nil
|
2020-08-11 21:56:10 +00:00
|
|
|
}
|
|
|
|
|
2021-01-26 17:05:44 +00:00
|
|
|
func (s *webDavServer) validateUser(user *dataprovider.User, r *http.Request) (string, error) {
|
2020-08-11 21:56:10 +00:00
|
|
|
connID := xid.New().String()
|
|
|
|
connectionID := fmt.Sprintf("%v_%v", common.ProtocolWebDAV, connID)
|
|
|
|
|
|
|
|
if !filepath.IsAbs(user.HomeDir) {
|
|
|
|
logger.Warn(logSender, connectionID, "user %#v has an invalid home dir: %#v. Home dir must be an absolute path, login not allowed",
|
|
|
|
user.Username, user.HomeDir)
|
|
|
|
return connID, fmt.Errorf("cannot login user with invalid home dir: %#v", user.HomeDir)
|
|
|
|
}
|
2020-08-17 10:49:20 +00:00
|
|
|
if utils.IsStringInSlice(common.ProtocolWebDAV, user.Filters.DeniedProtocols) {
|
|
|
|
logger.Debug(logSender, connectionID, "cannot login user %#v, protocol DAV is not allowed", user.Username)
|
|
|
|
return connID, fmt.Errorf("Protocol DAV is not allowed for user %#v", user.Username)
|
|
|
|
}
|
2020-08-19 17:36:12 +00:00
|
|
|
if !user.IsLoginMethodAllowed(dataprovider.LoginMethodPassword, nil) {
|
|
|
|
logger.Debug(logSender, connectionID, "cannot login user %#v, password login method is not allowed", user.Username)
|
|
|
|
return connID, fmt.Errorf("Password login method is not allowed for user %#v", user.Username)
|
|
|
|
}
|
2020-08-11 21:56:10 +00:00
|
|
|
if user.MaxSessions > 0 {
|
|
|
|
activeSessions := common.Connections.GetActiveSessions(user.Username)
|
|
|
|
if activeSessions >= user.MaxSessions {
|
|
|
|
logger.Debug(logSender, connID, "authentication refused for user: %#v, too many open sessions: %v/%v", user.Username,
|
|
|
|
activeSessions, user.MaxSessions)
|
|
|
|
return connID, fmt.Errorf("too many open sessions: %v", activeSessions)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if dataprovider.GetQuotaTracking() > 0 && user.HasOverlappedMappedPaths() {
|
|
|
|
logger.Debug(logSender, connectionID, "cannot login user %#v, overlapping mapped folders are allowed only with quota tracking disabled",
|
|
|
|
user.Username)
|
|
|
|
return connID, errors.New("overlapping mapped folders are allowed only with quota tracking disabled")
|
|
|
|
}
|
|
|
|
if !user.IsLoginFromAddrAllowed(r.RemoteAddr) {
|
|
|
|
logger.Debug(logSender, connectionID, "cannot login user %#v, remote address is not allowed: %v", user.Username, r.RemoteAddr)
|
|
|
|
return connID, fmt.Errorf("Login for user %#v is not allowed from this address: %v", user.Username, r.RemoteAddr)
|
|
|
|
}
|
|
|
|
return connID, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func writeLog(r *http.Request, err error) {
|
|
|
|
scheme := "http"
|
|
|
|
if r.TLS != nil {
|
|
|
|
scheme = "https"
|
|
|
|
}
|
|
|
|
fields := map[string]interface{}{
|
|
|
|
"remote_addr": r.RemoteAddr,
|
|
|
|
"proto": r.Proto,
|
|
|
|
"method": r.Method,
|
|
|
|
"user_agent": r.UserAgent(),
|
|
|
|
"uri": fmt.Sprintf("%s://%s%s", scheme, r.Host, r.RequestURI)}
|
|
|
|
if reqID, ok := r.Context().Value(requestIDKey).(string); ok {
|
|
|
|
fields["request_id"] = reqID
|
|
|
|
}
|
|
|
|
if reqStart, ok := r.Context().Value(requestStartKey).(time.Time); ok {
|
|
|
|
fields["elapsed_ms"] = time.Since(reqStart).Nanoseconds() / 1000000
|
|
|
|
}
|
|
|
|
logger.GetLogger().Info().
|
|
|
|
Timestamp().
|
|
|
|
Str("sender", logSender).
|
|
|
|
Fields(fields).
|
|
|
|
Err(err).
|
2020-10-29 18:23:33 +00:00
|
|
|
Send()
|
2020-08-11 21:56:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func checkRemoteAddress(r *http.Request) {
|
|
|
|
if common.Config.ProxyProtocol != 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
var ip string
|
|
|
|
|
|
|
|
if xrip := r.Header.Get(xRealIP); xrip != "" {
|
|
|
|
ip = xrip
|
|
|
|
} else if xff := r.Header.Get(xForwardedFor); xff != "" {
|
|
|
|
i := strings.Index(xff, ", ")
|
|
|
|
if i == -1 {
|
|
|
|
i = len(xff)
|
|
|
|
}
|
|
|
|
ip = strings.TrimSpace(xff[:i])
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(ip) > 0 {
|
|
|
|
r.RemoteAddr = ip
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-26 17:05:44 +00:00
|
|
|
func updateLoginMetrics(user *dataprovider.User, ip string, err error) {
|
2020-08-12 14:15:12 +00:00
|
|
|
metrics.AddLoginAttempt(dataprovider.LoginMethodPassword)
|
2020-08-11 21:56:10 +00:00
|
|
|
if err != nil {
|
2021-01-26 17:05:44 +00:00
|
|
|
logger.ConnectionFailedLog(user.Username, ip, dataprovider.LoginMethodPassword, common.ProtocolWebDAV, err.Error())
|
2021-01-02 13:05:09 +00:00
|
|
|
event := common.HostEventLoginFailed
|
|
|
|
if _, ok := err.(*dataprovider.RecordNotFoundError); ok {
|
|
|
|
event = common.HostEventUserNotFound
|
|
|
|
}
|
|
|
|
common.AddDefenderEvent(ip, event)
|
2020-08-11 21:56:10 +00:00
|
|
|
}
|
2020-08-12 14:15:12 +00:00
|
|
|
metrics.AddLoginResult(dataprovider.LoginMethodPassword, err)
|
2021-01-26 17:05:44 +00:00
|
|
|
dataprovider.ExecutePostLoginHook(user, dataprovider.LoginMethodPassword, ip, common.ProtocolWebDAV, err)
|
2020-08-11 21:56:10 +00:00
|
|
|
}
|