2024-01-01 10:31:45 +00:00
|
|
|
// Copyright (C) 2019 Nicola Murino
|
2022-07-17 18:16:00 +00:00
|
|
|
//
|
|
|
|
// This program is free software: you can redistribute it and/or modify
|
|
|
|
// it under the terms of the GNU Affero General Public License as published
|
|
|
|
// by the Free Software Foundation, version 3.
|
|
|
|
//
|
|
|
|
// This program is distributed in the hope that it will be useful,
|
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
// GNU Affero General Public License for more details.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the GNU Affero General Public License
|
2023-01-03 09:18:30 +00:00
|
|
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
2022-07-17 18:16:00 +00:00
|
|
|
|
2019-07-30 18:51:29 +00:00
|
|
|
// Package dataprovider provides data access.
|
2023-02-09 08:33:33 +00:00
|
|
|
// It abstracts different data providers using a common API.
|
2019-07-20 10:26:52 +00:00
|
|
|
package dataprovider
|
|
|
|
|
|
|
|
import (
|
2020-01-21 09:54:05 +00:00
|
|
|
"bufio"
|
2019-11-14 10:06:03 +00:00
|
|
|
"bytes"
|
2020-01-06 20:42:41 +00:00
|
|
|
"context"
|
2022-04-02 20:20:21 +00:00
|
|
|
"crypto/md5"
|
2024-02-25 10:12:57 +00:00
|
|
|
"crypto/rsa"
|
2019-08-17 13:20:49 +00:00
|
|
|
"crypto/sha1"
|
|
|
|
"crypto/sha256"
|
|
|
|
"crypto/sha512"
|
|
|
|
"crypto/subtle"
|
2021-02-28 11:10:40 +00:00
|
|
|
"crypto/x509"
|
2019-08-17 13:20:49 +00:00
|
|
|
"encoding/base64"
|
2021-12-25 11:08:07 +00:00
|
|
|
"encoding/hex"
|
2019-11-14 10:06:03 +00:00
|
|
|
"encoding/json"
|
2024-01-14 20:36:23 +00:00
|
|
|
"encoding/pem"
|
2019-08-12 16:31:31 +00:00
|
|
|
"errors"
|
2019-07-20 10:26:52 +00:00
|
|
|
"fmt"
|
2019-08-17 13:20:49 +00:00
|
|
|
"hash"
|
2020-02-16 10:43:52 +00:00
|
|
|
"io"
|
2019-12-30 17:37:50 +00:00
|
|
|
"net"
|
2019-11-14 10:06:03 +00:00
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"os"
|
|
|
|
"os/exec"
|
2019-12-25 17:20:19 +00:00
|
|
|
"path"
|
2019-07-20 10:26:52 +00:00
|
|
|
"path/filepath"
|
2021-01-17 21:29:08 +00:00
|
|
|
"regexp"
|
2020-01-21 09:54:05 +00:00
|
|
|
"runtime"
|
2024-07-24 16:27:13 +00:00
|
|
|
"slices"
|
2019-08-17 13:20:49 +00:00
|
|
|
"strconv"
|
2019-07-20 10:26:52 +00:00
|
|
|
"strings"
|
2020-01-21 09:54:05 +00:00
|
|
|
"sync"
|
2021-05-14 17:21:15 +00:00
|
|
|
"sync/atomic"
|
2019-09-13 16:45:36 +00:00
|
|
|
"time"
|
2019-07-20 10:26:52 +00:00
|
|
|
|
2020-09-04 19:08:09 +00:00
|
|
|
"github.com/GehirnInc/crypt"
|
|
|
|
"github.com/GehirnInc/crypt/apr1_crypt"
|
|
|
|
"github.com/GehirnInc/crypt/md5_crypt"
|
2022-09-28 17:15:02 +00:00
|
|
|
"github.com/GehirnInc/crypt/sha256_crypt"
|
2020-09-04 19:08:09 +00:00
|
|
|
"github.com/GehirnInc/crypt/sha512_crypt"
|
2019-07-20 10:26:52 +00:00
|
|
|
"github.com/alexedwards/argon2id"
|
2020-04-01 21:25:23 +00:00
|
|
|
"github.com/go-chi/render"
|
|
|
|
"github.com/rs/xid"
|
2022-01-06 10:54:43 +00:00
|
|
|
"github.com/sftpgo/sdk"
|
2021-08-06 16:56:07 +00:00
|
|
|
passwordvalidator "github.com/wagslane/go-password-validator"
|
2019-08-12 16:31:31 +00:00
|
|
|
"golang.org/x/crypto/bcrypt"
|
2019-08-17 13:20:49 +00:00
|
|
|
"golang.org/x/crypto/pbkdf2"
|
2019-07-20 10:26:52 +00:00
|
|
|
"golang.org/x/crypto/ssh"
|
|
|
|
|
2022-07-24 14:18:54 +00:00
|
|
|
"github.com/drakkan/sftpgo/v2/internal/command"
|
|
|
|
"github.com/drakkan/sftpgo/v2/internal/httpclient"
|
|
|
|
"github.com/drakkan/sftpgo/v2/internal/kms"
|
|
|
|
"github.com/drakkan/sftpgo/v2/internal/logger"
|
|
|
|
"github.com/drakkan/sftpgo/v2/internal/mfa"
|
|
|
|
"github.com/drakkan/sftpgo/v2/internal/plugin"
|
|
|
|
"github.com/drakkan/sftpgo/v2/internal/util"
|
|
|
|
"github.com/drakkan/sftpgo/v2/internal/vfs"
|
2019-07-20 10:26:52 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2021-03-23 18:14:15 +00:00
|
|
|
// SQLiteDataProviderName defines the name for SQLite database provider
|
2019-07-20 10:26:52 +00:00
|
|
|
SQLiteDataProviderName = "sqlite"
|
2021-03-23 18:14:15 +00:00
|
|
|
// PGSQLDataProviderName defines the name for PostgreSQL database provider
|
2019-09-06 09:23:06 +00:00
|
|
|
PGSQLDataProviderName = "postgresql"
|
2021-03-23 18:14:15 +00:00
|
|
|
// MySQLDataProviderName defines the name for MySQL database provider
|
2019-07-20 10:26:52 +00:00
|
|
|
MySQLDataProviderName = "mysql"
|
2021-03-23 18:14:15 +00:00
|
|
|
// BoltDataProviderName defines the name for bbolt key/value store provider
|
2019-08-12 16:31:31 +00:00
|
|
|
BoltDataProviderName = "bolt"
|
2021-03-23 18:14:15 +00:00
|
|
|
// MemoryDataProviderName defines the name for memory provider
|
2019-10-25 16:37:12 +00:00
|
|
|
MemoryDataProviderName = "memory"
|
2021-03-23 18:14:15 +00:00
|
|
|
// CockroachDataProviderName defines the for CockroachDB provider
|
2021-03-27 18:41:00 +00:00
|
|
|
CockroachDataProviderName = "cockroachdb"
|
2020-11-22 20:53:04 +00:00
|
|
|
// DumpVersion defines the version for the dump.
|
|
|
|
// For restore/load we support the current version and the previous one
|
2023-02-09 08:33:33 +00:00
|
|
|
DumpVersion = 16
|
2019-07-20 10:26:52 +00:00
|
|
|
|
2020-04-11 10:25:21 +00:00
|
|
|
argonPwdPrefix = "$argon2id$"
|
|
|
|
bcryptPwdPrefix = "$2a$"
|
|
|
|
pbkdf2SHA1Prefix = "$pbkdf2-sha1$"
|
|
|
|
pbkdf2SHA256Prefix = "$pbkdf2-sha256$"
|
|
|
|
pbkdf2SHA512Prefix = "$pbkdf2-sha512$"
|
|
|
|
pbkdf2SHA256B64SaltPrefix = "$pbkdf2-b64salt-sha256$"
|
|
|
|
md5cryptPwdPrefix = "$1$"
|
|
|
|
md5cryptApr1PwdPrefix = "$apr1$"
|
2022-09-28 17:15:02 +00:00
|
|
|
sha256cryptPwdPrefix = "$5$"
|
2020-04-11 10:25:21 +00:00
|
|
|
sha512cryptPwdPrefix = "$6$"
|
2023-03-26 08:33:30 +00:00
|
|
|
yescryptPwdPrefix = "$y$"
|
2023-06-03 14:58:45 +00:00
|
|
|
md5DigestPwdPrefix = "{MD5}"
|
|
|
|
sha256DigestPwdPrefix = "{SHA256}"
|
|
|
|
sha512DigestPwdPrefix = "{SHA512}"
|
2020-04-11 10:25:21 +00:00
|
|
|
trackQuotaDisabledError = "please enable track_quota in your configuration to use this method"
|
|
|
|
operationAdd = "add"
|
|
|
|
operationUpdate = "update"
|
|
|
|
operationDelete = "delete"
|
2021-04-12 18:00:49 +00:00
|
|
|
sqlPrefixValidChars = "abcdefghijklmnopqrstuvwxyz_0123456789"
|
2021-05-12 20:44:17 +00:00
|
|
|
maxHookResponseSize = 1048576 // 1MB
|
2022-06-09 05:37:50 +00:00
|
|
|
iso8601UTCFormat = "2006-01-02T15:04:05Z"
|
2020-06-07 21:30:18 +00:00
|
|
|
)
|
|
|
|
|
2021-04-20 11:55:09 +00:00
|
|
|
// Supported algorithms for hashing passwords.
|
|
|
|
// These algorithms can be used when SFTPGo hashes a plain text password
|
|
|
|
const (
|
|
|
|
HashingAlgoBcrypt = "bcrypt"
|
|
|
|
HashingAlgoArgon2ID = "argon2id"
|
|
|
|
)
|
|
|
|
|
2020-06-07 21:30:18 +00:00
|
|
|
// ordering constants
|
|
|
|
const (
|
|
|
|
OrderASC = "ASC"
|
|
|
|
OrderDESC = "DESC"
|
2019-07-20 10:26:52 +00:00
|
|
|
)
|
|
|
|
|
2021-09-04 10:11:04 +00:00
|
|
|
const (
|
|
|
|
protocolSSH = "SSH"
|
|
|
|
protocolFTP = "FTP"
|
|
|
|
protocolWebDAV = "DAV"
|
|
|
|
protocolHTTP = "HTTP"
|
|
|
|
)
|
|
|
|
|
2023-04-18 16:11:23 +00:00
|
|
|
// Dump scopes
|
|
|
|
const (
|
|
|
|
DumpScopeUsers = "users"
|
|
|
|
DumpScopeFolders = "folders"
|
|
|
|
DumpScopeGroups = "groups"
|
|
|
|
DumpScopeAdmins = "admins"
|
|
|
|
DumpScopeAPIKeys = "api_keys"
|
|
|
|
DumpScopeShares = "shares"
|
|
|
|
DumpScopeActions = "actions"
|
|
|
|
DumpScopeRules = "rules"
|
|
|
|
DumpScopeRoles = "roles"
|
|
|
|
DumpScopeIPLists = "ip_lists"
|
|
|
|
DumpScopeConfigs = "configs"
|
|
|
|
)
|
|
|
|
|
2024-01-17 16:36:35 +00:00
|
|
|
const (
|
|
|
|
fieldUsername = 1
|
|
|
|
fieldName = 2
|
2024-01-24 18:23:15 +00:00
|
|
|
fieldIPNet = 3
|
2024-01-17 16:36:35 +00:00
|
|
|
)
|
|
|
|
|
2019-07-20 10:26:52 +00:00
|
|
|
var (
|
2020-04-09 21:32:42 +00:00
|
|
|
// SupportedProviders defines the supported data providers
|
2019-10-25 16:37:12 +00:00
|
|
|
SupportedProviders = []string{SQLiteDataProviderName, PGSQLDataProviderName, MySQLDataProviderName,
|
2021-03-23 18:14:15 +00:00
|
|
|
BoltDataProviderName, MemoryDataProviderName, CockroachDataProviderName}
|
2020-04-09 21:32:42 +00:00
|
|
|
// ValidPerms defines all the valid permissions for a user
|
2021-11-14 15:23:33 +00:00
|
|
|
ValidPerms = []string{PermAny, PermListItems, PermDownload, PermUpload, PermOverwrite, PermCreateDirs, PermRename,
|
2024-02-20 17:19:09 +00:00
|
|
|
PermRenameFiles, PermRenameDirs, PermDelete, PermDeleteFiles, PermDeleteDirs, PermCopy, PermCreateSymlinks,
|
|
|
|
PermChmod, PermChown, PermChtimes}
|
2021-02-28 11:10:40 +00:00
|
|
|
// ValidLoginMethods defines all the valid login methods
|
2022-03-06 15:57:13 +00:00
|
|
|
ValidLoginMethods = []string{SSHLoginMethodPublicKey, LoginMethodPassword, SSHLoginMethodPassword,
|
|
|
|
SSHLoginMethodKeyboardInteractive, SSHLoginMethodKeyAndPassword, SSHLoginMethodKeyAndKeyboardInt,
|
|
|
|
LoginMethodTLSCertificate, LoginMethodTLSCertificateAndPwd}
|
2020-04-09 21:32:42 +00:00
|
|
|
// SSHMultiStepsLoginMethods defines the supported Multi-Step Authentications
|
|
|
|
SSHMultiStepsLoginMethods = []string{SSHLoginMethodKeyAndPassword, SSHLoginMethodKeyAndKeyboardInt}
|
2023-05-12 16:34:59 +00:00
|
|
|
// ErrNoAuthTried defines the error for connection closed before authentication
|
|
|
|
ErrNoAuthTried = errors.New("no auth tried")
|
2021-12-25 11:08:07 +00:00
|
|
|
// ErrNotImplemented defines the error for features not supported for a particular data provider
|
|
|
|
ErrNotImplemented = errors.New("feature not supported with the configured data provider")
|
2020-08-17 10:49:20 +00:00
|
|
|
// ValidProtocols defines all the valid protcols
|
2021-09-04 10:11:04 +00:00
|
|
|
ValidProtocols = []string{protocolSSH, protocolFTP, protocolWebDAV, protocolHTTP}
|
|
|
|
// MFAProtocols defines the supported protocols for multi-factor authentication
|
|
|
|
MFAProtocols = []string{protocolHTTP, protocolSSH, protocolFTP}
|
2020-10-05 17:42:33 +00:00
|
|
|
// ErrNoInitRequired defines the error returned by InitProvider if no inizialization/update is required
|
2021-03-21 18:15:47 +00:00
|
|
|
ErrNoInitRequired = errors.New("the data provider is up to date")
|
2020-08-31 17:25:17 +00:00
|
|
|
// ErrInvalidCredentials defines the error to return if the supplied credentials are invalid
|
2021-11-27 16:04:13 +00:00
|
|
|
ErrInvalidCredentials = errors.New("invalid credentials")
|
|
|
|
// ErrLoginNotAllowedFromIP defines the error to return if login is denied from the current IP
|
2021-11-06 13:13:20 +00:00
|
|
|
ErrLoginNotAllowedFromIP = errors.New("login is not allowed from this IP")
|
2024-01-17 16:36:35 +00:00
|
|
|
// ErrDuplicatedKey occurs when there is a unique key constraint violation
|
|
|
|
ErrDuplicatedKey = errors.New("duplicated key not allowed")
|
|
|
|
// ErrForeignKeyViolated occurs when there is a foreign key constraint violation
|
|
|
|
ErrForeignKeyViolated = errors.New("violates foreign key constraint")
|
2024-06-30 16:52:59 +00:00
|
|
|
tz = ""
|
2024-01-17 16:36:35 +00:00
|
|
|
isAdminCreated atomic.Bool
|
|
|
|
validTLSUsernames = []string{string(sdk.TLSUsernameNone), string(sdk.TLSUsernameCN)}
|
|
|
|
config Config
|
|
|
|
provider Provider
|
|
|
|
sqlPlaceholders []string
|
|
|
|
internalHashPwdPrefixes = []string{argonPwdPrefix, bcryptPwdPrefix}
|
|
|
|
hashPwdPrefixes = []string{argonPwdPrefix, bcryptPwdPrefix, pbkdf2SHA1Prefix, pbkdf2SHA256Prefix,
|
2023-06-03 14:58:45 +00:00
|
|
|
pbkdf2SHA512Prefix, pbkdf2SHA256B64SaltPrefix, md5cryptPwdPrefix, md5cryptApr1PwdPrefix, md5DigestPwdPrefix,
|
|
|
|
sha256DigestPwdPrefix, sha512DigestPwdPrefix, sha256cryptPwdPrefix, sha512cryptPwdPrefix, yescryptPwdPrefix}
|
2023-03-26 08:33:30 +00:00
|
|
|
pbkdfPwdPrefixes = []string{pbkdf2SHA1Prefix, pbkdf2SHA256Prefix, pbkdf2SHA512Prefix, pbkdf2SHA256B64SaltPrefix}
|
|
|
|
pbkdfPwdB64SaltPrefixes = []string{pbkdf2SHA256B64SaltPrefix}
|
|
|
|
unixPwdPrefixes = []string{md5cryptPwdPrefix, md5cryptApr1PwdPrefix, sha256cryptPwdPrefix, sha512cryptPwdPrefix,
|
|
|
|
yescryptPwdPrefix}
|
2023-06-03 14:58:45 +00:00
|
|
|
digestPwdPrefixes = []string{md5DigestPwdPrefix, sha256DigestPwdPrefix, sha512DigestPwdPrefix}
|
2022-04-25 13:49:11 +00:00
|
|
|
sharedProviders = []string{PGSQLDataProviderName, MySQLDataProviderName, CockroachDataProviderName}
|
|
|
|
logSender = "dataprovider"
|
2022-06-24 11:16:45 +00:00
|
|
|
sqlTableUsers string
|
|
|
|
sqlTableFolders string
|
|
|
|
sqlTableUsersFoldersMapping string
|
|
|
|
sqlTableAdmins string
|
|
|
|
sqlTableAPIKeys string
|
|
|
|
sqlTableShares string
|
|
|
|
sqlTableDefenderHosts string
|
|
|
|
sqlTableDefenderEvents string
|
|
|
|
sqlTableActiveTransfers string
|
|
|
|
sqlTableGroups string
|
|
|
|
sqlTableUsersGroupsMapping string
|
2022-09-13 16:04:27 +00:00
|
|
|
sqlTableAdminsGroupsMapping string
|
2022-06-24 11:16:45 +00:00
|
|
|
sqlTableGroupsFoldersMapping string
|
|
|
|
sqlTableSharedSessions string
|
2022-07-11 06:17:36 +00:00
|
|
|
sqlTableEventsActions string
|
|
|
|
sqlTableEventsRules string
|
|
|
|
sqlTableRulesActionsMapping string
|
|
|
|
sqlTableTasks string
|
2022-09-25 17:48:55 +00:00
|
|
|
sqlTableNodes string
|
2022-11-16 18:04:50 +00:00
|
|
|
sqlTableRoles string
|
2023-02-09 08:33:33 +00:00
|
|
|
sqlTableIPLists string
|
2023-02-19 18:03:45 +00:00
|
|
|
sqlTableConfigs string
|
2022-06-24 11:16:45 +00:00
|
|
|
sqlTableSchemaVersion string
|
2022-04-25 13:49:11 +00:00
|
|
|
argon2Params *argon2id.Params
|
|
|
|
lastLoginMinDelay = 10 * time.Minute
|
|
|
|
usernameRegex = regexp.MustCompile("^[a-zA-Z0-9-_.~]+$")
|
|
|
|
tempPath string
|
2022-10-12 16:12:12 +00:00
|
|
|
allowSelfConnections int
|
2022-08-01 16:48:54 +00:00
|
|
|
fnReloadRules FnReloadRules
|
|
|
|
fnRemoveRule FnRemoveRule
|
|
|
|
fnHandleRuleForProviderEvent FnHandleRuleForProviderEvent
|
2024-08-17 07:11:42 +00:00
|
|
|
fnCanSetHomeDir func() bool
|
|
|
|
fnPreUserValidation func(u *User)
|
|
|
|
fnPreFolderValidation func(f *vfs.BaseVirtualFolder)
|
|
|
|
fnPreGroupValidation func(g *Group)
|
2019-07-20 10:26:52 +00:00
|
|
|
)
|
|
|
|
|
2024-08-17 07:11:42 +00:00
|
|
|
// CanSetHomeDir returns true if the home directory can be changed
|
|
|
|
func CanSetHomeDir() bool {
|
|
|
|
if fnCanSetHomeDir != nil {
|
|
|
|
return fnCanSetHomeDir()
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2022-06-24 11:16:45 +00:00
|
|
|
func initSQLTables() {
|
|
|
|
sqlTableUsers = "users"
|
|
|
|
sqlTableFolders = "folders"
|
|
|
|
sqlTableUsersFoldersMapping = "users_folders_mapping"
|
|
|
|
sqlTableAdmins = "admins"
|
|
|
|
sqlTableAPIKeys = "api_keys"
|
|
|
|
sqlTableShares = "shares"
|
|
|
|
sqlTableDefenderHosts = "defender_hosts"
|
|
|
|
sqlTableDefenderEvents = "defender_events"
|
|
|
|
sqlTableActiveTransfers = "active_transfers"
|
|
|
|
sqlTableGroups = "groups"
|
|
|
|
sqlTableUsersGroupsMapping = "users_groups_mapping"
|
|
|
|
sqlTableGroupsFoldersMapping = "groups_folders_mapping"
|
2022-09-13 16:04:27 +00:00
|
|
|
sqlTableAdminsGroupsMapping = "admins_groups_mapping"
|
2022-06-24 11:16:45 +00:00
|
|
|
sqlTableSharedSessions = "shared_sessions"
|
2022-07-11 06:17:36 +00:00
|
|
|
sqlTableEventsActions = "events_actions"
|
|
|
|
sqlTableEventsRules = "events_rules"
|
|
|
|
sqlTableRulesActionsMapping = "rules_actions_mapping"
|
|
|
|
sqlTableTasks = "tasks"
|
2022-09-25 17:48:55 +00:00
|
|
|
sqlTableNodes = "nodes"
|
2022-11-16 18:04:50 +00:00
|
|
|
sqlTableRoles = "roles"
|
2023-02-09 08:33:33 +00:00
|
|
|
sqlTableIPLists = "ip_lists"
|
2023-02-19 18:03:45 +00:00
|
|
|
sqlTableConfigs = "configurations"
|
2022-06-24 11:16:45 +00:00
|
|
|
sqlTableSchemaVersion = "schema_version"
|
|
|
|
}
|
|
|
|
|
2022-08-01 16:48:54 +00:00
|
|
|
// FnReloadRules defined the callback to reload event rules
|
|
|
|
type FnReloadRules func()
|
|
|
|
|
|
|
|
// FnRemoveRule defines the callback to remove an event rule
|
|
|
|
type FnRemoveRule func(name string)
|
|
|
|
|
|
|
|
// FnHandleRuleForProviderEvent define the callback to handle event rules for provider events
|
2022-12-03 10:45:27 +00:00
|
|
|
type FnHandleRuleForProviderEvent func(operation, executor, ip, objectType, objectName, role string, object plugin.Renderer)
|
2022-08-01 16:48:54 +00:00
|
|
|
|
|
|
|
// SetEventRulesCallbacks sets the event rules callbacks
|
|
|
|
func SetEventRulesCallbacks(reload FnReloadRules, remove FnRemoveRule, handle FnHandleRuleForProviderEvent) {
|
|
|
|
fnReloadRules = reload
|
|
|
|
fnRemoveRule = remove
|
|
|
|
fnHandleRuleForProviderEvent = handle
|
|
|
|
}
|
|
|
|
|
2020-02-08 13:44:25 +00:00
|
|
|
type schemaVersion struct {
|
|
|
|
Version int
|
|
|
|
}
|
|
|
|
|
2021-04-20 11:55:09 +00:00
|
|
|
// BcryptOptions defines the options for bcrypt password hashing
|
|
|
|
type BcryptOptions struct {
|
|
|
|
Cost int `json:"cost" mapstructure:"cost"`
|
|
|
|
}
|
|
|
|
|
2020-09-04 15:09:31 +00:00
|
|
|
// Argon2Options defines the options for argon2 password hashing
|
|
|
|
type Argon2Options struct {
|
|
|
|
Memory uint32 `json:"memory" mapstructure:"memory"`
|
|
|
|
Iterations uint32 `json:"iterations" mapstructure:"iterations"`
|
|
|
|
Parallelism uint8 `json:"parallelism" mapstructure:"parallelism"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// PasswordHashing defines the configuration for password hashing
|
|
|
|
type PasswordHashing struct {
|
2021-04-20 11:55:09 +00:00
|
|
|
BcryptOptions BcryptOptions `json:"bcrypt_options" mapstructure:"bcrypt_options"`
|
2021-04-25 07:38:33 +00:00
|
|
|
Argon2Options Argon2Options `json:"argon2_options" mapstructure:"argon2_options"`
|
|
|
|
// Algorithm to use for hashing passwords. Available algorithms: argon2id, bcrypt. Default: bcrypt
|
|
|
|
Algo string `json:"algo" mapstructure:"algo"`
|
2020-09-04 15:09:31 +00:00
|
|
|
}
|
|
|
|
|
2021-08-06 16:56:07 +00:00
|
|
|
// PasswordValidationRules defines the password validation rules
|
|
|
|
type PasswordValidationRules struct {
|
|
|
|
// MinEntropy defines the minimum password entropy.
|
|
|
|
// 0 means disabled, any password will be accepted.
|
|
|
|
// Take a look at the following link for more details
|
|
|
|
// https://github.com/wagslane/go-password-validator#what-entropy-value-should-i-use
|
|
|
|
MinEntropy float64 `json:"min_entropy" mapstructure:"min_entropy"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// PasswordValidation defines the password validation rules for admins and protocol users
|
|
|
|
type PasswordValidation struct {
|
|
|
|
// Password validation rules for SFTPGo admin users
|
|
|
|
Admins PasswordValidationRules `json:"admins" mapstructure:"admins"`
|
|
|
|
// Password validation rules for SFTPGo protocol users
|
|
|
|
Users PasswordValidationRules `json:"users" mapstructure:"users"`
|
|
|
|
}
|
|
|
|
|
2022-07-24 06:10:23 +00:00
|
|
|
type wrappedFolder struct {
|
|
|
|
Folder vfs.BaseVirtualFolder
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w *wrappedFolder) RenderAsJSON(reload bool) ([]byte, error) {
|
|
|
|
if reload {
|
|
|
|
folder, err := provider.getFolderByName(w.Folder.Name)
|
|
|
|
if err != nil {
|
|
|
|
providerLog(logger.LevelError, "unable to reload folder before rendering as json: %v", err)
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
folder.PrepareForRendering()
|
|
|
|
return json.Marshal(folder)
|
|
|
|
}
|
|
|
|
w.Folder.PrepareForRendering()
|
|
|
|
return json.Marshal(w.Folder)
|
|
|
|
}
|
|
|
|
|
2021-10-10 11:08:05 +00:00
|
|
|
// ObjectsActions defines the action to execute on user create, update, delete for the specified objects
|
|
|
|
type ObjectsActions struct {
|
2019-11-14 10:06:03 +00:00
|
|
|
// Valid values are add, update, delete. Empty slice to disable
|
|
|
|
ExecuteOn []string `json:"execute_on" mapstructure:"execute_on"`
|
2021-10-10 11:08:05 +00:00
|
|
|
// Valid values are user, admin, api_key
|
|
|
|
ExecuteFor []string `json:"execute_for" mapstructure:"execute_for"`
|
2020-05-24 13:29:39 +00:00
|
|
|
// Absolute path to an external program or an HTTP URL
|
|
|
|
Hook string `json:"hook" mapstructure:"hook"`
|
2019-11-14 10:06:03 +00:00
|
|
|
}
|
|
|
|
|
2020-12-08 10:18:34 +00:00
|
|
|
// ProviderStatus defines the provider status
|
|
|
|
type ProviderStatus struct {
|
|
|
|
Driver string `json:"driver"`
|
|
|
|
IsActive bool `json:"is_active"`
|
|
|
|
Error string `json:"error"`
|
|
|
|
}
|
|
|
|
|
2022-09-25 17:48:55 +00:00
|
|
|
// Config defines the provider configuration
|
2019-07-20 10:26:52 +00:00
|
|
|
type Config struct {
|
2019-07-30 18:51:29 +00:00
|
|
|
// Driver name, must be one of the SupportedProviders
|
2019-08-07 20:46:13 +00:00
|
|
|
Driver string `json:"driver" mapstructure:"driver"`
|
2020-01-06 20:42:41 +00:00
|
|
|
// Database name. For driver sqlite this can be the database name relative to the config dir
|
|
|
|
// or the absolute path to the SQLite database.
|
2019-08-07 20:46:13 +00:00
|
|
|
Name string `json:"name" mapstructure:"name"`
|
2022-10-02 10:43:26 +00:00
|
|
|
// Database host. For postgresql and cockroachdb driver you can specify multiple hosts separated by commas
|
2019-08-07 20:46:13 +00:00
|
|
|
Host string `json:"host" mapstructure:"host"`
|
2019-07-30 18:51:29 +00:00
|
|
|
// Database port
|
2019-08-07 20:46:13 +00:00
|
|
|
Port int `json:"port" mapstructure:"port"`
|
2019-07-30 18:51:29 +00:00
|
|
|
// Database username
|
2024-04-26 08:57:38 +00:00
|
|
|
Username string `json:"username" mapstructure:"username"`
|
2019-07-30 18:51:29 +00:00
|
|
|
// Database password
|
2024-04-26 08:57:38 +00:00
|
|
|
Password string `json:"password" mapstructure:"password"`
|
2019-07-30 18:51:29 +00:00
|
|
|
// Used for drivers mysql and postgresql.
|
|
|
|
// 0 disable SSL/TLS connections.
|
|
|
|
// 1 require ssl.
|
|
|
|
// 2 set ssl mode to verify-ca for driver postgresql and skip-verify for driver mysql.
|
|
|
|
// 3 set ssl mode to verify-full for driver postgresql and preferred for driver mysql.
|
2019-08-07 20:46:13 +00:00
|
|
|
SSLMode int `json:"sslmode" mapstructure:"sslmode"`
|
2022-10-02 10:43:26 +00:00
|
|
|
// Used for drivers mysql, postgresql and cockroachdb. Set to true to disable SNI
|
2022-09-07 12:31:50 +00:00
|
|
|
DisableSNI bool `json:"disable_sni" mapstructure:"disable_sni"`
|
2022-10-02 10:43:26 +00:00
|
|
|
// TargetSessionAttrs is a postgresql and cockroachdb specific option.
|
|
|
|
// It determines whether the session must have certain properties to be acceptable.
|
|
|
|
// It's typically used in combination with multiple host names to select the first
|
|
|
|
// acceptable alternative among several hosts
|
|
|
|
TargetSessionAttrs string `json:"target_session_attrs" mapstructure:"target_session_attrs"`
|
2022-01-30 17:04:03 +00:00
|
|
|
// Path to the root certificate authority used to verify that the server certificate was signed by a trusted CA
|
|
|
|
RootCert string `json:"root_cert" mapstructure:"root_cert"`
|
|
|
|
// Path to the client certificate for two-way TLS authentication
|
|
|
|
ClientCert string `json:"client_cert" mapstructure:"client_cert"`
|
|
|
|
// Path to the client key for two-way TLS authentication
|
|
|
|
ClientKey string `json:"client_key" mapstructure:"client_key"`
|
2019-07-30 18:51:29 +00:00
|
|
|
// Custom database connection string.
|
|
|
|
// If not empty this connection string will be used instead of build one using the previous parameters
|
2019-08-07 20:46:13 +00:00
|
|
|
ConnectionString string `json:"connection_string" mapstructure:"connection_string"`
|
2020-06-07 21:30:18 +00:00
|
|
|
// prefix for SQL tables
|
|
|
|
SQLTablesPrefix string `json:"sql_tables_prefix" mapstructure:"sql_tables_prefix"`
|
2019-07-30 18:51:29 +00:00
|
|
|
// Set the preferred way to track users quota between the following choices:
|
|
|
|
// 0, disable quota tracking. REST API to scan user dir and update quota will do nothing
|
|
|
|
// 1, quota is updated each time a user upload or delete a file even if the user has no quota restrictions
|
2020-06-07 21:30:18 +00:00
|
|
|
// 2, quota is updated each time a user upload or delete a file but only for users with quota restrictions
|
|
|
|
// and for virtual folders.
|
2019-07-30 18:51:29 +00:00
|
|
|
// With this configuration the "quota scan" REST API can still be used to periodically update space usage
|
|
|
|
// for users without quota restrictions
|
2019-08-07 20:46:13 +00:00
|
|
|
TrackQuota int `json:"track_quota" mapstructure:"track_quota"`
|
2019-09-13 06:14:07 +00:00
|
|
|
// Sets the maximum number of open connections for mysql and postgresql driver.
|
|
|
|
// Default 0 (unlimited)
|
|
|
|
PoolSize int `json:"pool_size" mapstructure:"pool_size"`
|
2020-03-03 22:25:23 +00:00
|
|
|
// Users default base directory.
|
2019-09-28 20:48:52 +00:00
|
|
|
// If no home dir is defined while adding a new user, and this value is
|
|
|
|
// a valid absolute path, then the user home dir will be automatically
|
|
|
|
// defined as the path obtained joining the base dir and the username
|
|
|
|
UsersBaseDir string `json:"users_base_dir" mapstructure:"users_base_dir"`
|
2021-10-10 11:08:05 +00:00
|
|
|
// Actions to execute on objects add, update, delete.
|
|
|
|
// The supported objects are user, admin, api_key.
|
2019-11-14 16:43:14 +00:00
|
|
|
// Update action will not be fired for internal updates such as the last login or the user quota fields.
|
2021-10-10 11:08:05 +00:00
|
|
|
Actions ObjectsActions `json:"actions" mapstructure:"actions"`
|
2020-04-01 21:25:23 +00:00
|
|
|
// Absolute path to an external program or an HTTP URL to invoke for users authentication.
|
|
|
|
// Leave empty to use builtin authentication.
|
2020-01-06 20:42:41 +00:00
|
|
|
// If the authentication succeed the user will be automatically added/updated inside the defined data provider.
|
|
|
|
// Actions defined for user added/updated will not be executed in this case.
|
|
|
|
// This method is slower than built-in authentication methods, but it's very flexible as anyone can
|
2020-04-01 21:25:23 +00:00
|
|
|
// easily write his own authentication hooks.
|
|
|
|
ExternalAuthHook string `json:"external_auth_hook" mapstructure:"external_auth_hook"`
|
|
|
|
// ExternalAuthScope defines the scope for the external authentication hook.
|
2020-10-05 09:29:18 +00:00
|
|
|
// - 0 means all supported authentication scopes, the external hook will be executed for password,
|
2021-02-28 11:10:40 +00:00
|
|
|
// public key, keyboard interactive authentication and TLS certificates
|
2020-01-21 09:54:05 +00:00
|
|
|
// - 1 means passwords only
|
|
|
|
// - 2 means public keys only
|
|
|
|
// - 4 means keyboard interactive only
|
2021-02-28 11:10:40 +00:00
|
|
|
// - 8 means TLS certificates only
|
2020-01-21 09:54:05 +00:00
|
|
|
// you can combine the scopes, for example 3 means password and public key, 5 password and keyboard
|
|
|
|
// interactive and so on
|
2020-01-06 20:42:41 +00:00
|
|
|
ExternalAuthScope int `json:"external_auth_scope" mapstructure:"external_auth_scope"`
|
2020-04-01 21:25:23 +00:00
|
|
|
// Absolute path to an external program or an HTTP URL to invoke just before the user login.
|
|
|
|
// This program/URL allows to modify or create the user trying to login.
|
|
|
|
// It is useful if you have users with dynamic fields to update just before the login.
|
|
|
|
// Please note that if you want to create a new user, the pre-login hook response must
|
2020-03-27 22:26:22 +00:00
|
|
|
// include all the mandatory user fields.
|
|
|
|
//
|
2020-04-01 21:25:23 +00:00
|
|
|
// The pre-login hook must finish within 30 seconds.
|
2020-02-23 17:50:59 +00:00
|
|
|
//
|
2020-04-01 21:25:23 +00:00
|
|
|
// If an error happens while executing the "PreLoginHook" then login will be denied.
|
|
|
|
// PreLoginHook and ExternalAuthHook are mutally exclusive.
|
2020-02-23 17:50:59 +00:00
|
|
|
// Leave empty to disable.
|
2020-04-01 21:25:23 +00:00
|
|
|
PreLoginHook string `json:"pre_login_hook" mapstructure:"pre_login_hook"`
|
2020-08-12 14:15:12 +00:00
|
|
|
// Absolute path to an external program or an HTTP URL to invoke after the user login.
|
|
|
|
// Based on the configured scope you can choose if notify failed or successful logins
|
|
|
|
// or both
|
|
|
|
PostLoginHook string `json:"post_login_hook" mapstructure:"post_login_hook"`
|
|
|
|
// PostLoginScope defines the scope for the post-login hook.
|
|
|
|
// - 0 means notify both failed and successful logins
|
|
|
|
// - 1 means notify failed logins
|
|
|
|
// - 2 means notify successful logins
|
|
|
|
PostLoginScope int `json:"post_login_scope" mapstructure:"post_login_scope"`
|
2020-08-19 17:36:12 +00:00
|
|
|
// Absolute path to an external program or an HTTP URL to invoke just before password
|
|
|
|
// authentication. This hook allows you to externally check the provided password,
|
|
|
|
// its main use case is to allow to easily support things like password+OTP for protocols
|
|
|
|
// without keyboard interactive support such as FTP and WebDAV. You can ask your users
|
|
|
|
// to login using a string consisting of a fixed password and a One Time Token, you
|
|
|
|
// can verify the token inside the hook and ask to SFTPGo to verify the fixed part.
|
|
|
|
CheckPasswordHook string `json:"check_password_hook" mapstructure:"check_password_hook"`
|
|
|
|
// CheckPasswordScope defines the scope for the check password hook.
|
|
|
|
// - 0 means all protocols
|
|
|
|
// - 1 means SSH
|
|
|
|
// - 2 means FTP
|
|
|
|
// - 4 means WebDAV
|
|
|
|
// you can combine the scopes, for example 6 means FTP and WebDAV
|
|
|
|
CheckPasswordScope int `json:"check_password_scope" mapstructure:"check_password_scope"`
|
2020-10-05 17:42:33 +00:00
|
|
|
// Defines how the database will be initialized/updated:
|
|
|
|
// - 0 means automatically
|
|
|
|
// - 1 means manually using the initprovider sub-command
|
|
|
|
UpdateMode int `json:"update_mode" mapstructure:"update_mode"`
|
2020-10-22 08:42:40 +00:00
|
|
|
// PasswordHashing defines the configuration for password hashing
|
|
|
|
PasswordHashing PasswordHashing `json:"password_hashing" mapstructure:"password_hashing"`
|
2021-08-06 16:56:07 +00:00
|
|
|
// PasswordValidation defines the password validation rules
|
|
|
|
PasswordValidation PasswordValidation `json:"password_validation" mapstructure:"password_validation"`
|
2021-04-20 07:39:36 +00:00
|
|
|
// Verifying argon2 passwords has a high memory and computational cost,
|
|
|
|
// by enabling, in memory, password caching you reduce this cost.
|
|
|
|
PasswordCaching bool `json:"password_caching" mapstructure:"password_caching"`
|
2021-04-11 06:38:43 +00:00
|
|
|
// DelayedQuotaUpdate defines the number of seconds to accumulate quota updates.
|
|
|
|
// If there are a lot of close uploads, accumulating quota updates can save you many
|
|
|
|
// queries to the data provider.
|
|
|
|
// If you want to track quotas, a scheduled quota update is recommended in any case, the stored
|
|
|
|
// quota size may be incorrect for several reasons, such as an unexpected shutdown, temporary provider
|
|
|
|
// failures, file copied outside of SFTPGo, and so on.
|
|
|
|
// 0 means immediate quota update.
|
|
|
|
DelayedQuotaUpdate int `json:"delayed_quota_update" mapstructure:"delayed_quota_update"`
|
2021-05-14 17:21:15 +00:00
|
|
|
// If enabled, a default admin user with username "admin" and password "password" will be created
|
|
|
|
// on first start.
|
|
|
|
// You can also create the first admin user by using the web interface or by loading initial data.
|
|
|
|
CreateDefaultAdmin bool `json:"create_default_admin" mapstructure:"create_default_admin"`
|
2022-01-31 17:01:37 +00:00
|
|
|
// Rules for usernames and folder names:
|
|
|
|
// - 0 means no rules
|
|
|
|
// - 1 means you can use any UTF-8 character. The names are used in URIs for REST API and Web admin.
|
|
|
|
// By default only unreserved URI characters are allowed: ALPHA / DIGIT / "-" / "." / "_" / "~".
|
|
|
|
// - 2 means names are converted to lowercase before saving/matching and so case
|
|
|
|
// insensitive matching is possible
|
|
|
|
// - 4 means trimming trailing and leading white spaces before saving/matching
|
|
|
|
// Rules can be combined, for example 3 means both converting to lowercase and allowing any UTF-8 character.
|
|
|
|
// Enabling these options for existing installations could be backward incompatible, some users
|
|
|
|
// could be unable to login, for example existing users with mixed cases in their usernames.
|
|
|
|
// You have to ensure that all existing users respect the defined rules.
|
|
|
|
NamingRules int `json:"naming_rules" mapstructure:"naming_rules"`
|
2021-08-20 07:35:06 +00:00
|
|
|
// If the data provider is shared across multiple SFTPGo instances, set this parameter to 1.
|
|
|
|
// MySQL, PostgreSQL and CockroachDB can be shared, this setting is ignored for other data
|
|
|
|
// providers. For shared data providers, SFTPGo periodically reloads the latest updated users,
|
|
|
|
// based on the "updated_at" field, and updates its internal caches if users are updated from
|
2022-01-30 10:42:36 +00:00
|
|
|
// a different instance. This check, if enabled, is executed every 10 minutes.
|
|
|
|
// For shared data providers, active transfers are persisted in the database and thus
|
|
|
|
// quota checks between ongoing transfers will work cross multiple instances
|
2021-08-20 07:35:06 +00:00
|
|
|
IsShared int `json:"is_shared" mapstructure:"is_shared"`
|
2022-09-25 17:48:55 +00:00
|
|
|
// Node defines the configuration for this cluster node.
|
|
|
|
// Ignored if the provider is not shared/shareable
|
|
|
|
Node NodeConfig `json:"node" mapstructure:"node"`
|
2022-03-13 12:45:07 +00:00
|
|
|
// Path to the backup directory. This can be an absolute path or a path relative to the config dir
|
|
|
|
BackupsPath string `json:"backups_path" mapstructure:"backups_path"`
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
2022-09-07 14:23:56 +00:00
|
|
|
// GetShared returns the provider share mode.
|
|
|
|
// This method is called before the provider is initialized
|
2022-01-30 10:42:36 +00:00
|
|
|
func (c *Config) GetShared() int {
|
2024-07-24 16:27:13 +00:00
|
|
|
if !slices.Contains(sharedProviders, c.Driver) {
|
2022-01-30 10:42:36 +00:00
|
|
|
return 0
|
|
|
|
}
|
|
|
|
return c.IsShared
|
|
|
|
}
|
|
|
|
|
2022-01-31 17:01:37 +00:00
|
|
|
func (c *Config) convertName(name string) string {
|
2022-07-11 06:17:36 +00:00
|
|
|
if c.NamingRules <= 1 {
|
2022-01-31 17:01:37 +00:00
|
|
|
return name
|
|
|
|
}
|
|
|
|
if c.NamingRules&2 != 0 {
|
|
|
|
name = strings.ToLower(name)
|
|
|
|
}
|
|
|
|
if c.NamingRules&4 != 0 {
|
|
|
|
name = strings.TrimSpace(name)
|
|
|
|
}
|
|
|
|
|
|
|
|
return name
|
|
|
|
}
|
|
|
|
|
2021-12-25 11:08:07 +00:00
|
|
|
// IsDefenderSupported returns true if the configured provider supports the defender
|
|
|
|
func (c *Config) IsDefenderSupported() bool {
|
|
|
|
switch c.Driver {
|
|
|
|
case MySQLDataProviderName, PGSQLDataProviderName, CockroachDataProviderName:
|
|
|
|
return true
|
|
|
|
default:
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-30 17:04:03 +00:00
|
|
|
func (c *Config) requireCustomTLSForMySQL() bool {
|
2022-09-07 12:31:50 +00:00
|
|
|
if config.DisableSNI {
|
|
|
|
return config.SSLMode != 0
|
|
|
|
}
|
2022-01-30 17:04:03 +00:00
|
|
|
if config.RootCert != "" && util.IsFileInputValid(config.RootCert) {
|
|
|
|
return config.SSLMode != 0
|
|
|
|
}
|
|
|
|
if config.ClientCert != "" && config.ClientKey != "" && util.IsFileInputValid(config.ClientCert) &&
|
|
|
|
util.IsFileInputValid(config.ClientKey) {
|
|
|
|
return config.SSLMode != 0
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2022-10-29 12:04:31 +00:00
|
|
|
func (c *Config) doBackup() (string, error) {
|
2022-07-11 06:17:36 +00:00
|
|
|
now := time.Now().UTC()
|
|
|
|
outputFile := filepath.Join(c.BackupsPath, fmt.Sprintf("backup_%s_%d.json", now.Weekday(), now.Hour()))
|
2022-08-01 16:48:54 +00:00
|
|
|
providerLog(logger.LevelDebug, "starting backup to file %q", outputFile)
|
2022-03-13 12:45:07 +00:00
|
|
|
err := os.MkdirAll(filepath.Dir(outputFile), 0700)
|
|
|
|
if err != nil {
|
2022-08-01 16:48:54 +00:00
|
|
|
providerLog(logger.LevelError, "unable to create backup dir %q: %v", outputFile, err)
|
2022-10-29 12:04:31 +00:00
|
|
|
return outputFile, fmt.Errorf("unable to create backup dir: %w", err)
|
2022-03-13 12:45:07 +00:00
|
|
|
}
|
2023-04-18 16:11:23 +00:00
|
|
|
backup, err := DumpData(nil)
|
2022-03-13 12:45:07 +00:00
|
|
|
if err != nil {
|
2022-08-01 16:48:54 +00:00
|
|
|
providerLog(logger.LevelError, "unable to execute backup: %v", err)
|
2022-10-29 12:04:31 +00:00
|
|
|
return outputFile, fmt.Errorf("unable to dump backup data: %w", err)
|
2022-03-13 12:45:07 +00:00
|
|
|
}
|
|
|
|
dump, err := json.Marshal(backup)
|
|
|
|
if err != nil {
|
2022-08-01 16:48:54 +00:00
|
|
|
providerLog(logger.LevelError, "unable to marshal backup as JSON: %v", err)
|
2022-10-29 12:04:31 +00:00
|
|
|
return outputFile, fmt.Errorf("unable to marshal backup data as JSON: %w", err)
|
2022-03-13 12:45:07 +00:00
|
|
|
}
|
|
|
|
err = os.WriteFile(outputFile, dump, 0600)
|
|
|
|
if err != nil {
|
2022-08-01 16:48:54 +00:00
|
|
|
providerLog(logger.LevelError, "unable to save backup: %v", err)
|
2022-10-29 12:04:31 +00:00
|
|
|
return outputFile, fmt.Errorf("unable to save backup: %w", err)
|
2022-03-13 12:45:07 +00:00
|
|
|
}
|
2022-08-01 16:48:54 +00:00
|
|
|
providerLog(logger.LevelDebug, "backup saved to %q", outputFile)
|
2022-10-29 12:04:31 +00:00
|
|
|
return outputFile, nil
|
2022-03-13 12:45:07 +00:00
|
|
|
}
|
|
|
|
|
2024-06-30 16:52:59 +00:00
|
|
|
// SetTZ sets the configured timezone.
|
|
|
|
func SetTZ(val string) {
|
|
|
|
tz = val
|
|
|
|
}
|
|
|
|
|
|
|
|
// UseLocalTime returns true if local time should be used instead of UTC.
|
|
|
|
func UseLocalTime() bool {
|
|
|
|
return tz == "local"
|
|
|
|
}
|
|
|
|
|
2022-08-01 16:48:54 +00:00
|
|
|
// ExecuteBackup executes a backup
|
2022-10-29 12:04:31 +00:00
|
|
|
func ExecuteBackup() (string, error) {
|
2022-08-01 16:48:54 +00:00
|
|
|
return config.doBackup()
|
|
|
|
}
|
|
|
|
|
2022-01-31 17:01:37 +00:00
|
|
|
// ConvertName converts the given name based on the configured rules
|
|
|
|
func ConvertName(name string) string {
|
|
|
|
return config.convertName(name)
|
|
|
|
}
|
|
|
|
|
2022-01-20 17:19:20 +00:00
|
|
|
// ActiveTransfer defines an active protocol transfer
|
|
|
|
type ActiveTransfer struct {
|
|
|
|
ID int64
|
|
|
|
Type int
|
|
|
|
ConnID string
|
|
|
|
Username string
|
|
|
|
FolderName string
|
2022-01-30 10:42:36 +00:00
|
|
|
IP string
|
2022-01-20 17:19:20 +00:00
|
|
|
TruncatedSize int64
|
|
|
|
CurrentULSize int64
|
|
|
|
CurrentDLSize int64
|
|
|
|
CreatedAt int64
|
|
|
|
UpdatedAt int64
|
|
|
|
}
|
|
|
|
|
2022-01-30 10:42:36 +00:00
|
|
|
// TransferQuota stores the allowed transfer quota fields
|
|
|
|
type TransferQuota struct {
|
|
|
|
ULSize int64
|
|
|
|
DLSize int64
|
|
|
|
TotalSize int64
|
|
|
|
AllowedULSize int64
|
|
|
|
AllowedDLSize int64
|
|
|
|
AllowedTotalSize int64
|
|
|
|
}
|
|
|
|
|
2022-01-31 18:30:25 +00:00
|
|
|
// HasSizeLimits returns true if any size limit is set
|
|
|
|
func (q *TransferQuota) HasSizeLimits() bool {
|
|
|
|
return q.AllowedDLSize > 0 || q.AllowedULSize > 0 || q.AllowedTotalSize > 0
|
|
|
|
}
|
|
|
|
|
2022-01-30 10:42:36 +00:00
|
|
|
// HasUploadSpace returns true if there is transfer upload space available
|
|
|
|
func (q *TransferQuota) HasUploadSpace() bool {
|
|
|
|
if q.TotalSize <= 0 && q.ULSize <= 0 {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
if q.TotalSize > 0 {
|
|
|
|
return q.AllowedTotalSize > 0
|
|
|
|
}
|
|
|
|
return q.AllowedULSize > 0
|
|
|
|
}
|
|
|
|
|
|
|
|
// HasDownloadSpace returns true if there is transfer download space available
|
|
|
|
func (q *TransferQuota) HasDownloadSpace() bool {
|
|
|
|
if q.TotalSize <= 0 && q.DLSize <= 0 {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
if q.TotalSize > 0 {
|
|
|
|
return q.AllowedTotalSize > 0
|
|
|
|
}
|
|
|
|
return q.AllowedDLSize > 0
|
2022-01-20 17:19:20 +00:00
|
|
|
}
|
|
|
|
|
2021-12-25 11:08:07 +00:00
|
|
|
// DefenderEntry defines a defender entry
|
|
|
|
type DefenderEntry struct {
|
|
|
|
ID int64 `json:"-"`
|
|
|
|
IP string `json:"ip"`
|
|
|
|
Score int `json:"score,omitempty"`
|
|
|
|
BanTime time.Time `json:"ban_time,omitempty"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetID returns an unique ID for a defender entry
|
|
|
|
func (d *DefenderEntry) GetID() string {
|
|
|
|
return hex.EncodeToString([]byte(d.IP))
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetBanTime returns the ban time for a defender entry as string
|
|
|
|
func (d *DefenderEntry) GetBanTime() string {
|
|
|
|
if d.BanTime.IsZero() {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
return d.BanTime.UTC().Format(time.RFC3339)
|
|
|
|
}
|
|
|
|
|
|
|
|
// MarshalJSON returns the JSON encoding of a DefenderEntry.
|
|
|
|
func (d *DefenderEntry) MarshalJSON() ([]byte, error) {
|
|
|
|
return json.Marshal(&struct {
|
|
|
|
ID string `json:"id"`
|
|
|
|
IP string `json:"ip"`
|
|
|
|
Score int `json:"score,omitempty"`
|
|
|
|
BanTime string `json:"ban_time,omitempty"`
|
|
|
|
}{
|
|
|
|
ID: d.GetID(),
|
|
|
|
IP: d.IP,
|
|
|
|
Score: d.Score,
|
|
|
|
BanTime: d.GetBanTime(),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-02-02 21:20:39 +00:00
|
|
|
// BackupData defines the structure for the backup/restore files
|
|
|
|
type BackupData struct {
|
2022-07-11 06:17:36 +00:00
|
|
|
Users []User `json:"users"`
|
|
|
|
Groups []Group `json:"groups"`
|
|
|
|
Folders []vfs.BaseVirtualFolder `json:"folders"`
|
|
|
|
Admins []Admin `json:"admins"`
|
|
|
|
APIKeys []APIKey `json:"api_keys"`
|
|
|
|
Shares []Share `json:"shares"`
|
|
|
|
EventActions []BaseEventAction `json:"event_actions"`
|
|
|
|
EventRules []EventRule `json:"event_rules"`
|
2022-11-16 18:04:50 +00:00
|
|
|
Roles []Role `json:"roles"`
|
2023-02-09 08:33:33 +00:00
|
|
|
IPLists []IPListEntry `json:"ip_lists"`
|
2023-02-19 18:03:45 +00:00
|
|
|
Configs *Configs `json:"configs"`
|
2022-07-11 06:17:36 +00:00
|
|
|
Version int `json:"version"`
|
2020-02-02 21:20:39 +00:00
|
|
|
}
|
|
|
|
|
2021-02-01 18:04:15 +00:00
|
|
|
// HasFolder returns true if the folder with the given name is included
|
|
|
|
func (d *BackupData) HasFolder(name string) bool {
|
|
|
|
for _, folder := range d.Folders {
|
|
|
|
if folder.Name == name {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2020-08-19 17:36:12 +00:00
|
|
|
type checkPasswordRequest struct {
|
|
|
|
Username string `json:"username"`
|
|
|
|
IP string `json:"ip"`
|
|
|
|
Password string `json:"password"`
|
|
|
|
Protocol string `json:"protocol"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type checkPasswordResponse struct {
|
|
|
|
// 0 KO, 1 OK, 2 partial success, -1 not executed
|
|
|
|
Status int `json:"status"`
|
|
|
|
// for status = 2 this is the password to check against the one stored
|
|
|
|
// inside the SFTPGo data provider
|
|
|
|
ToVerify string `json:"to_verify"`
|
|
|
|
}
|
|
|
|
|
2019-11-26 21:26:42 +00:00
|
|
|
// GetQuotaTracking returns the configured mode for user's quota tracking
|
|
|
|
func GetQuotaTracking() int {
|
|
|
|
return config.TrackQuota
|
|
|
|
}
|
|
|
|
|
2022-01-10 18:44:16 +00:00
|
|
|
// HasUsersBaseDir returns true if users base dir is set
|
|
|
|
func HasUsersBaseDir() bool {
|
|
|
|
return config.UsersBaseDir != ""
|
|
|
|
}
|
|
|
|
|
2020-06-07 21:30:18 +00:00
|
|
|
// Provider defines the interface that data providers must implement.
|
2019-07-20 10:26:52 +00:00
|
|
|
type Provider interface {
|
2020-08-19 17:36:12 +00:00
|
|
|
validateUserAndPass(username, password, ip, protocol string) (User, error)
|
2022-03-31 16:16:50 +00:00
|
|
|
validateUserAndPubKey(username string, pubKey []byte, isSSHCert bool) (User, string, error)
|
2021-02-28 11:10:40 +00:00
|
|
|
validateUserAndTLSCert(username, protocol string, tlsCert *x509.Certificate) (User, error)
|
2019-07-20 10:26:52 +00:00
|
|
|
updateQuota(username string, filesAdd int, sizeAdd int64, reset bool) error
|
2022-01-30 10:42:36 +00:00
|
|
|
updateTransferQuota(username string, uploadSize, downloadSize int64, reset bool) error
|
|
|
|
getUsedQuota(username string) (int, int64, int64, int64, error)
|
2022-11-16 18:04:50 +00:00
|
|
|
userExists(username, role string) (User, error)
|
2021-01-05 08:50:22 +00:00
|
|
|
addUser(user *User) error
|
|
|
|
updateUser(user *User) error
|
2022-07-17 16:48:41 +00:00
|
|
|
deleteUser(user User, softDelete bool) error
|
2022-12-11 16:15:34 +00:00
|
|
|
updateUserPassword(username, password string) error // used internally when converting passwords from other hash
|
2022-11-16 18:04:50 +00:00
|
|
|
getUsers(limit int, offset int, order, role string) ([]User, error)
|
2019-12-27 22:12:44 +00:00
|
|
|
dumpUsers() ([]User, error)
|
2021-08-20 07:35:06 +00:00
|
|
|
getRecentlyUpdatedUsers(after int64) ([]User, error)
|
2022-01-20 17:19:20 +00:00
|
|
|
getUsersForQuotaCheck(toFetch map[string]bool) ([]User, error)
|
2019-11-13 10:36:21 +00:00
|
|
|
updateLastLogin(username string) error
|
2021-08-19 13:51:43 +00:00
|
|
|
updateAdminLastLogin(username string) error
|
|
|
|
setUpdatedAt(username string)
|
2022-04-25 13:49:11 +00:00
|
|
|
getFolders(limit, offset int, order string, minimal bool) ([]vfs.BaseVirtualFolder, error)
|
2021-02-01 18:04:15 +00:00
|
|
|
getFolderByName(name string) (vfs.BaseVirtualFolder, error)
|
2021-01-05 08:50:22 +00:00
|
|
|
addFolder(folder *vfs.BaseVirtualFolder) error
|
2021-02-01 18:04:15 +00:00
|
|
|
updateFolder(folder *vfs.BaseVirtualFolder) error
|
2022-04-25 13:49:11 +00:00
|
|
|
deleteFolder(folder vfs.BaseVirtualFolder) error
|
2021-02-01 18:04:15 +00:00
|
|
|
updateFolderQuota(name string, filesAdd int, sizeAdd int64, reset bool) error
|
|
|
|
getUsedFolderQuota(name string) (int, int64, error)
|
2020-06-07 21:30:18 +00:00
|
|
|
dumpFolders() ([]vfs.BaseVirtualFolder, error)
|
2022-04-25 13:49:11 +00:00
|
|
|
getGroups(limit, offset int, order string, minimal bool) ([]Group, error)
|
|
|
|
getGroupsWithNames(names []string) ([]Group, error)
|
|
|
|
getUsersInGroups(names []string) ([]string, error)
|
|
|
|
groupExists(name string) (Group, error)
|
|
|
|
addGroup(group *Group) error
|
|
|
|
updateGroup(group *Group) error
|
|
|
|
deleteGroup(group Group) error
|
|
|
|
dumpGroups() ([]Group, error)
|
2021-01-17 21:29:08 +00:00
|
|
|
adminExists(username string) (Admin, error)
|
|
|
|
addAdmin(admin *Admin) error
|
|
|
|
updateAdmin(admin *Admin) error
|
2022-04-25 13:49:11 +00:00
|
|
|
deleteAdmin(admin Admin) error
|
2021-01-17 21:29:08 +00:00
|
|
|
getAdmins(limit int, offset int, order string) ([]Admin, error)
|
|
|
|
dumpAdmins() ([]Admin, error)
|
|
|
|
validateAdminAndPass(username, password, ip string) (Admin, error)
|
2021-08-17 16:08:32 +00:00
|
|
|
apiKeyExists(keyID string) (APIKey, error)
|
|
|
|
addAPIKey(apiKey *APIKey) error
|
|
|
|
updateAPIKey(apiKey *APIKey) error
|
2022-04-25 13:49:11 +00:00
|
|
|
deleteAPIKey(apiKey APIKey) error
|
2021-08-17 16:08:32 +00:00
|
|
|
getAPIKeys(limit int, offset int, order string) ([]APIKey, error)
|
|
|
|
dumpAPIKeys() ([]APIKey, error)
|
|
|
|
updateAPIKeyLastUse(keyID string) error
|
2021-11-06 13:13:20 +00:00
|
|
|
shareExists(shareID, username string) (Share, error)
|
|
|
|
addShare(share *Share) error
|
|
|
|
updateShare(share *Share) error
|
2022-04-25 13:49:11 +00:00
|
|
|
deleteShare(share Share) error
|
2021-11-06 13:13:20 +00:00
|
|
|
getShares(limit int, offset int, order, username string) ([]Share, error)
|
|
|
|
dumpShares() ([]Share, error)
|
|
|
|
updateShareLastUse(shareID string, numTokens int) error
|
2022-01-16 11:09:17 +00:00
|
|
|
getDefenderHosts(from int64, limit int) ([]DefenderEntry, error)
|
|
|
|
getDefenderHostByIP(ip string, from int64) (DefenderEntry, error)
|
|
|
|
isDefenderHostBanned(ip string) (DefenderEntry, error)
|
2021-12-25 11:08:07 +00:00
|
|
|
updateDefenderBanTime(ip string, minutes int) error
|
|
|
|
deleteDefenderHost(ip string) error
|
|
|
|
addDefenderEvent(ip string, score int) error
|
|
|
|
setDefenderBanTime(ip string, banTime int64) error
|
|
|
|
cleanupDefender(from int64) error
|
2022-01-30 10:42:36 +00:00
|
|
|
addActiveTransfer(transfer ActiveTransfer) error
|
|
|
|
updateActiveTransferSizes(ulSize, dlSize, transferID int64, connectionID string) error
|
|
|
|
removeActiveTransfer(transferID int64, connectionID string) error
|
|
|
|
cleanupActiveTransfers(before time.Time) error
|
|
|
|
getActiveTransfers(from time.Time) ([]ActiveTransfer, error)
|
2022-05-19 17:49:51 +00:00
|
|
|
addSharedSession(session Session) error
|
|
|
|
deleteSharedSession(key string) error
|
|
|
|
getSharedSession(key string) (Session, error)
|
|
|
|
cleanupSharedSessions(sessionType SessionType, before int64) error
|
2022-07-11 06:17:36 +00:00
|
|
|
getEventActions(limit, offset int, order string, minimal bool) ([]BaseEventAction, error)
|
|
|
|
dumpEventActions() ([]BaseEventAction, error)
|
|
|
|
eventActionExists(name string) (BaseEventAction, error)
|
|
|
|
addEventAction(action *BaseEventAction) error
|
|
|
|
updateEventAction(action *BaseEventAction) error
|
|
|
|
deleteEventAction(action BaseEventAction) error
|
|
|
|
getEventRules(limit, offset int, order string) ([]EventRule, error)
|
|
|
|
dumpEventRules() ([]EventRule, error)
|
|
|
|
getRecentlyUpdatedRules(after int64) ([]EventRule, error)
|
|
|
|
eventRuleExists(name string) (EventRule, error)
|
|
|
|
addEventRule(rule *EventRule) error
|
|
|
|
updateEventRule(rule *EventRule) error
|
|
|
|
deleteEventRule(rule EventRule, softDelete bool) error
|
|
|
|
getTaskByName(name string) (Task, error)
|
|
|
|
addTask(name string) error
|
|
|
|
updateTask(name string, version int64) error
|
|
|
|
updateTaskTimestamp(name string) error
|
2022-08-21 17:01:08 +00:00
|
|
|
setFirstDownloadTimestamp(username string) error
|
|
|
|
setFirstUploadTimestamp(username string) error
|
2022-09-25 17:48:55 +00:00
|
|
|
addNode() error
|
|
|
|
getNodeByName(name string) (Node, error)
|
|
|
|
getNodes() ([]Node, error)
|
|
|
|
updateNodeTimestamp() error
|
|
|
|
cleanupNodes() error
|
2022-11-16 18:04:50 +00:00
|
|
|
roleExists(name string) (Role, error)
|
|
|
|
addRole(role *Role) error
|
|
|
|
updateRole(role *Role) error
|
|
|
|
deleteRole(role Role) error
|
|
|
|
getRoles(limit int, offset int, order string, minimal bool) ([]Role, error)
|
|
|
|
dumpRoles() ([]Role, error)
|
2023-02-09 08:33:33 +00:00
|
|
|
ipListEntryExists(ipOrNet string, listType IPListType) (IPListEntry, error)
|
|
|
|
addIPListEntry(entry *IPListEntry) error
|
|
|
|
updateIPListEntry(entry *IPListEntry) error
|
|
|
|
deleteIPListEntry(entry IPListEntry, softDelete bool) error
|
|
|
|
getIPListEntries(listType IPListType, filter, from, order string, limit int) ([]IPListEntry, error)
|
|
|
|
getRecentlyUpdatedIPListEntries(after int64) ([]IPListEntry, error)
|
|
|
|
dumpIPListEntries() ([]IPListEntry, error)
|
|
|
|
countIPListEntries(listType IPListType) (int64, error)
|
|
|
|
getListEntriesForIP(ip string, listType IPListType) ([]IPListEntry, error)
|
2023-02-19 18:03:45 +00:00
|
|
|
getConfigs() (Configs, error)
|
|
|
|
setConfigs(configs *Configs) error
|
2019-09-13 16:45:36 +00:00
|
|
|
checkAvailability() error
|
2019-09-28 20:48:52 +00:00
|
|
|
close() error
|
2020-02-02 21:20:39 +00:00
|
|
|
reloadConfig() error
|
2020-02-08 13:44:25 +00:00
|
|
|
initializeDatabase() error
|
|
|
|
migrateDatabase() error
|
2020-11-26 21:08:33 +00:00
|
|
|
revertDatabase(targetVersion int) error
|
2021-11-15 17:40:31 +00:00
|
|
|
resetDatabase() error
|
2019-09-13 16:45:36 +00:00
|
|
|
}
|
|
|
|
|
2022-10-12 16:12:12 +00:00
|
|
|
// SetAllowSelfConnections sets the desired behaviour for self connections
|
|
|
|
func SetAllowSelfConnections(value int) {
|
|
|
|
allowSelfConnections = value
|
|
|
|
}
|
|
|
|
|
2021-05-31 19:45:29 +00:00
|
|
|
// SetTempPath sets the path for temporary files
|
|
|
|
func SetTempPath(fsPath string) {
|
|
|
|
tempPath = fsPath
|
|
|
|
}
|
|
|
|
|
2022-07-12 06:32:31 +00:00
|
|
|
func checkSharedMode() {
|
2024-07-24 16:27:13 +00:00
|
|
|
if !slices.Contains(sharedProviders, config.Driver) {
|
2022-07-12 06:32:31 +00:00
|
|
|
config.IsShared = 0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-30 18:51:29 +00:00
|
|
|
// Initialize the data provider.
|
|
|
|
// An error is returned if the configured driver is invalid or if the data provider cannot be initialized
|
2021-01-17 21:29:08 +00:00
|
|
|
func Initialize(cnf Config, basePath string, checkAdmins bool) error {
|
2019-07-20 10:26:52 +00:00
|
|
|
config = cnf
|
2022-07-12 06:32:31 +00:00
|
|
|
checkSharedMode()
|
2022-05-31 16:22:18 +00:00
|
|
|
config.Actions.ExecuteOn = util.RemoveDuplicates(config.Actions.ExecuteOn, true)
|
|
|
|
config.Actions.ExecuteFor = util.RemoveDuplicates(config.Actions.ExecuteFor, true)
|
2020-01-06 20:42:41 +00:00
|
|
|
|
2022-03-13 12:45:07 +00:00
|
|
|
cnf.BackupsPath = getConfigPath(cnf.BackupsPath, basePath)
|
|
|
|
if cnf.BackupsPath == "" {
|
2023-02-26 14:15:34 +00:00
|
|
|
return fmt.Errorf("required directory is invalid, backup path %q", cnf.BackupsPath)
|
2020-02-23 17:50:59 +00:00
|
|
|
}
|
2022-10-29 12:04:31 +00:00
|
|
|
absoluteBackupPath, err := util.GetAbsolutePath(cnf.BackupsPath)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("unable to get absolute backup path: %w", err)
|
|
|
|
}
|
|
|
|
config.BackupsPath = absoluteBackupPath
|
2020-11-25 13:18:12 +00:00
|
|
|
|
2022-09-25 17:48:55 +00:00
|
|
|
if err := initializeHashingAlgo(&cnf); err != nil {
|
2021-05-14 17:21:15 +00:00
|
|
|
return err
|
2021-04-20 11:55:09 +00:00
|
|
|
}
|
2022-09-25 17:48:55 +00:00
|
|
|
if err := validateHooks(); err != nil {
|
2020-11-22 20:53:04 +00:00
|
|
|
return err
|
2020-02-08 13:44:25 +00:00
|
|
|
}
|
2022-09-25 17:48:55 +00:00
|
|
|
if err := createProvider(basePath); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := checkDatabase(checkAdmins); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
admins, err := provider.getAdmins(1, 0, OrderASC)
|
2020-02-08 13:44:25 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-09-25 17:48:55 +00:00
|
|
|
isAdminCreated.Store(len(admins) > 0)
|
|
|
|
if err := config.Node.validate(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
delayedQuotaUpdater.start()
|
2023-06-03 15:54:24 +00:00
|
|
|
if currentNode != nil {
|
|
|
|
config.BackupsPath = filepath.Join(config.BackupsPath, currentNode.Name)
|
|
|
|
}
|
|
|
|
providerLog(logger.LevelDebug, "absolute backup path %q", config.BackupsPath)
|
2022-09-25 17:48:55 +00:00
|
|
|
return startScheduler()
|
|
|
|
}
|
|
|
|
|
|
|
|
func checkDatabase(checkAdmins bool) error {
|
|
|
|
if config.UpdateMode == 0 {
|
|
|
|
err := provider.initializeDatabase()
|
2020-10-05 17:42:33 +00:00
|
|
|
if err != nil && err != ErrNoInitRequired {
|
2024-06-15 14:02:09 +00:00
|
|
|
logger.WarnToConsole("unable to initialize data provider: %v", err)
|
|
|
|
providerLog(logger.LevelError, "unable to initialize data provider: %v", err)
|
2020-10-05 17:42:33 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err == nil {
|
2024-06-15 14:02:09 +00:00
|
|
|
logger.DebugToConsole("data provider successfully initialized")
|
|
|
|
providerLog(logger.LevelInfo, "data provider successfully initialized")
|
2020-10-05 17:42:33 +00:00
|
|
|
}
|
|
|
|
err = provider.migrateDatabase()
|
|
|
|
if err != nil && err != ErrNoInitRequired {
|
2021-12-16 18:53:00 +00:00
|
|
|
providerLog(logger.LevelError, "database migration error: %v", err)
|
2020-10-05 17:42:33 +00:00
|
|
|
return err
|
|
|
|
}
|
2022-09-25 17:48:55 +00:00
|
|
|
if checkAdmins && config.CreateDefaultAdmin {
|
2021-01-17 21:29:08 +00:00
|
|
|
err = checkDefaultAdmin()
|
|
|
|
if err != nil {
|
2021-12-16 18:53:00 +00:00
|
|
|
providerLog(logger.LevelError, "erro checking the default admin: %v", err)
|
2021-01-17 21:29:08 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2020-10-05 17:42:33 +00:00
|
|
|
} else {
|
|
|
|
providerLog(logger.LevelInfo, "database initialization/migration skipped, manual mode is configured")
|
2020-01-31 18:04:00 +00:00
|
|
|
}
|
2022-09-25 17:48:55 +00:00
|
|
|
return nil
|
2020-02-08 13:44:25 +00:00
|
|
|
}
|
2020-01-06 20:42:41 +00:00
|
|
|
|
2020-04-01 21:25:23 +00:00
|
|
|
func validateHooks() error {
|
2020-08-19 17:36:12 +00:00
|
|
|
var hooks []string
|
2021-01-05 08:50:22 +00:00
|
|
|
if config.PreLoginHook != "" && !strings.HasPrefix(config.PreLoginHook, "http") {
|
2020-08-19 17:36:12 +00:00
|
|
|
hooks = append(hooks, config.PreLoginHook)
|
2020-04-01 21:25:23 +00:00
|
|
|
}
|
2021-01-05 08:50:22 +00:00
|
|
|
if config.ExternalAuthHook != "" && !strings.HasPrefix(config.ExternalAuthHook, "http") {
|
2020-08-19 17:36:12 +00:00
|
|
|
hooks = append(hooks, config.ExternalAuthHook)
|
2020-04-01 21:25:23 +00:00
|
|
|
}
|
2021-01-05 08:50:22 +00:00
|
|
|
if config.PostLoginHook != "" && !strings.HasPrefix(config.PostLoginHook, "http") {
|
2020-08-19 17:36:12 +00:00
|
|
|
hooks = append(hooks, config.PostLoginHook)
|
|
|
|
}
|
2021-01-05 08:50:22 +00:00
|
|
|
if config.CheckPasswordHook != "" && !strings.HasPrefix(config.CheckPasswordHook, "http") {
|
2020-08-19 17:36:12 +00:00
|
|
|
hooks = append(hooks, config.CheckPasswordHook)
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, hook := range hooks {
|
|
|
|
if !filepath.IsAbs(hook) {
|
2023-02-26 14:15:34 +00:00
|
|
|
return fmt.Errorf("invalid hook: %q must be an absolute path", hook)
|
2020-08-12 14:15:12 +00:00
|
|
|
}
|
2020-08-19 17:36:12 +00:00
|
|
|
_, err := os.Stat(hook)
|
2020-08-12 14:15:12 +00:00
|
|
|
if err != nil {
|
2021-12-16 18:53:00 +00:00
|
|
|
providerLog(logger.LevelError, "invalid hook: %v", err)
|
2020-08-12 14:15:12 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2020-08-19 17:36:12 +00:00
|
|
|
|
2020-04-01 21:25:23 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-03-13 12:45:07 +00:00
|
|
|
// GetBackupsPath returns the normalized backups path
|
|
|
|
func GetBackupsPath() string {
|
|
|
|
return config.BackupsPath
|
|
|
|
}
|
|
|
|
|
2024-04-27 08:50:25 +00:00
|
|
|
// GetProviderFromValue returns the FilesystemProvider matching the specified value.
|
|
|
|
// If no match is found LocalFilesystemProvider is returned.
|
|
|
|
func GetProviderFromValue(value string) sdk.FilesystemProvider {
|
|
|
|
val, err := strconv.Atoi(value)
|
|
|
|
if err != nil {
|
|
|
|
return sdk.LocalFilesystemProvider
|
|
|
|
}
|
|
|
|
result := sdk.FilesystemProvider(val)
|
|
|
|
if sdk.IsProviderSupported(result) {
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
return sdk.LocalFilesystemProvider
|
|
|
|
}
|
|
|
|
|
2021-05-14 17:21:15 +00:00
|
|
|
func initializeHashingAlgo(cnf *Config) error {
|
2023-10-17 16:06:52 +00:00
|
|
|
parallelism := cnf.PasswordHashing.Argon2Options.Parallelism
|
|
|
|
if parallelism == 0 {
|
|
|
|
parallelism = uint8(runtime.NumCPU())
|
|
|
|
}
|
2021-05-14 17:21:15 +00:00
|
|
|
argon2Params = &argon2id.Params{
|
|
|
|
Memory: cnf.PasswordHashing.Argon2Options.Memory,
|
|
|
|
Iterations: cnf.PasswordHashing.Argon2Options.Iterations,
|
2023-10-17 16:06:52 +00:00
|
|
|
Parallelism: parallelism,
|
2021-05-14 17:21:15 +00:00
|
|
|
SaltLength: 16,
|
|
|
|
KeyLength: 32,
|
|
|
|
}
|
|
|
|
|
|
|
|
if config.PasswordHashing.Algo == HashingAlgoBcrypt {
|
|
|
|
if config.PasswordHashing.BcryptOptions.Cost > bcrypt.MaxCost {
|
|
|
|
err := fmt.Errorf("invalid bcrypt cost %v, max allowed %v", config.PasswordHashing.BcryptOptions.Cost, bcrypt.MaxCost)
|
|
|
|
logger.WarnToConsole("Unable to initialize data provider: %v", err)
|
2021-12-16 18:53:00 +00:00
|
|
|
providerLog(logger.LevelError, "Unable to initialize data provider: %v", err)
|
2021-05-14 17:21:15 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-06-07 21:30:18 +00:00
|
|
|
func validateSQLTablesPrefix() error {
|
2022-06-24 11:16:45 +00:00
|
|
|
initSQLTables()
|
2021-04-12 18:00:49 +00:00
|
|
|
if config.SQLTablesPrefix != "" {
|
2020-06-07 21:30:18 +00:00
|
|
|
for _, char := range config.SQLTablesPrefix {
|
|
|
|
if !strings.Contains(sqlPrefixValidChars, strings.ToLower(string(char))) {
|
2021-04-12 18:00:49 +00:00
|
|
|
return errors.New("invalid sql_tables_prefix only chars in range 'a..z', 'A..Z', '0-9' and '_' are allowed")
|
2020-06-07 21:30:18 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
sqlTableUsers = config.SQLTablesPrefix + sqlTableUsers
|
|
|
|
sqlTableFolders = config.SQLTablesPrefix + sqlTableFolders
|
2022-06-24 11:16:45 +00:00
|
|
|
sqlTableUsersFoldersMapping = config.SQLTablesPrefix + sqlTableUsersFoldersMapping
|
2021-01-17 21:29:08 +00:00
|
|
|
sqlTableAdmins = config.SQLTablesPrefix + sqlTableAdmins
|
2021-08-17 16:08:32 +00:00
|
|
|
sqlTableAPIKeys = config.SQLTablesPrefix + sqlTableAPIKeys
|
2021-11-06 13:13:20 +00:00
|
|
|
sqlTableShares = config.SQLTablesPrefix + sqlTableShares
|
2022-01-30 10:42:36 +00:00
|
|
|
sqlTableDefenderEvents = config.SQLTablesPrefix + sqlTableDefenderEvents
|
|
|
|
sqlTableDefenderHosts = config.SQLTablesPrefix + sqlTableDefenderHosts
|
|
|
|
sqlTableActiveTransfers = config.SQLTablesPrefix + sqlTableActiveTransfers
|
2022-06-24 11:16:45 +00:00
|
|
|
sqlTableGroups = config.SQLTablesPrefix + sqlTableGroups
|
|
|
|
sqlTableUsersGroupsMapping = config.SQLTablesPrefix + sqlTableUsersGroupsMapping
|
2022-09-13 16:04:27 +00:00
|
|
|
sqlTableAdminsGroupsMapping = config.SQLTablesPrefix + sqlTableAdminsGroupsMapping
|
2022-06-24 11:16:45 +00:00
|
|
|
sqlTableGroupsFoldersMapping = config.SQLTablesPrefix + sqlTableGroupsFoldersMapping
|
|
|
|
sqlTableSharedSessions = config.SQLTablesPrefix + sqlTableSharedSessions
|
2022-07-11 06:17:36 +00:00
|
|
|
sqlTableEventsActions = config.SQLTablesPrefix + sqlTableEventsActions
|
|
|
|
sqlTableEventsRules = config.SQLTablesPrefix + sqlTableEventsRules
|
|
|
|
sqlTableRulesActionsMapping = config.SQLTablesPrefix + sqlTableRulesActionsMapping
|
|
|
|
sqlTableTasks = config.SQLTablesPrefix + sqlTableTasks
|
2022-09-25 17:48:55 +00:00
|
|
|
sqlTableNodes = config.SQLTablesPrefix + sqlTableNodes
|
2022-11-16 18:04:50 +00:00
|
|
|
sqlTableRoles = config.SQLTablesPrefix + sqlTableRoles
|
2023-02-09 08:33:33 +00:00
|
|
|
sqlTableIPLists = config.SQLTablesPrefix + sqlTableIPLists
|
2023-02-19 18:03:45 +00:00
|
|
|
sqlTableConfigs = config.SQLTablesPrefix + sqlTableConfigs
|
2020-06-07 21:30:18 +00:00
|
|
|
sqlTableSchemaVersion = config.SQLTablesPrefix + sqlTableSchemaVersion
|
2022-06-24 11:16:45 +00:00
|
|
|
providerLog(logger.LevelDebug, "sql table for users %q, folders %q users folders mapping %q admins %q "+
|
|
|
|
"api keys %q shares %q defender hosts %q defender events %q transfers %q groups %q "+
|
2022-09-13 16:04:27 +00:00
|
|
|
"users groups mapping %q admins groups mapping %q groups folders mapping %q shared sessions %q "+
|
2023-02-09 08:33:33 +00:00
|
|
|
"schema version %q events actions %q events rules %q rules actions mapping %q tasks %q nodes %q roles %q"+
|
2023-02-19 18:03:45 +00:00
|
|
|
"ip lists %q configs %q",
|
2022-06-24 11:16:45 +00:00
|
|
|
sqlTableUsers, sqlTableFolders, sqlTableUsersFoldersMapping, sqlTableAdmins, sqlTableAPIKeys,
|
|
|
|
sqlTableShares, sqlTableDefenderHosts, sqlTableDefenderEvents, sqlTableActiveTransfers, sqlTableGroups,
|
2022-09-13 16:04:27 +00:00
|
|
|
sqlTableUsersGroupsMapping, sqlTableAdminsGroupsMapping, sqlTableGroupsFoldersMapping, sqlTableSharedSessions,
|
2022-09-25 17:48:55 +00:00
|
|
|
sqlTableSchemaVersion, sqlTableEventsActions, sqlTableEventsRules, sqlTableRulesActionsMapping,
|
2023-02-19 18:03:45 +00:00
|
|
|
sqlTableTasks, sqlTableNodes, sqlTableRoles, sqlTableIPLists, sqlTableConfigs)
|
2020-06-07 21:30:18 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-01-17 21:29:08 +00:00
|
|
|
func checkDefaultAdmin() error {
|
|
|
|
admins, err := provider.getAdmins(1, 0, OrderASC)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if len(admins) > 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
logger.Debug(logSender, "", "no admins found, try to create the default one")
|
|
|
|
// we need to create the default admin
|
|
|
|
admin := &Admin{}
|
2021-08-20 08:37:51 +00:00
|
|
|
if err := admin.setFromEnv(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-01-17 21:29:08 +00:00
|
|
|
return provider.addAdmin(admin)
|
|
|
|
}
|
|
|
|
|
2020-02-08 13:44:25 +00:00
|
|
|
// InitializeDatabase creates the initial database structure
|
|
|
|
func InitializeDatabase(cnf Config, basePath string) error {
|
|
|
|
config = cnf
|
|
|
|
|
2022-02-28 16:05:18 +00:00
|
|
|
if err := initializeHashingAlgo(&cnf); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-11-26 21:08:33 +00:00
|
|
|
|
2020-02-08 13:44:25 +00:00
|
|
|
err := createProvider(basePath)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
2020-10-05 17:42:33 +00:00
|
|
|
err = provider.initializeDatabase()
|
|
|
|
if err != nil && err != ErrNoInitRequired {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return provider.migrateDatabase()
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
2020-11-26 21:08:33 +00:00
|
|
|
// RevertDatabase restores schema and/or data to a previous version
|
|
|
|
func RevertDatabase(cnf Config, basePath string, targetVersion int) error {
|
|
|
|
config = cnf
|
|
|
|
|
|
|
|
err := createProvider(basePath)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
err = provider.initializeDatabase()
|
|
|
|
if err != nil && err != ErrNoInitRequired {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return provider.revertDatabase(targetVersion)
|
|
|
|
}
|
|
|
|
|
2021-11-15 17:40:31 +00:00
|
|
|
// ResetDatabase restores schema and/or data to a previous version
|
|
|
|
func ResetDatabase(cnf Config, basePath string) error {
|
|
|
|
config = cnf
|
|
|
|
|
|
|
|
if err := createProvider(basePath); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return provider.resetDatabase()
|
|
|
|
}
|
|
|
|
|
2021-01-17 21:29:08 +00:00
|
|
|
// CheckAdminAndPass validates the given admin and password connecting from ip
|
|
|
|
func CheckAdminAndPass(username, password, ip string) (Admin, error) {
|
2022-01-31 17:01:37 +00:00
|
|
|
username = config.convertName(username)
|
2021-01-17 21:29:08 +00:00
|
|
|
return provider.validateAdminAndPass(username, password, ip)
|
|
|
|
}
|
|
|
|
|
2021-03-01 18:28:11 +00:00
|
|
|
// CheckCachedUserCredentials checks the credentials for a cached user
|
2023-05-20 10:39:07 +00:00
|
|
|
func CheckCachedUserCredentials(user *CachedUser, password, ip, loginMethod, protocol string, tlsCert *x509.Certificate) (*CachedUser, *User, error) {
|
|
|
|
if !user.User.skipExternalAuth() && isExternalAuthConfigured(loginMethod) {
|
|
|
|
u, _, err := CheckCompositeCredentials(user.User.Username, password, ip, loginMethod, protocol, tlsCert)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
webDAVUsersCache.swap(&u, password)
|
|
|
|
cu, _ := webDAVUsersCache.get(u.Username)
|
|
|
|
return cu, &u, nil
|
|
|
|
}
|
2022-07-27 16:54:25 +00:00
|
|
|
if err := user.User.CheckLoginConditions(); err != nil {
|
2023-05-20 10:39:07 +00:00
|
|
|
return user, nil, err
|
2022-07-27 16:54:25 +00:00
|
|
|
}
|
|
|
|
if loginMethod == LoginMethodPassword && user.User.Filters.IsAnonymous {
|
2023-05-20 10:39:07 +00:00
|
|
|
return user, nil, nil
|
2022-07-27 16:54:25 +00:00
|
|
|
}
|
2021-03-01 18:28:11 +00:00
|
|
|
if loginMethod != LoginMethodPassword {
|
|
|
|
_, err := checkUserAndTLSCertificate(&user.User, protocol, tlsCert)
|
|
|
|
if err != nil {
|
2023-05-20 10:39:07 +00:00
|
|
|
return user, nil, err
|
2021-03-01 18:28:11 +00:00
|
|
|
}
|
|
|
|
if loginMethod == LoginMethodTLSCertificate {
|
2023-08-04 18:56:23 +00:00
|
|
|
if !user.User.IsLoginMethodAllowed(LoginMethodTLSCertificate, protocol) {
|
2023-05-20 10:39:07 +00:00
|
|
|
return user, nil, fmt.Errorf("certificate login method is not allowed for user %q", user.User.Username)
|
2021-03-01 18:28:11 +00:00
|
|
|
}
|
2023-05-20 10:39:07 +00:00
|
|
|
return user, nil, nil
|
2021-03-01 18:28:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
if password == "" {
|
2023-05-20 10:39:07 +00:00
|
|
|
return user, nil, ErrInvalidCredentials
|
2021-03-01 18:28:11 +00:00
|
|
|
}
|
|
|
|
if user.Password != "" {
|
|
|
|
if password == user.Password {
|
2023-05-20 10:39:07 +00:00
|
|
|
return user, nil, nil
|
2021-03-01 18:28:11 +00:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if ok, _ := isPasswordOK(&user.User, password); ok {
|
2023-05-20 10:39:07 +00:00
|
|
|
return user, nil, nil
|
2021-03-01 18:28:11 +00:00
|
|
|
}
|
|
|
|
}
|
2023-05-20 10:39:07 +00:00
|
|
|
return user, nil, ErrInvalidCredentials
|
2021-03-01 18:28:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// CheckCompositeCredentials checks multiple credentials.
|
|
|
|
// WebDAV users can send both a password and a TLS certificate within the same request
|
|
|
|
func CheckCompositeCredentials(username, password, ip, loginMethod, protocol string, tlsCert *x509.Certificate) (User, string, error) {
|
2022-01-31 17:01:37 +00:00
|
|
|
username = config.convertName(username)
|
2021-03-01 18:28:11 +00:00
|
|
|
if loginMethod == LoginMethodPassword {
|
|
|
|
user, err := CheckUserAndPass(username, password, ip, protocol)
|
|
|
|
return user, loginMethod, err
|
|
|
|
}
|
|
|
|
user, err := CheckUserBeforeTLSAuth(username, ip, protocol, tlsCert)
|
|
|
|
if err != nil {
|
|
|
|
return user, loginMethod, err
|
|
|
|
}
|
2024-01-14 20:36:23 +00:00
|
|
|
if !user.IsTLSVerificationEnabled() {
|
2021-03-01 18:28:11 +00:00
|
|
|
// for backward compatibility with 2.0.x we only check the password and change the login method here
|
|
|
|
// in future updates we have to return an error
|
|
|
|
user, err := CheckUserAndPass(username, password, ip, protocol)
|
|
|
|
return user, LoginMethodPassword, err
|
|
|
|
}
|
|
|
|
user, err = checkUserAndTLSCertificate(&user, protocol, tlsCert)
|
|
|
|
if err != nil {
|
|
|
|
return user, loginMethod, err
|
|
|
|
}
|
2023-08-04 18:56:23 +00:00
|
|
|
if loginMethod == LoginMethodTLSCertificate && !user.IsLoginMethodAllowed(LoginMethodTLSCertificate, protocol) {
|
2023-02-26 14:15:34 +00:00
|
|
|
return user, loginMethod, fmt.Errorf("certificate login method is not allowed for user %q", user.Username)
|
2021-03-01 18:28:11 +00:00
|
|
|
}
|
|
|
|
if loginMethod == LoginMethodTLSCertificateAndPwd {
|
2021-08-08 15:09:48 +00:00
|
|
|
if plugin.Handler.HasAuthScope(plugin.AuthScopePassword) {
|
|
|
|
user, err = doPluginAuth(username, password, nil, ip, protocol, nil, plugin.AuthScopePassword)
|
|
|
|
} else if config.ExternalAuthHook != "" && (config.ExternalAuthScope == 0 || config.ExternalAuthScope&1 != 0) {
|
2021-03-01 18:28:11 +00:00
|
|
|
user, err = doExternalAuth(username, password, nil, "", ip, protocol, nil)
|
2021-08-08 15:09:48 +00:00
|
|
|
} else if config.PreLoginHook != "" {
|
2022-04-12 17:31:25 +00:00
|
|
|
user, err = executePreLoginHook(username, LoginMethodPassword, ip, protocol, nil)
|
2021-08-08 15:09:48 +00:00
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return user, loginMethod, err
|
2021-03-01 18:28:11 +00:00
|
|
|
}
|
|
|
|
user, err = checkUserAndPass(&user, password, ip, protocol)
|
|
|
|
}
|
|
|
|
return user, loginMethod, err
|
|
|
|
}
|
|
|
|
|
2021-02-28 11:10:40 +00:00
|
|
|
// CheckUserBeforeTLSAuth checks if a user exits before trying mutual TLS
|
|
|
|
func CheckUserBeforeTLSAuth(username, ip, protocol string, tlsCert *x509.Certificate) (User, error) {
|
2022-01-31 17:01:37 +00:00
|
|
|
username = config.convertName(username)
|
2021-08-08 15:09:48 +00:00
|
|
|
if plugin.Handler.HasAuthScope(plugin.AuthScopeTLSCertificate) {
|
2022-04-25 13:49:11 +00:00
|
|
|
user, err := doPluginAuth(username, "", nil, ip, protocol, tlsCert, plugin.AuthScopeTLSCertificate)
|
|
|
|
if err != nil {
|
|
|
|
return user, err
|
|
|
|
}
|
|
|
|
err = user.LoadAndApplyGroupSettings()
|
|
|
|
return user, err
|
2021-08-08 15:09:48 +00:00
|
|
|
}
|
2021-02-28 11:10:40 +00:00
|
|
|
if config.ExternalAuthHook != "" && (config.ExternalAuthScope == 0 || config.ExternalAuthScope&8 != 0) {
|
2022-04-25 13:49:11 +00:00
|
|
|
user, err := doExternalAuth(username, "", nil, "", ip, protocol, tlsCert)
|
|
|
|
if err != nil {
|
|
|
|
return user, err
|
|
|
|
}
|
|
|
|
err = user.LoadAndApplyGroupSettings()
|
|
|
|
return user, err
|
2021-02-28 11:10:40 +00:00
|
|
|
}
|
|
|
|
if config.PreLoginHook != "" {
|
2022-04-25 13:49:11 +00:00
|
|
|
user, err := executePreLoginHook(username, LoginMethodTLSCertificate, ip, protocol, nil)
|
|
|
|
if err != nil {
|
|
|
|
return user, err
|
|
|
|
}
|
|
|
|
err = user.LoadAndApplyGroupSettings()
|
|
|
|
return user, err
|
2021-02-28 11:10:40 +00:00
|
|
|
}
|
2022-11-16 18:04:50 +00:00
|
|
|
user, err := UserExists(username, "")
|
2022-04-25 13:49:11 +00:00
|
|
|
if err != nil {
|
|
|
|
return user, err
|
|
|
|
}
|
|
|
|
err = user.LoadAndApplyGroupSettings()
|
|
|
|
return user, err
|
2021-02-28 11:10:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// CheckUserAndTLSCert returns the SFTPGo user with the given username and check if the
|
|
|
|
// given TLS certificate allow authentication without password
|
|
|
|
func CheckUserAndTLSCert(username, ip, protocol string, tlsCert *x509.Certificate) (User, error) {
|
2022-01-31 17:01:37 +00:00
|
|
|
username = config.convertName(username)
|
2021-08-08 15:09:48 +00:00
|
|
|
if plugin.Handler.HasAuthScope(plugin.AuthScopeTLSCertificate) {
|
|
|
|
user, err := doPluginAuth(username, "", nil, ip, protocol, tlsCert, plugin.AuthScopeTLSCertificate)
|
|
|
|
if err != nil {
|
|
|
|
return user, err
|
|
|
|
}
|
|
|
|
return checkUserAndTLSCertificate(&user, protocol, tlsCert)
|
|
|
|
}
|
2021-02-28 11:10:40 +00:00
|
|
|
if config.ExternalAuthHook != "" && (config.ExternalAuthScope == 0 || config.ExternalAuthScope&8 != 0) {
|
|
|
|
user, err := doExternalAuth(username, "", nil, "", ip, protocol, tlsCert)
|
|
|
|
if err != nil {
|
|
|
|
return user, err
|
|
|
|
}
|
|
|
|
return checkUserAndTLSCertificate(&user, protocol, tlsCert)
|
|
|
|
}
|
|
|
|
if config.PreLoginHook != "" {
|
2022-04-12 17:31:25 +00:00
|
|
|
user, err := executePreLoginHook(username, LoginMethodTLSCertificate, ip, protocol, nil)
|
2021-02-28 11:10:40 +00:00
|
|
|
if err != nil {
|
|
|
|
return user, err
|
|
|
|
}
|
|
|
|
return checkUserAndTLSCertificate(&user, protocol, tlsCert)
|
|
|
|
}
|
|
|
|
return provider.validateUserAndTLSCert(username, protocol, tlsCert)
|
|
|
|
}
|
|
|
|
|
|
|
|
// CheckUserAndPass retrieves the SFTPGo user with the given username and password if a match is found or an error
|
2020-08-12 14:15:12 +00:00
|
|
|
func CheckUserAndPass(username, password, ip, protocol string) (User, error) {
|
2022-01-31 17:01:37 +00:00
|
|
|
username = config.convertName(username)
|
2021-08-08 15:09:48 +00:00
|
|
|
if plugin.Handler.HasAuthScope(plugin.AuthScopePassword) {
|
|
|
|
user, err := doPluginAuth(username, password, nil, ip, protocol, nil, plugin.AuthScopePassword)
|
|
|
|
if err != nil {
|
|
|
|
return user, err
|
|
|
|
}
|
|
|
|
return checkUserAndPass(&user, password, ip, protocol)
|
|
|
|
}
|
2021-01-05 08:50:22 +00:00
|
|
|
if config.ExternalAuthHook != "" && (config.ExternalAuthScope == 0 || config.ExternalAuthScope&1 != 0) {
|
2021-02-28 11:10:40 +00:00
|
|
|
user, err := doExternalAuth(username, password, nil, "", ip, protocol, nil)
|
2020-01-06 20:42:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return user, err
|
|
|
|
}
|
2021-02-16 18:11:36 +00:00
|
|
|
return checkUserAndPass(&user, password, ip, protocol)
|
2020-01-06 20:42:41 +00:00
|
|
|
}
|
2021-01-05 08:50:22 +00:00
|
|
|
if config.PreLoginHook != "" {
|
2022-04-12 17:31:25 +00:00
|
|
|
user, err := executePreLoginHook(username, LoginMethodPassword, ip, protocol, nil)
|
2020-02-23 17:50:59 +00:00
|
|
|
if err != nil {
|
|
|
|
return user, err
|
|
|
|
}
|
2021-02-16 18:11:36 +00:00
|
|
|
return checkUserAndPass(&user, password, ip, protocol)
|
2020-02-23 17:50:59 +00:00
|
|
|
}
|
2020-08-19 17:36:12 +00:00
|
|
|
return provider.validateUserAndPass(username, password, ip, protocol)
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
2019-07-30 18:51:29 +00:00
|
|
|
// CheckUserAndPubKey retrieves the SFTP user with the given username and public key if a match is found or an error
|
2022-03-31 16:16:50 +00:00
|
|
|
func CheckUserAndPubKey(username string, pubKey []byte, ip, protocol string, isSSHCert bool) (User, string, error) {
|
2022-01-31 17:01:37 +00:00
|
|
|
username = config.convertName(username)
|
2021-08-08 15:09:48 +00:00
|
|
|
if plugin.Handler.HasAuthScope(plugin.AuthScopePublicKey) {
|
|
|
|
user, err := doPluginAuth(username, "", pubKey, ip, protocol, nil, plugin.AuthScopePublicKey)
|
|
|
|
if err != nil {
|
|
|
|
return user, "", err
|
|
|
|
}
|
2022-03-31 16:16:50 +00:00
|
|
|
return checkUserAndPubKey(&user, pubKey, isSSHCert)
|
2021-08-08 15:09:48 +00:00
|
|
|
}
|
2021-01-05 08:50:22 +00:00
|
|
|
if config.ExternalAuthHook != "" && (config.ExternalAuthScope == 0 || config.ExternalAuthScope&2 != 0) {
|
2021-02-28 11:10:40 +00:00
|
|
|
user, err := doExternalAuth(username, "", pubKey, "", ip, protocol, nil)
|
2020-01-06 20:42:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return user, "", err
|
|
|
|
}
|
2022-03-31 16:16:50 +00:00
|
|
|
return checkUserAndPubKey(&user, pubKey, isSSHCert)
|
2020-01-06 20:42:41 +00:00
|
|
|
}
|
2021-01-05 08:50:22 +00:00
|
|
|
if config.PreLoginHook != "" {
|
2022-04-12 17:31:25 +00:00
|
|
|
user, err := executePreLoginHook(username, SSHLoginMethodPublicKey, ip, protocol, nil)
|
2020-02-23 17:50:59 +00:00
|
|
|
if err != nil {
|
|
|
|
return user, "", err
|
|
|
|
}
|
2022-03-31 16:16:50 +00:00
|
|
|
return checkUserAndPubKey(&user, pubKey, isSSHCert)
|
2020-02-23 17:50:59 +00:00
|
|
|
}
|
2022-03-31 16:16:50 +00:00
|
|
|
return provider.validateUserAndPubKey(username, pubKey, isSSHCert)
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
2020-01-21 09:54:05 +00:00
|
|
|
// CheckKeyboardInteractiveAuth checks the keyboard interactive authentication and returns
|
|
|
|
// the authenticated user or an error
|
2024-02-05 18:02:01 +00:00
|
|
|
func CheckKeyboardInteractiveAuth(username, authHook string, client ssh.KeyboardInteractiveChallenge,
|
|
|
|
ip, protocol string, isPartialAuth bool,
|
|
|
|
) (User, error) {
|
2020-01-21 09:54:05 +00:00
|
|
|
var user User
|
|
|
|
var err error
|
2022-01-31 17:01:37 +00:00
|
|
|
username = config.convertName(username)
|
2021-08-08 15:09:48 +00:00
|
|
|
if plugin.Handler.HasAuthScope(plugin.AuthScopeKeyboardInteractive) {
|
|
|
|
user, err = doPluginAuth(username, "", nil, ip, protocol, nil, plugin.AuthScopeKeyboardInteractive)
|
|
|
|
} else if config.ExternalAuthHook != "" && (config.ExternalAuthScope == 0 || config.ExternalAuthScope&4 != 0) {
|
2021-02-28 11:10:40 +00:00
|
|
|
user, err = doExternalAuth(username, "", nil, "1", ip, protocol, nil)
|
2021-01-05 08:50:22 +00:00
|
|
|
} else if config.PreLoginHook != "" {
|
2022-04-12 17:31:25 +00:00
|
|
|
user, err = executePreLoginHook(username, SSHLoginMethodKeyboardInteractive, ip, protocol, nil)
|
2020-01-21 09:54:05 +00:00
|
|
|
} else {
|
2022-11-16 18:04:50 +00:00
|
|
|
user, err = provider.userExists(username, "")
|
2020-01-21 09:54:05 +00:00
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return user, err
|
|
|
|
}
|
2024-02-05 18:02:01 +00:00
|
|
|
return doKeyboardInteractiveAuth(&user, authHook, client, ip, protocol, isPartialAuth)
|
2020-01-21 09:54:05 +00:00
|
|
|
}
|
|
|
|
|
2022-07-26 16:51:39 +00:00
|
|
|
// GetFTPPreAuthUser returns the SFTPGo user with the specified username
|
|
|
|
// after receiving the FTP "USER" command.
|
|
|
|
// If a pre-login hook is defined it will be executed so the SFTPGo user
|
|
|
|
// can be created if it does not exist
|
|
|
|
func GetFTPPreAuthUser(username, ip string) (User, error) {
|
|
|
|
var user User
|
|
|
|
var err error
|
|
|
|
if config.PreLoginHook != "" {
|
|
|
|
user, err = executePreLoginHook(username, "", ip, protocolFTP, nil)
|
|
|
|
} else {
|
2022-11-16 18:04:50 +00:00
|
|
|
user, err = UserExists(username, "")
|
2022-07-26 16:51:39 +00:00
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return user, err
|
|
|
|
}
|
|
|
|
err = user.LoadAndApplyGroupSettings()
|
|
|
|
return user, err
|
|
|
|
}
|
|
|
|
|
2022-02-19 09:53:35 +00:00
|
|
|
// GetUserAfterIDPAuth returns the SFTPGo user with the specified username
|
|
|
|
// after a successful authentication with an external identity provider.
|
|
|
|
// If a pre-login hook is defined it will be executed so the SFTPGo user
|
|
|
|
// can be created if it does not exist
|
2022-05-19 17:49:51 +00:00
|
|
|
func GetUserAfterIDPAuth(username, ip, protocol string, oidcTokenFields *map[string]any) (User, error) {
|
2022-04-25 13:49:11 +00:00
|
|
|
var user User
|
|
|
|
var err error
|
2022-02-19 09:53:35 +00:00
|
|
|
if config.PreLoginHook != "" {
|
2022-04-25 13:49:11 +00:00
|
|
|
user, err = executePreLoginHook(username, LoginMethodIDP, ip, protocol, oidcTokenFields)
|
2022-12-11 16:15:34 +00:00
|
|
|
user.Filters.RequirePasswordChange = false
|
2022-04-25 13:49:11 +00:00
|
|
|
} else {
|
2022-11-16 18:04:50 +00:00
|
|
|
user, err = UserExists(username, "")
|
2022-04-25 13:49:11 +00:00
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return user, err
|
2022-02-19 09:53:35 +00:00
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
err = user.LoadAndApplyGroupSettings()
|
|
|
|
return user, err
|
2022-02-19 09:53:35 +00:00
|
|
|
}
|
|
|
|
|
2021-12-25 11:08:07 +00:00
|
|
|
// GetDefenderHosts returns hosts that are banned or for which some violations have been detected
|
2022-01-16 11:09:17 +00:00
|
|
|
func GetDefenderHosts(from int64, limit int) ([]DefenderEntry, error) {
|
2021-12-25 11:08:07 +00:00
|
|
|
return provider.getDefenderHosts(from, limit)
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetDefenderHostByIP returns a defender host by ip, if any
|
2022-01-16 11:09:17 +00:00
|
|
|
func GetDefenderHostByIP(ip string, from int64) (DefenderEntry, error) {
|
2021-12-25 11:08:07 +00:00
|
|
|
return provider.getDefenderHostByIP(ip, from)
|
|
|
|
}
|
|
|
|
|
|
|
|
// IsDefenderHostBanned returns a defender entry and no error if the specified host is banned
|
2022-01-16 11:09:17 +00:00
|
|
|
func IsDefenderHostBanned(ip string) (DefenderEntry, error) {
|
2021-12-25 11:08:07 +00:00
|
|
|
return provider.isDefenderHostBanned(ip)
|
|
|
|
}
|
|
|
|
|
|
|
|
// UpdateDefenderBanTime increments ban time for the specified ip
|
|
|
|
func UpdateDefenderBanTime(ip string, minutes int) error {
|
|
|
|
return provider.updateDefenderBanTime(ip, minutes)
|
|
|
|
}
|
|
|
|
|
|
|
|
// DeleteDefenderHost removes the specified IP from the defender lists
|
|
|
|
func DeleteDefenderHost(ip string) error {
|
|
|
|
return provider.deleteDefenderHost(ip)
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddDefenderEvent adds an event for the given IP with the given score
|
|
|
|
// and returns the host with the updated score
|
2022-01-16 11:09:17 +00:00
|
|
|
func AddDefenderEvent(ip string, score int, from int64) (DefenderEntry, error) {
|
2021-12-25 11:08:07 +00:00
|
|
|
if err := provider.addDefenderEvent(ip, score); err != nil {
|
2022-01-16 11:09:17 +00:00
|
|
|
return DefenderEntry{}, err
|
2021-12-25 11:08:07 +00:00
|
|
|
}
|
|
|
|
return provider.getDefenderHostByIP(ip, from)
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetDefenderBanTime sets the ban time for the specified IP
|
|
|
|
func SetDefenderBanTime(ip string, banTime int64) error {
|
|
|
|
return provider.setDefenderBanTime(ip, banTime)
|
|
|
|
}
|
|
|
|
|
|
|
|
// CleanupDefender removes events and hosts older than "from" from the data provider
|
|
|
|
func CleanupDefender(from int64) error {
|
|
|
|
return provider.cleanupDefender(from)
|
|
|
|
}
|
|
|
|
|
2021-11-06 13:13:20 +00:00
|
|
|
// UpdateShareLastUse updates the LastUseAt and UsedTokens for the given share
|
|
|
|
func UpdateShareLastUse(share *Share, numTokens int) error {
|
|
|
|
return provider.updateShareLastUse(share.ShareID, numTokens)
|
|
|
|
}
|
|
|
|
|
2021-08-17 16:08:32 +00:00
|
|
|
// UpdateAPIKeyLastUse updates the LastUseAt field for the given API key
|
|
|
|
func UpdateAPIKeyLastUse(apiKey *APIKey) error {
|
|
|
|
lastUse := util.GetTimeFromMsecSinceEpoch(apiKey.LastUseAt)
|
|
|
|
diff := -time.Until(lastUse)
|
|
|
|
if diff < 0 || diff > lastLoginMinDelay {
|
|
|
|
return provider.updateAPIKeyLastUse(apiKey.KeyID)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// UpdateLastLogin updates the last login field for the given SFTPGo user
|
2021-08-19 13:51:43 +00:00
|
|
|
func UpdateLastLogin(user *User) {
|
2022-02-25 10:51:10 +00:00
|
|
|
delay := lastLoginMinDelay
|
|
|
|
if user.Filters.ExternalAuthCacheTime > 0 {
|
|
|
|
delay = time.Duration(user.Filters.ExternalAuthCacheTime) * time.Second
|
|
|
|
}
|
2022-03-03 18:31:54 +00:00
|
|
|
if user.LastLogin <= user.UpdatedAt || !isLastActivityRecent(user.LastLogin, delay) {
|
2020-12-06 07:19:41 +00:00
|
|
|
err := provider.updateLastLogin(user.Username)
|
|
|
|
if err == nil {
|
2021-03-27 18:10:27 +00:00
|
|
|
webDAVUsersCache.updateLastLogin(user.Username)
|
2020-12-06 07:19:41 +00:00
|
|
|
}
|
2020-11-30 20:46:34 +00:00
|
|
|
}
|
2021-08-19 13:51:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// UpdateAdminLastLogin updates the last login field for the given SFTPGo admin
|
|
|
|
func UpdateAdminLastLogin(admin *Admin) {
|
2022-02-25 10:51:10 +00:00
|
|
|
if !isLastActivityRecent(admin.LastLogin, lastLoginMinDelay) {
|
2021-08-19 13:51:43 +00:00
|
|
|
provider.updateAdminLastLogin(admin.Username) //nolint:errcheck
|
|
|
|
}
|
2019-11-13 10:36:21 +00:00
|
|
|
}
|
|
|
|
|
2022-01-30 10:42:36 +00:00
|
|
|
// UpdateUserQuota updates the quota for the given SFTPGo user adding filesAdd and sizeAdd.
|
2019-07-30 18:51:29 +00:00
|
|
|
// If reset is true filesAdd and sizeAdd indicates the total files and the total size instead of the difference.
|
2021-02-16 18:11:36 +00:00
|
|
|
func UpdateUserQuota(user *User, filesAdd int, sizeAdd int64, reset bool) error {
|
2019-07-20 10:26:52 +00:00
|
|
|
if config.TrackQuota == 0 {
|
2021-07-11 13:26:51 +00:00
|
|
|
return util.NewMethodDisabledError(trackQuotaDisabledError)
|
2019-07-28 20:04:50 +00:00
|
|
|
} else if config.TrackQuota == 2 && !reset && !user.HasQuotaRestrictions() {
|
|
|
|
return nil
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
2020-08-31 17:25:17 +00:00
|
|
|
if filesAdd == 0 && sizeAdd == 0 && !reset {
|
|
|
|
return nil
|
|
|
|
}
|
2021-04-11 06:38:43 +00:00
|
|
|
if config.DelayedQuotaUpdate == 0 || reset {
|
|
|
|
if reset {
|
|
|
|
delayedQuotaUpdater.resetUserQuota(user.Username)
|
|
|
|
}
|
|
|
|
return provider.updateQuota(user.Username, filesAdd, sizeAdd, reset)
|
|
|
|
}
|
|
|
|
delayedQuotaUpdater.updateUserQuota(user.Username, filesAdd, sizeAdd)
|
|
|
|
return nil
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
2024-07-13 17:30:40 +00:00
|
|
|
// UpdateUserFolderQuota updates the quota for the given user and virtual folder.
|
|
|
|
func UpdateUserFolderQuota(folder *vfs.VirtualFolder, user *User, filesAdd int, sizeAdd int64, reset bool) {
|
|
|
|
if folder.IsIncludedInUserQuota() {
|
|
|
|
UpdateUserQuota(user, filesAdd, sizeAdd, reset) //nolint:errcheck
|
2024-07-13 19:02:40 +00:00
|
|
|
return
|
2024-07-13 17:30:40 +00:00
|
|
|
}
|
2024-07-13 19:02:40 +00:00
|
|
|
UpdateVirtualFolderQuota(&folder.BaseVirtualFolder, filesAdd, sizeAdd, reset) //nolint:errcheck
|
2024-07-13 17:30:40 +00:00
|
|
|
}
|
|
|
|
|
2020-06-07 21:30:18 +00:00
|
|
|
// UpdateVirtualFolderQuota updates the quota for the given virtual folder adding filesAdd and sizeAdd.
|
|
|
|
// If reset is true filesAdd and sizeAdd indicates the total files and the total size instead of the difference.
|
2021-02-16 18:11:36 +00:00
|
|
|
func UpdateVirtualFolderQuota(vfolder *vfs.BaseVirtualFolder, filesAdd int, sizeAdd int64, reset bool) error {
|
2020-06-07 21:30:18 +00:00
|
|
|
if config.TrackQuota == 0 {
|
2021-07-11 13:26:51 +00:00
|
|
|
return util.NewMethodDisabledError(trackQuotaDisabledError)
|
2020-06-07 21:30:18 +00:00
|
|
|
}
|
2020-08-31 17:25:17 +00:00
|
|
|
if filesAdd == 0 && sizeAdd == 0 && !reset {
|
|
|
|
return nil
|
|
|
|
}
|
2021-04-11 06:38:43 +00:00
|
|
|
if config.DelayedQuotaUpdate == 0 || reset {
|
|
|
|
if reset {
|
|
|
|
delayedQuotaUpdater.resetFolderQuota(vfolder.Name)
|
|
|
|
}
|
|
|
|
return provider.updateFolderQuota(vfolder.Name, filesAdd, sizeAdd, reset)
|
|
|
|
}
|
|
|
|
delayedQuotaUpdater.updateFolderQuota(vfolder.Name, filesAdd, sizeAdd)
|
|
|
|
return nil
|
2020-06-07 21:30:18 +00:00
|
|
|
}
|
|
|
|
|
2022-01-30 10:42:36 +00:00
|
|
|
// UpdateUserTransferQuota updates the transfer quota for the given SFTPGo user.
|
|
|
|
// If reset is true uploadSize and downloadSize indicates the actual sizes instead of the difference.
|
|
|
|
func UpdateUserTransferQuota(user *User, uploadSize, downloadSize int64, reset bool) error {
|
2019-07-20 10:26:52 +00:00
|
|
|
if config.TrackQuota == 0 {
|
2022-01-30 10:42:36 +00:00
|
|
|
return util.NewMethodDisabledError(trackQuotaDisabledError)
|
|
|
|
} else if config.TrackQuota == 2 && !reset && !user.HasTransferQuotaRestrictions() {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if downloadSize == 0 && uploadSize == 0 && !reset {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if config.DelayedQuotaUpdate == 0 || reset {
|
|
|
|
if reset {
|
|
|
|
delayedQuotaUpdater.resetUserTransferQuota(user.Username)
|
|
|
|
}
|
|
|
|
return provider.updateTransferQuota(user.Username, uploadSize, downloadSize, reset)
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
2022-01-30 10:42:36 +00:00
|
|
|
delayedQuotaUpdater.updateUserTransferQuota(user.Username, uploadSize, downloadSize)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-08-21 17:01:08 +00:00
|
|
|
// UpdateUserTransferTimestamps updates the first download/upload fields if unset
|
|
|
|
func UpdateUserTransferTimestamps(username string, isUpload bool) error {
|
|
|
|
if isUpload {
|
|
|
|
err := provider.setFirstUploadTimestamp(username)
|
|
|
|
if err != nil {
|
|
|
|
providerLog(logger.LevelWarn, "unable to set first upload: %v", err)
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
err := provider.setFirstDownloadTimestamp(username)
|
|
|
|
if err != nil {
|
|
|
|
providerLog(logger.LevelWarn, "unable to set first download: %v", err)
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-01-30 10:42:36 +00:00
|
|
|
// GetUsedQuota returns the used quota for the given SFTPGo user.
|
|
|
|
func GetUsedQuota(username string) (int, int64, int64, int64, error) {
|
|
|
|
if config.TrackQuota == 0 {
|
|
|
|
return 0, 0, 0, 0, util.NewMethodDisabledError(trackQuotaDisabledError)
|
|
|
|
}
|
|
|
|
files, size, ulTransferSize, dlTransferSize, err := provider.getUsedQuota(username)
|
2021-04-11 06:38:43 +00:00
|
|
|
if err != nil {
|
2022-01-30 10:42:36 +00:00
|
|
|
return files, size, ulTransferSize, dlTransferSize, err
|
2021-04-11 06:38:43 +00:00
|
|
|
}
|
|
|
|
delayedFiles, delayedSize := delayedQuotaUpdater.getUserPendingQuota(username)
|
2022-01-30 10:42:36 +00:00
|
|
|
delayedUlTransferSize, delayedDLTransferSize := delayedQuotaUpdater.getUserPendingTransferQuota(username)
|
|
|
|
|
|
|
|
return files + delayedFiles, size + delayedSize, ulTransferSize + delayedUlTransferSize,
|
|
|
|
dlTransferSize + delayedDLTransferSize, err
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
2020-06-07 21:30:18 +00:00
|
|
|
// GetUsedVirtualFolderQuota returns the used quota for the given virtual folder.
|
2021-02-01 18:04:15 +00:00
|
|
|
func GetUsedVirtualFolderQuota(name string) (int, int64, error) {
|
2020-06-07 21:30:18 +00:00
|
|
|
if config.TrackQuota == 0 {
|
2021-07-11 13:26:51 +00:00
|
|
|
return 0, 0, util.NewMethodDisabledError(trackQuotaDisabledError)
|
2020-06-07 21:30:18 +00:00
|
|
|
}
|
2021-04-11 06:38:43 +00:00
|
|
|
files, size, err := provider.getUsedFolderQuota(name)
|
|
|
|
if err != nil {
|
|
|
|
return files, size, err
|
|
|
|
}
|
|
|
|
delayedFiles, delayedSize := delayedQuotaUpdater.getFolderPendingQuota(name)
|
|
|
|
return files + delayedFiles, size + delayedSize, err
|
2020-06-07 21:30:18 +00:00
|
|
|
}
|
|
|
|
|
2023-02-19 18:03:45 +00:00
|
|
|
// GetConfigs returns the configurations
|
|
|
|
func GetConfigs() (Configs, error) {
|
|
|
|
return provider.getConfigs()
|
|
|
|
}
|
|
|
|
|
|
|
|
// UpdateConfigs updates configurations
|
|
|
|
func UpdateConfigs(configs *Configs, executor, ipAddress, role string) error {
|
|
|
|
if configs == nil {
|
|
|
|
configs = &Configs{}
|
|
|
|
} else {
|
|
|
|
configs.UpdatedAt = util.GetTimeAsMsSinceEpoch(time.Now())
|
|
|
|
}
|
|
|
|
err := provider.setConfigs(configs)
|
|
|
|
if err == nil {
|
|
|
|
executeAction(operationUpdate, executor, ipAddress, actionObjectConfigs, "configs", role, configs)
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-11-06 13:13:20 +00:00
|
|
|
// AddShare adds a new share
|
2022-12-03 10:45:27 +00:00
|
|
|
func AddShare(share *Share, executor, ipAddress, role string) error {
|
2021-11-06 13:13:20 +00:00
|
|
|
err := provider.addShare(share)
|
|
|
|
if err == nil {
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationAdd, executor, ipAddress, actionObjectShare, share.ShareID, role, share)
|
2021-11-06 13:13:20 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// UpdateShare updates an existing share
|
2022-12-03 10:45:27 +00:00
|
|
|
func UpdateShare(share *Share, executor, ipAddress, role string) error {
|
2021-11-06 13:13:20 +00:00
|
|
|
err := provider.updateShare(share)
|
|
|
|
if err == nil {
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationUpdate, executor, ipAddress, actionObjectShare, share.ShareID, role, share)
|
2021-11-06 13:13:20 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// DeleteShare deletes an existing share
|
2022-12-03 10:45:27 +00:00
|
|
|
func DeleteShare(shareID string, executor, ipAddress, role string) error {
|
2021-11-06 13:13:20 +00:00
|
|
|
share, err := provider.shareExists(shareID, executor)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
err = provider.deleteShare(share)
|
2021-11-06 13:13:20 +00:00
|
|
|
if err == nil {
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationDelete, executor, ipAddress, actionObjectShare, shareID, role, &share)
|
2021-11-06 13:13:20 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// ShareExists returns the share with the given ID if it exists
|
|
|
|
func ShareExists(shareID, username string) (Share, error) {
|
|
|
|
if shareID == "" {
|
2023-02-26 14:15:34 +00:00
|
|
|
return Share{}, util.NewRecordNotFoundError(fmt.Sprintf("Share %q does not exist", shareID))
|
2021-11-06 13:13:20 +00:00
|
|
|
}
|
|
|
|
return provider.shareExists(shareID, username)
|
|
|
|
}
|
|
|
|
|
2023-02-09 08:33:33 +00:00
|
|
|
// AddIPListEntry adds a new IP list entry
|
|
|
|
func AddIPListEntry(entry *IPListEntry, executor, ipAddress, executorRole string) error {
|
|
|
|
err := provider.addIPListEntry(entry)
|
|
|
|
if err == nil {
|
|
|
|
executeAction(operationAdd, executor, ipAddress, actionObjectIPListEntry, entry.getName(), executorRole, entry)
|
|
|
|
for _, l := range inMemoryLists {
|
|
|
|
l.addEntry(entry)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// UpdateIPListEntry updates an existing IP list entry
|
|
|
|
func UpdateIPListEntry(entry *IPListEntry, executor, ipAddress, executorRole string) error {
|
|
|
|
err := provider.updateIPListEntry(entry)
|
|
|
|
if err == nil {
|
|
|
|
executeAction(operationUpdate, executor, ipAddress, actionObjectIPListEntry, entry.getName(), executorRole, entry)
|
|
|
|
for _, l := range inMemoryLists {
|
|
|
|
l.updateEntry(entry)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// DeleteIPListEntry deletes an existing IP list entry
|
|
|
|
func DeleteIPListEntry(ipOrNet string, listType IPListType, executor, ipAddress, executorRole string) error {
|
|
|
|
entry, err := provider.ipListEntryExists(ipOrNet, listType)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
err = provider.deleteIPListEntry(entry, config.IsShared == 1)
|
|
|
|
if err == nil {
|
|
|
|
executeAction(operationDelete, executor, ipAddress, actionObjectIPListEntry, entry.getName(), executorRole, &entry)
|
|
|
|
for _, l := range inMemoryLists {
|
|
|
|
l.removeEntry(&entry)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// IPListEntryExists returns the IP list entry with the given IP/net and type if it exists
|
|
|
|
func IPListEntryExists(ipOrNet string, listType IPListType) (IPListEntry, error) {
|
|
|
|
return provider.ipListEntryExists(ipOrNet, listType)
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetIPListEntries returns the IP list entries applying the specified criteria and search limit
|
|
|
|
func GetIPListEntries(listType IPListType, filter, from, order string, limit int) ([]IPListEntry, error) {
|
2024-07-24 16:27:13 +00:00
|
|
|
if !slices.Contains(supportedIPListType, listType) {
|
2023-02-09 08:33:33 +00:00
|
|
|
return nil, util.NewValidationError(fmt.Sprintf("invalid list type %d", listType))
|
|
|
|
}
|
|
|
|
return provider.getIPListEntries(listType, filter, from, order, limit)
|
|
|
|
}
|
|
|
|
|
2022-11-16 18:04:50 +00:00
|
|
|
// AddRole adds a new role
|
2022-12-03 10:45:27 +00:00
|
|
|
func AddRole(role *Role, executor, ipAddress, executorRole string) error {
|
2022-11-16 18:04:50 +00:00
|
|
|
role.Name = config.convertName(role.Name)
|
|
|
|
err := provider.addRole(role)
|
|
|
|
if err == nil {
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationAdd, executor, ipAddress, actionObjectRole, role.Name, executorRole, role)
|
2022-11-16 18:04:50 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// UpdateRole updates an existing Role
|
2022-12-03 10:45:27 +00:00
|
|
|
func UpdateRole(role *Role, executor, ipAddress, executorRole string) error {
|
2022-11-16 18:04:50 +00:00
|
|
|
err := provider.updateRole(role)
|
|
|
|
if err == nil {
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationUpdate, executor, ipAddress, actionObjectRole, role.Name, executorRole, role)
|
2022-11-16 18:04:50 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// DeleteRole deletes an existing Role
|
2022-12-03 10:45:27 +00:00
|
|
|
func DeleteRole(name string, executor, ipAddress, executorRole string) error {
|
2022-11-16 18:04:50 +00:00
|
|
|
name = config.convertName(name)
|
|
|
|
role, err := provider.roleExists(name)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if len(role.Admins) > 0 {
|
|
|
|
errorString := fmt.Sprintf("the role %q is referenced, it cannot be removed", role.Name)
|
|
|
|
return util.NewValidationError(errorString)
|
|
|
|
}
|
|
|
|
err = provider.deleteRole(role)
|
|
|
|
if err == nil {
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationDelete, executor, ipAddress, actionObjectRole, role.Name, executorRole, &role)
|
2022-11-16 18:04:50 +00:00
|
|
|
for _, user := range role.Users {
|
|
|
|
provider.setUpdatedAt(user)
|
|
|
|
u, err := provider.userExists(user, "")
|
|
|
|
if err == nil {
|
2023-05-20 10:39:07 +00:00
|
|
|
webDAVUsersCache.swap(&u, "")
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationUpdate, executor, ipAddress, actionObjectUser, u.Username, u.Role, &u)
|
2022-11-16 18:04:50 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// RoleExists returns the Role with the given name if it exists
|
|
|
|
func RoleExists(name string) (Role, error) {
|
|
|
|
name = config.convertName(name)
|
|
|
|
return provider.roleExists(name)
|
|
|
|
}
|
|
|
|
|
2022-04-25 13:49:11 +00:00
|
|
|
// AddGroup adds a new group
|
2022-12-03 10:45:27 +00:00
|
|
|
func AddGroup(group *Group, executor, ipAddress, role string) error {
|
2022-04-25 13:49:11 +00:00
|
|
|
group.Name = config.convertName(group.Name)
|
|
|
|
err := provider.addGroup(group)
|
|
|
|
if err == nil {
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationAdd, executor, ipAddress, actionObjectGroup, group.Name, role, group)
|
2022-04-25 13:49:11 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// UpdateGroup updates an existing Group
|
2022-12-03 10:45:27 +00:00
|
|
|
func UpdateGroup(group *Group, users []string, executor, ipAddress, role string) error {
|
2022-04-25 13:49:11 +00:00
|
|
|
err := provider.updateGroup(group)
|
|
|
|
if err == nil {
|
|
|
|
for _, user := range users {
|
|
|
|
provider.setUpdatedAt(user)
|
2022-11-16 18:04:50 +00:00
|
|
|
u, err := provider.userExists(user, "")
|
2022-04-25 13:49:11 +00:00
|
|
|
if err == nil {
|
2023-05-20 10:39:07 +00:00
|
|
|
webDAVUsersCache.swap(&u, "")
|
2022-04-25 13:49:11 +00:00
|
|
|
} else {
|
|
|
|
RemoveCachedWebDAVUser(user)
|
|
|
|
}
|
|
|
|
}
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationUpdate, executor, ipAddress, actionObjectGroup, group.Name, role, group)
|
2022-04-25 13:49:11 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// DeleteGroup deletes an existing Group
|
2022-12-03 10:45:27 +00:00
|
|
|
func DeleteGroup(name string, executor, ipAddress, role string) error {
|
2022-04-25 13:49:11 +00:00
|
|
|
name = config.convertName(name)
|
|
|
|
group, err := provider.groupExists(name)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if len(group.Users) > 0 {
|
2022-11-16 18:04:50 +00:00
|
|
|
errorString := fmt.Sprintf("the group %q is referenced, it cannot be removed", group.Name)
|
2022-04-25 13:49:11 +00:00
|
|
|
return util.NewValidationError(errorString)
|
|
|
|
}
|
|
|
|
err = provider.deleteGroup(group)
|
|
|
|
if err == nil {
|
|
|
|
for _, user := range group.Users {
|
|
|
|
provider.setUpdatedAt(user)
|
2022-11-16 18:04:50 +00:00
|
|
|
u, err := provider.userExists(user, "")
|
2022-04-25 13:49:11 +00:00
|
|
|
if err == nil {
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationUpdate, executor, ipAddress, actionObjectUser, u.Username, u.Role, &u)
|
2022-04-25 13:49:11 +00:00
|
|
|
}
|
|
|
|
RemoveCachedWebDAVUser(user)
|
|
|
|
}
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationDelete, executor, ipAddress, actionObjectGroup, group.Name, role, &group)
|
2022-04-25 13:49:11 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// GroupExists returns the Group with the given name if it exists
|
|
|
|
func GroupExists(name string) (Group, error) {
|
|
|
|
name = config.convertName(name)
|
|
|
|
return provider.groupExists(name)
|
|
|
|
}
|
|
|
|
|
2021-08-17 16:08:32 +00:00
|
|
|
// AddAPIKey adds a new API key
|
2022-12-03 10:45:27 +00:00
|
|
|
func AddAPIKey(apiKey *APIKey, executor, ipAddress, role string) error {
|
2021-10-10 11:08:05 +00:00
|
|
|
err := provider.addAPIKey(apiKey)
|
|
|
|
if err == nil {
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationAdd, executor, ipAddress, actionObjectAPIKey, apiKey.KeyID, role, apiKey)
|
2021-10-10 11:08:05 +00:00
|
|
|
}
|
|
|
|
return err
|
2021-08-17 16:08:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// UpdateAPIKey updates an existing API key
|
2022-12-03 10:45:27 +00:00
|
|
|
func UpdateAPIKey(apiKey *APIKey, executor, ipAddress, role string) error {
|
2021-10-10 11:08:05 +00:00
|
|
|
err := provider.updateAPIKey(apiKey)
|
|
|
|
if err == nil {
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationUpdate, executor, ipAddress, actionObjectAPIKey, apiKey.KeyID, role, apiKey)
|
2021-10-10 11:08:05 +00:00
|
|
|
}
|
|
|
|
return err
|
2021-08-17 16:08:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// DeleteAPIKey deletes an existing API key
|
2022-12-03 10:45:27 +00:00
|
|
|
func DeleteAPIKey(keyID string, executor, ipAddress, role string) error {
|
2021-08-17 16:08:32 +00:00
|
|
|
apiKey, err := provider.apiKeyExists(keyID)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
err = provider.deleteAPIKey(apiKey)
|
2021-10-10 11:08:05 +00:00
|
|
|
if err == nil {
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationDelete, executor, ipAddress, actionObjectAPIKey, apiKey.KeyID, role, &apiKey)
|
2023-04-13 16:23:42 +00:00
|
|
|
cachedAPIKeys.Remove(keyID)
|
2021-10-10 11:08:05 +00:00
|
|
|
}
|
|
|
|
return err
|
2021-08-17 16:08:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// APIKeyExists returns the API key with the given ID if it exists
|
|
|
|
func APIKeyExists(keyID string) (APIKey, error) {
|
|
|
|
if keyID == "" {
|
2023-02-26 14:15:34 +00:00
|
|
|
return APIKey{}, util.NewRecordNotFoundError(fmt.Sprintf("API key %q does not exist", keyID))
|
2021-08-17 16:08:32 +00:00
|
|
|
}
|
|
|
|
return provider.apiKeyExists(keyID)
|
|
|
|
}
|
|
|
|
|
2022-07-11 06:17:36 +00:00
|
|
|
// GetEventActions returns an array of event actions respecting limit and offset
|
|
|
|
func GetEventActions(limit, offset int, order string, minimal bool) ([]BaseEventAction, error) {
|
|
|
|
return provider.getEventActions(limit, offset, order, minimal)
|
|
|
|
}
|
|
|
|
|
|
|
|
// EventActionExists returns the event action with the given name if it exists
|
|
|
|
func EventActionExists(name string) (BaseEventAction, error) {
|
|
|
|
name = config.convertName(name)
|
|
|
|
return provider.eventActionExists(name)
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddEventAction adds a new event action
|
2022-12-03 10:45:27 +00:00
|
|
|
func AddEventAction(action *BaseEventAction, executor, ipAddress, role string) error {
|
2022-07-11 06:17:36 +00:00
|
|
|
action.Name = config.convertName(action.Name)
|
|
|
|
err := provider.addEventAction(action)
|
|
|
|
if err == nil {
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationAdd, executor, ipAddress, actionObjectEventAction, action.Name, role, action)
|
2022-07-11 06:17:36 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// UpdateEventAction updates an existing event action
|
2022-12-03 10:45:27 +00:00
|
|
|
func UpdateEventAction(action *BaseEventAction, executor, ipAddress, role string) error {
|
2022-07-11 06:17:36 +00:00
|
|
|
err := provider.updateEventAction(action)
|
|
|
|
if err == nil {
|
2022-08-01 16:48:54 +00:00
|
|
|
if fnReloadRules != nil {
|
|
|
|
fnReloadRules()
|
|
|
|
}
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationUpdate, executor, ipAddress, actionObjectEventAction, action.Name, role, action)
|
2022-07-11 06:17:36 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// DeleteEventAction deletes an existing event action
|
2022-12-03 10:45:27 +00:00
|
|
|
func DeleteEventAction(name string, executor, ipAddress, role string) error {
|
2022-07-11 06:17:36 +00:00
|
|
|
name = config.convertName(name)
|
|
|
|
action, err := provider.eventActionExists(name)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if len(action.Rules) > 0 {
|
|
|
|
errorString := fmt.Sprintf("the event action %#q is referenced, it cannot be removed", action.Name)
|
|
|
|
return util.NewValidationError(errorString)
|
|
|
|
}
|
|
|
|
err = provider.deleteEventAction(action)
|
|
|
|
if err == nil {
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationDelete, executor, ipAddress, actionObjectEventAction, action.Name, role, &action)
|
2022-07-11 06:17:36 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetEventRules returns an array of event rules respecting limit and offset
|
|
|
|
func GetEventRules(limit, offset int, order string) ([]EventRule, error) {
|
|
|
|
return provider.getEventRules(limit, offset, order)
|
|
|
|
}
|
|
|
|
|
2022-08-01 16:48:54 +00:00
|
|
|
// GetRecentlyUpdatedRules returns the event rules updated after the specified time
|
|
|
|
func GetRecentlyUpdatedRules(after int64) ([]EventRule, error) {
|
|
|
|
return provider.getRecentlyUpdatedRules(after)
|
|
|
|
}
|
|
|
|
|
2022-07-11 06:17:36 +00:00
|
|
|
// EventRuleExists returns the event rule with the given name if it exists
|
|
|
|
func EventRuleExists(name string) (EventRule, error) {
|
|
|
|
name = config.convertName(name)
|
|
|
|
return provider.eventRuleExists(name)
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddEventRule adds a new event rule
|
2022-12-03 10:45:27 +00:00
|
|
|
func AddEventRule(rule *EventRule, executor, ipAddress, role string) error {
|
2022-07-11 06:17:36 +00:00
|
|
|
rule.Name = config.convertName(rule.Name)
|
|
|
|
err := provider.addEventRule(rule)
|
|
|
|
if err == nil {
|
2022-08-01 16:48:54 +00:00
|
|
|
if fnReloadRules != nil {
|
|
|
|
fnReloadRules()
|
|
|
|
}
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationAdd, executor, ipAddress, actionObjectEventRule, rule.Name, role, rule)
|
2022-07-11 06:17:36 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// UpdateEventRule updates an existing event rule
|
2022-12-03 10:45:27 +00:00
|
|
|
func UpdateEventRule(rule *EventRule, executor, ipAddress, role string) error {
|
2022-07-11 06:17:36 +00:00
|
|
|
err := provider.updateEventRule(rule)
|
|
|
|
if err == nil {
|
2022-08-01 16:48:54 +00:00
|
|
|
if fnReloadRules != nil {
|
|
|
|
fnReloadRules()
|
|
|
|
}
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationUpdate, executor, ipAddress, actionObjectEventRule, rule.Name, role, rule)
|
2022-07-11 06:17:36 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// DeleteEventRule deletes an existing event rule
|
2022-12-03 10:45:27 +00:00
|
|
|
func DeleteEventRule(name string, executor, ipAddress, role string) error {
|
2022-07-11 06:17:36 +00:00
|
|
|
name = config.convertName(name)
|
|
|
|
rule, err := provider.eventRuleExists(name)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-07-17 16:48:41 +00:00
|
|
|
err = provider.deleteEventRule(rule, config.IsShared == 1)
|
2022-07-11 06:17:36 +00:00
|
|
|
if err == nil {
|
2022-08-01 16:48:54 +00:00
|
|
|
if fnRemoveRule != nil {
|
|
|
|
fnRemoveRule(rule.Name)
|
|
|
|
}
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationDelete, executor, ipAddress, actionObjectEventRule, rule.Name, role, &rule)
|
2022-07-11 06:17:36 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-08-01 16:48:54 +00:00
|
|
|
// RemoveEventRule delets an existing event rule without marking it as deleted
|
|
|
|
func RemoveEventRule(rule EventRule) error {
|
|
|
|
return provider.deleteEventRule(rule, false)
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetTaskByName returns the task with the specified name
|
|
|
|
func GetTaskByName(name string) (Task, error) {
|
|
|
|
return provider.getTaskByName(name)
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddTask add a task with the specified name
|
|
|
|
func AddTask(name string) error {
|
|
|
|
return provider.addTask(name)
|
|
|
|
}
|
|
|
|
|
|
|
|
// UpdateTask updates the task with the specified name and version
|
|
|
|
func UpdateTask(name string, version int64) error {
|
|
|
|
return provider.updateTask(name, version)
|
|
|
|
}
|
|
|
|
|
|
|
|
// UpdateTaskTimestamp updates the timestamp for the task with the specified name
|
|
|
|
func UpdateTaskTimestamp(name string) error {
|
|
|
|
return provider.updateTaskTimestamp(name)
|
|
|
|
}
|
|
|
|
|
2022-09-25 17:48:55 +00:00
|
|
|
// GetNodes returns the other cluster nodes
|
|
|
|
func GetNodes() ([]Node, error) {
|
|
|
|
if currentNode == nil {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
nodes, err := provider.getNodes()
|
|
|
|
if err != nil {
|
|
|
|
providerLog(logger.LevelError, "unable to get other cluster nodes %v", err)
|
|
|
|
}
|
|
|
|
return nodes, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetNodeByName returns a node, different from the current one, by name
|
|
|
|
func GetNodeByName(name string) (Node, error) {
|
|
|
|
if currentNode == nil {
|
|
|
|
return Node{}, util.NewRecordNotFoundError(errNoClusterNodes.Error())
|
|
|
|
}
|
|
|
|
if name == currentNode.Name {
|
|
|
|
return Node{}, util.NewValidationError(fmt.Sprintf("%s is the current node, it must refer to other nodes", name))
|
|
|
|
}
|
|
|
|
return provider.getNodeByName(name)
|
|
|
|
}
|
|
|
|
|
2021-05-14 17:21:15 +00:00
|
|
|
// HasAdmin returns true if the first admin has been created
|
|
|
|
// and so SFTPGo is ready to be used
|
|
|
|
func HasAdmin() bool {
|
2022-08-30 13:47:41 +00:00
|
|
|
return isAdminCreated.Load()
|
2021-05-14 17:21:15 +00:00
|
|
|
}
|
|
|
|
|
2021-01-17 21:29:08 +00:00
|
|
|
// AddAdmin adds a new SFTPGo admin
|
2022-12-03 10:45:27 +00:00
|
|
|
func AddAdmin(admin *Admin, executor, ipAddress, role string) error {
|
2021-09-04 10:11:04 +00:00
|
|
|
admin.Filters.RecoveryCodes = nil
|
2022-01-06 09:11:47 +00:00
|
|
|
admin.Filters.TOTPConfig = AdminTOTPConfig{
|
2021-09-04 10:11:04 +00:00
|
|
|
Enabled: false,
|
|
|
|
}
|
2022-01-31 17:01:37 +00:00
|
|
|
admin.Username = config.convertName(admin.Username)
|
2021-05-14 17:21:15 +00:00
|
|
|
err := provider.addAdmin(admin)
|
|
|
|
if err == nil {
|
2022-08-30 13:47:41 +00:00
|
|
|
isAdminCreated.Store(true)
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationAdd, executor, ipAddress, actionObjectAdmin, admin.Username, role, admin)
|
2021-05-14 17:21:15 +00:00
|
|
|
}
|
|
|
|
return err
|
2021-01-17 21:29:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// UpdateAdmin updates an existing SFTPGo admin
|
2022-12-03 10:45:27 +00:00
|
|
|
func UpdateAdmin(admin *Admin, executor, ipAddress, role string) error {
|
2021-10-10 11:08:05 +00:00
|
|
|
err := provider.updateAdmin(admin)
|
|
|
|
if err == nil {
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationUpdate, executor, ipAddress, actionObjectAdmin, admin.Username, role, admin)
|
2021-10-10 11:08:05 +00:00
|
|
|
}
|
|
|
|
return err
|
2021-01-17 21:29:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// DeleteAdmin deletes an existing SFTPGo admin
|
2022-12-03 10:45:27 +00:00
|
|
|
func DeleteAdmin(username, executor, ipAddress, role string) error {
|
2022-01-31 17:01:37 +00:00
|
|
|
username = config.convertName(username)
|
2021-01-17 21:29:08 +00:00
|
|
|
admin, err := provider.adminExists(username)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
err = provider.deleteAdmin(admin)
|
2021-10-10 11:08:05 +00:00
|
|
|
if err == nil {
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationDelete, executor, ipAddress, actionObjectAdmin, admin.Username, role, &admin)
|
2023-04-13 16:23:42 +00:00
|
|
|
cachedAdminPasswords.Remove(username)
|
2021-10-10 11:08:05 +00:00
|
|
|
}
|
|
|
|
return err
|
2021-01-17 21:29:08 +00:00
|
|
|
}
|
|
|
|
|
2021-08-17 16:08:32 +00:00
|
|
|
// AdminExists returns the admin with the given username if it exists
|
2021-01-17 21:29:08 +00:00
|
|
|
func AdminExists(username string) (Admin, error) {
|
2022-01-31 17:01:37 +00:00
|
|
|
username = config.convertName(username)
|
2021-01-17 21:29:08 +00:00
|
|
|
return provider.adminExists(username)
|
|
|
|
}
|
|
|
|
|
|
|
|
// UserExists checks if the given SFTPGo username exists, returns an error if no match is found
|
2022-11-16 18:04:50 +00:00
|
|
|
func UserExists(username, role string) (User, error) {
|
2022-01-31 17:01:37 +00:00
|
|
|
username = config.convertName(username)
|
2022-11-16 18:04:50 +00:00
|
|
|
return provider.userExists(username, role)
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
2022-04-25 13:49:11 +00:00
|
|
|
// GetUserWithGroupSettings tries to return the user with the specified username
|
|
|
|
// loading also the group settings
|
2022-11-16 18:04:50 +00:00
|
|
|
func GetUserWithGroupSettings(username, role string) (User, error) {
|
2022-04-25 13:49:11 +00:00
|
|
|
username = config.convertName(username)
|
2022-11-16 18:04:50 +00:00
|
|
|
user, err := provider.userExists(username, role)
|
2022-04-25 13:49:11 +00:00
|
|
|
if err != nil {
|
|
|
|
return user, err
|
|
|
|
}
|
|
|
|
err = user.LoadAndApplyGroupSettings()
|
|
|
|
return user, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetUserVariants tries to return the user with the specified username with and without
|
|
|
|
// group settings applied
|
2022-11-16 18:04:50 +00:00
|
|
|
func GetUserVariants(username, role string) (User, User, error) {
|
2022-04-25 13:49:11 +00:00
|
|
|
username = config.convertName(username)
|
2022-11-16 18:04:50 +00:00
|
|
|
user, err := provider.userExists(username, role)
|
2022-04-25 13:49:11 +00:00
|
|
|
if err != nil {
|
|
|
|
return user, User{}, err
|
|
|
|
}
|
|
|
|
userWithGroupSettings := user.getACopy()
|
|
|
|
err = userWithGroupSettings.LoadAndApplyGroupSettings()
|
|
|
|
return user, userWithGroupSettings, err
|
|
|
|
}
|
|
|
|
|
2020-08-31 17:25:17 +00:00
|
|
|
// AddUser adds a new SFTPGo user.
|
2022-12-03 10:45:27 +00:00
|
|
|
func AddUser(user *User, executor, ipAddress, role string) error {
|
2022-01-31 17:01:37 +00:00
|
|
|
user.Username = config.convertName(user.Username)
|
2020-07-08 17:59:31 +00:00
|
|
|
err := provider.addUser(user)
|
2019-11-14 10:06:03 +00:00
|
|
|
if err == nil {
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationAdd, executor, ipAddress, actionObjectUser, user.Username, role, user)
|
2019-11-14 10:06:03 +00:00
|
|
|
}
|
|
|
|
return err
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
2022-04-25 13:49:11 +00:00
|
|
|
// UpdateUserPassword updates the user password
|
2022-12-03 10:45:27 +00:00
|
|
|
func UpdateUserPassword(username, plainPwd, executor, ipAddress, role string) error {
|
2022-12-11 16:15:34 +00:00
|
|
|
user, err := provider.userExists(username, role)
|
2022-04-25 13:49:11 +00:00
|
|
|
if err != nil {
|
2022-12-11 16:15:34 +00:00
|
|
|
return err
|
2022-04-25 13:49:11 +00:00
|
|
|
}
|
2023-03-02 08:11:30 +00:00
|
|
|
userCopy := user.getACopy()
|
|
|
|
if err := userCopy.LoadAndApplyGroupSettings(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
userCopy.Password = plainPwd
|
|
|
|
if err := createUserPasswordHash(&userCopy); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
user.LastPasswordChange = userCopy.LastPasswordChange
|
|
|
|
user.Password = userCopy.Password
|
2022-12-11 16:15:34 +00:00
|
|
|
user.Filters.RequirePasswordChange = false
|
|
|
|
// the last password change is set when validating the user
|
|
|
|
if err := provider.updateUser(&user); err != nil {
|
|
|
|
return err
|
2022-04-25 13:49:11 +00:00
|
|
|
}
|
2023-05-20 10:39:07 +00:00
|
|
|
webDAVUsersCache.swap(&user, plainPwd)
|
2022-12-11 16:15:34 +00:00
|
|
|
executeAction(operationUpdate, executor, ipAddress, actionObjectUser, username, role, &user)
|
2022-04-25 13:49:11 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-08-31 17:25:17 +00:00
|
|
|
// UpdateUser updates an existing SFTPGo user.
|
2022-12-03 10:45:27 +00:00
|
|
|
func UpdateUser(user *User, executor, ipAddress, role string) error {
|
2022-04-25 13:49:11 +00:00
|
|
|
if user.groupSettingsApplied {
|
|
|
|
return errors.New("cannot save a user with group settings applied")
|
|
|
|
}
|
2020-07-08 17:59:31 +00:00
|
|
|
err := provider.updateUser(user)
|
2019-11-14 10:06:03 +00:00
|
|
|
if err == nil {
|
2023-05-20 10:39:07 +00:00
|
|
|
webDAVUsersCache.swap(user, "")
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationUpdate, executor, ipAddress, actionObjectUser, user.Username, role, user)
|
2019-11-14 10:06:03 +00:00
|
|
|
}
|
|
|
|
return err
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
2020-09-01 14:10:26 +00:00
|
|
|
// DeleteUser deletes an existing SFTPGo user.
|
2022-11-16 18:04:50 +00:00
|
|
|
func DeleteUser(username, executor, ipAddress, role string) error {
|
2022-01-31 17:01:37 +00:00
|
|
|
username = config.convertName(username)
|
2022-11-16 18:04:50 +00:00
|
|
|
user, err := provider.userExists(username, role)
|
2021-01-17 21:29:08 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
2022-07-17 16:48:41 +00:00
|
|
|
err = provider.deleteUser(user, config.IsShared == 1)
|
2019-11-14 10:06:03 +00:00
|
|
|
if err == nil {
|
2020-08-31 17:25:17 +00:00
|
|
|
RemoveCachedWebDAVUser(user.Username)
|
2022-07-17 16:48:41 +00:00
|
|
|
delayedQuotaUpdater.resetUserQuota(user.Username)
|
2023-04-13 16:23:42 +00:00
|
|
|
cachedUserPasswords.Remove(username)
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationDelete, executor, ipAddress, actionObjectUser, user.Username, role, &user)
|
2019-11-14 10:06:03 +00:00
|
|
|
}
|
|
|
|
return err
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
2022-01-30 10:42:36 +00:00
|
|
|
// AddActiveTransfer stores the specified transfer
|
|
|
|
func AddActiveTransfer(transfer ActiveTransfer) {
|
|
|
|
if err := provider.addActiveTransfer(transfer); err != nil {
|
|
|
|
providerLog(logger.LevelError, "unable to add transfer id %v, connection id %v: %v",
|
|
|
|
transfer.ID, transfer.ConnID, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// UpdateActiveTransferSizes updates the current upload and download sizes for the specified transfer
|
|
|
|
func UpdateActiveTransferSizes(ulSize, dlSize, transferID int64, connectionID string) {
|
|
|
|
if err := provider.updateActiveTransferSizes(ulSize, dlSize, transferID, connectionID); err != nil {
|
|
|
|
providerLog(logger.LevelError, "unable to update sizes for transfer id %v, connection id %v: %v",
|
|
|
|
transferID, connectionID, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// RemoveActiveTransfer removes the specified transfer
|
|
|
|
func RemoveActiveTransfer(transferID int64, connectionID string) {
|
|
|
|
if err := provider.removeActiveTransfer(transferID, connectionID); err != nil {
|
|
|
|
providerLog(logger.LevelError, "unable to delete transfer id %v, connection id %v: %v",
|
|
|
|
transferID, connectionID, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// CleanupActiveTransfers removes the transfer before the specified time
|
|
|
|
func CleanupActiveTransfers(before time.Time) error {
|
|
|
|
err := provider.cleanupActiveTransfers(before)
|
|
|
|
if err == nil {
|
|
|
|
providerLog(logger.LevelDebug, "deleted active transfers updated before: %v", before)
|
|
|
|
} else {
|
|
|
|
providerLog(logger.LevelError, "error deleting active transfers updated before %v: %v", before, err)
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetActiveTransfers retrieves the active transfers with an update time after the specified value
|
|
|
|
func GetActiveTransfers(from time.Time) ([]ActiveTransfer, error) {
|
|
|
|
return provider.getActiveTransfers(from)
|
|
|
|
}
|
|
|
|
|
2022-05-19 17:49:51 +00:00
|
|
|
// AddSharedSession stores a new session within the data provider
|
|
|
|
func AddSharedSession(session Session) error {
|
|
|
|
err := provider.addSharedSession(session)
|
|
|
|
if err != nil {
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelError, "unable to add shared session, key %q, type: %v, err: %v",
|
2022-05-19 17:49:51 +00:00
|
|
|
session.Key, session.Type, err)
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// DeleteSharedSession deletes the session with the specified key
|
|
|
|
func DeleteSharedSession(key string) error {
|
|
|
|
err := provider.deleteSharedSession(key)
|
|
|
|
if err != nil {
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelError, "unable to add shared session, key %q, err: %v", key, err)
|
2022-05-19 17:49:51 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetSharedSession retrieves the session with the specified key
|
|
|
|
func GetSharedSession(key string) (Session, error) {
|
|
|
|
return provider.getSharedSession(key)
|
|
|
|
}
|
|
|
|
|
|
|
|
// CleanupSharedSessions removes the shared session with the specified type and
|
|
|
|
// before the specified time
|
|
|
|
func CleanupSharedSessions(sessionType SessionType, before time.Time) error {
|
|
|
|
err := provider.cleanupSharedSessions(sessionType, util.GetTimeAsMsSinceEpoch(before))
|
|
|
|
if err == nil {
|
|
|
|
providerLog(logger.LevelDebug, "deleted shared sessions before: %v, type: %v", before, sessionType)
|
|
|
|
} else {
|
|
|
|
providerLog(logger.LevelError, "error deleting shared session before %v, type %v: %v", before, sessionType, err)
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-02-02 21:20:39 +00:00
|
|
|
// ReloadConfig reloads provider configuration.
|
|
|
|
// Currently only implemented for memory provider, allows to reload the users
|
|
|
|
// from the configured file, if defined
|
|
|
|
func ReloadConfig() error {
|
|
|
|
return provider.reloadConfig()
|
|
|
|
}
|
|
|
|
|
2021-11-06 13:13:20 +00:00
|
|
|
// GetShares returns an array of shares respecting limit and offset
|
|
|
|
func GetShares(limit, offset int, order, username string) ([]Share, error) {
|
|
|
|
return provider.getShares(limit, offset, order, username)
|
|
|
|
}
|
|
|
|
|
2021-08-17 16:08:32 +00:00
|
|
|
// GetAPIKeys returns an array of API keys respecting limit and offset
|
|
|
|
func GetAPIKeys(limit, offset int, order string) ([]APIKey, error) {
|
|
|
|
return provider.getAPIKeys(limit, offset, order)
|
|
|
|
}
|
|
|
|
|
2021-01-17 21:29:08 +00:00
|
|
|
// GetAdmins returns an array of admins respecting limit and offset
|
|
|
|
func GetAdmins(limit, offset int, order string) ([]Admin, error) {
|
|
|
|
return provider.getAdmins(limit, offset, order)
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
2022-11-16 18:04:50 +00:00
|
|
|
// GetRoles returns an array of roles respecting limit and offset
|
|
|
|
func GetRoles(limit, offset int, order string, minimal bool) ([]Role, error) {
|
|
|
|
return provider.getRoles(limit, offset, order, minimal)
|
|
|
|
}
|
|
|
|
|
2022-04-25 13:49:11 +00:00
|
|
|
// GetGroups returns an array of groups respecting limit and offset
|
|
|
|
func GetGroups(limit, offset int, order string, minimal bool) ([]Group, error) {
|
|
|
|
return provider.getGroups(limit, offset, order, minimal)
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetUsers returns an array of users respecting limit and offset
|
2022-11-16 18:04:50 +00:00
|
|
|
func GetUsers(limit, offset int, order, role string) ([]User, error) {
|
|
|
|
return provider.getUsers(limit, offset, order, role)
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
2022-01-20 17:19:20 +00:00
|
|
|
// GetUsersForQuotaCheck returns the users with the fields required for a quota check
|
|
|
|
func GetUsersForQuotaCheck(toFetch map[string]bool) ([]User, error) {
|
|
|
|
return provider.getUsersForQuotaCheck(toFetch)
|
|
|
|
}
|
|
|
|
|
2020-06-07 21:30:18 +00:00
|
|
|
// AddFolder adds a new virtual folder.
|
2022-12-03 10:45:27 +00:00
|
|
|
func AddFolder(folder *vfs.BaseVirtualFolder, executor, ipAddress, role string) error {
|
2022-01-31 17:01:37 +00:00
|
|
|
folder.Name = config.convertName(folder.Name)
|
2022-07-24 06:10:23 +00:00
|
|
|
err := provider.addFolder(folder)
|
|
|
|
if err == nil {
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationAdd, executor, ipAddress, actionObjectFolder, folder.Name, role, &wrappedFolder{Folder: *folder})
|
2022-07-24 06:10:23 +00:00
|
|
|
}
|
|
|
|
return err
|
2020-06-07 21:30:18 +00:00
|
|
|
}
|
|
|
|
|
2021-02-01 18:04:15 +00:00
|
|
|
// UpdateFolder updates the specified virtual folder
|
2022-12-03 10:45:27 +00:00
|
|
|
func UpdateFolder(folder *vfs.BaseVirtualFolder, users []string, groups []string, executor, ipAddress, role string) error {
|
2021-03-21 18:15:47 +00:00
|
|
|
err := provider.updateFolder(folder)
|
|
|
|
if err == nil {
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationUpdate, executor, ipAddress, actionObjectFolder, folder.Name, role, &wrappedFolder{Folder: *folder})
|
2022-04-25 13:49:11 +00:00
|
|
|
usersInGroups, errGrp := provider.getUsersInGroups(groups)
|
|
|
|
if errGrp == nil {
|
|
|
|
users = append(users, usersInGroups...)
|
2022-05-31 16:22:18 +00:00
|
|
|
users = util.RemoveDuplicates(users, false)
|
2022-04-25 13:49:11 +00:00
|
|
|
} else {
|
|
|
|
providerLog(logger.LevelWarn, "unable to get users in groups %+v: %v", groups, errGrp)
|
|
|
|
}
|
2021-03-21 18:15:47 +00:00
|
|
|
for _, user := range users {
|
2021-08-19 13:51:43 +00:00
|
|
|
provider.setUpdatedAt(user)
|
2022-11-16 18:04:50 +00:00
|
|
|
u, err := provider.userExists(user, "")
|
2021-08-19 13:51:43 +00:00
|
|
|
if err == nil {
|
2023-05-20 10:39:07 +00:00
|
|
|
webDAVUsersCache.swap(&u, "")
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationUpdate, executor, ipAddress, actionObjectUser, u.Username, u.Role, &u)
|
2021-08-19 13:51:43 +00:00
|
|
|
} else {
|
|
|
|
RemoveCachedWebDAVUser(user)
|
|
|
|
}
|
2021-03-21 18:15:47 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return err
|
2021-02-01 18:04:15 +00:00
|
|
|
}
|
|
|
|
|
2020-06-07 21:30:18 +00:00
|
|
|
// DeleteFolder deletes an existing folder.
|
2022-12-03 10:45:27 +00:00
|
|
|
func DeleteFolder(folderName, executor, ipAddress, role string) error {
|
2022-01-31 17:01:37 +00:00
|
|
|
folderName = config.convertName(folderName)
|
2021-02-01 18:04:15 +00:00
|
|
|
folder, err := provider.getFolderByName(folderName)
|
2021-01-17 21:29:08 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
2020-06-07 21:30:18 +00:00
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
err = provider.deleteFolder(folder)
|
2021-03-21 18:15:47 +00:00
|
|
|
if err == nil {
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationDelete, executor, ipAddress, actionObjectFolder, folder.Name, role, &wrappedFolder{Folder: folder})
|
2022-04-25 13:49:11 +00:00
|
|
|
users := folder.Users
|
|
|
|
usersInGroups, errGrp := provider.getUsersInGroups(folder.Groups)
|
|
|
|
if errGrp == nil {
|
|
|
|
users = append(users, usersInGroups...)
|
2022-05-31 16:22:18 +00:00
|
|
|
users = util.RemoveDuplicates(users, false)
|
2022-04-25 13:49:11 +00:00
|
|
|
} else {
|
|
|
|
providerLog(logger.LevelWarn, "unable to get users in groups %+v: %v", folder.Groups, errGrp)
|
|
|
|
}
|
|
|
|
for _, user := range users {
|
2021-08-19 13:51:43 +00:00
|
|
|
provider.setUpdatedAt(user)
|
2022-11-16 18:04:50 +00:00
|
|
|
u, err := provider.userExists(user, "")
|
2021-10-10 11:08:05 +00:00
|
|
|
if err == nil {
|
2022-12-03 10:45:27 +00:00
|
|
|
executeAction(operationUpdate, executor, ipAddress, actionObjectUser, u.Username, u.Role, &u)
|
2021-10-10 11:08:05 +00:00
|
|
|
}
|
2021-03-21 18:15:47 +00:00
|
|
|
RemoveCachedWebDAVUser(user)
|
|
|
|
}
|
2021-04-11 06:38:43 +00:00
|
|
|
delayedQuotaUpdater.resetFolderQuota(folderName)
|
2021-03-21 18:15:47 +00:00
|
|
|
}
|
|
|
|
return err
|
2020-06-07 21:30:18 +00:00
|
|
|
}
|
|
|
|
|
2021-02-01 18:04:15 +00:00
|
|
|
// GetFolderByName returns the folder with the specified name if any
|
|
|
|
func GetFolderByName(name string) (vfs.BaseVirtualFolder, error) {
|
2022-01-31 17:01:37 +00:00
|
|
|
name = config.convertName(name)
|
2021-02-01 18:04:15 +00:00
|
|
|
return provider.getFolderByName(name)
|
2020-06-07 21:30:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// GetFolders returns an array of folders respecting limit and offset
|
2022-04-25 13:49:11 +00:00
|
|
|
func GetFolders(limit, offset int, order string, minimal bool) ([]vfs.BaseVirtualFolder, error) {
|
|
|
|
return provider.getFolders(limit, offset, order, minimal)
|
2020-06-07 21:30:18 +00:00
|
|
|
}
|
|
|
|
|
2023-04-18 16:11:23 +00:00
|
|
|
func dumpUsers(data *BackupData, scopes []string) error {
|
2024-07-24 16:27:13 +00:00
|
|
|
if len(scopes) == 0 || slices.Contains(scopes, DumpScopeUsers) {
|
2023-04-18 16:11:23 +00:00
|
|
|
users, err := provider.dumpUsers()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
data.Users = users
|
|
|
|
}
|
|
|
|
return nil
|
2022-08-01 16:48:54 +00:00
|
|
|
}
|
|
|
|
|
2023-04-18 16:11:23 +00:00
|
|
|
func dumpFolders(data *BackupData, scopes []string) error {
|
2024-07-24 16:27:13 +00:00
|
|
|
if len(scopes) == 0 || slices.Contains(scopes, DumpScopeFolders) {
|
2023-04-18 16:11:23 +00:00
|
|
|
folders, err := provider.dumpFolders()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
data.Folders = folders
|
|
|
|
}
|
|
|
|
return nil
|
2022-08-01 16:48:54 +00:00
|
|
|
}
|
|
|
|
|
2023-04-18 16:11:23 +00:00
|
|
|
func dumpGroups(data *BackupData, scopes []string) error {
|
2024-07-24 16:27:13 +00:00
|
|
|
if len(scopes) == 0 || slices.Contains(scopes, DumpScopeGroups) {
|
2023-04-18 16:11:23 +00:00
|
|
|
groups, err := provider.dumpGroups()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
data.Groups = groups
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func dumpAdmins(data *BackupData, scopes []string) error {
|
2024-07-24 16:27:13 +00:00
|
|
|
if len(scopes) == 0 || slices.Contains(scopes, DumpScopeAdmins) {
|
2023-04-18 16:11:23 +00:00
|
|
|
admins, err := provider.dumpAdmins()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
data.Admins = admins
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func dumpAPIKeys(data *BackupData, scopes []string) error {
|
2024-07-24 16:27:13 +00:00
|
|
|
if len(scopes) == 0 || slices.Contains(scopes, DumpScopeAPIKeys) {
|
2023-04-18 16:11:23 +00:00
|
|
|
apiKeys, err := provider.dumpAPIKeys()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
data.APIKeys = apiKeys
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func dumpShares(data *BackupData, scopes []string) error {
|
2024-07-24 16:27:13 +00:00
|
|
|
if len(scopes) == 0 || slices.Contains(scopes, DumpScopeShares) {
|
2023-04-18 16:11:23 +00:00
|
|
|
shares, err := provider.dumpShares()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
data.Shares = shares
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func dumpActions(data *BackupData, scopes []string) error {
|
2024-07-24 16:27:13 +00:00
|
|
|
if len(scopes) == 0 || slices.Contains(scopes, DumpScopeActions) {
|
2023-04-18 16:11:23 +00:00
|
|
|
actions, err := provider.dumpEventActions()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
data.EventActions = actions
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func dumpRules(data *BackupData, scopes []string) error {
|
2024-07-24 16:27:13 +00:00
|
|
|
if len(scopes) == 0 || slices.Contains(scopes, DumpScopeRules) {
|
2023-04-18 16:11:23 +00:00
|
|
|
rules, err := provider.dumpEventRules()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
data.EventRules = rules
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func dumpRoles(data *BackupData, scopes []string) error {
|
2024-07-24 16:27:13 +00:00
|
|
|
if len(scopes) == 0 || slices.Contains(scopes, DumpScopeRoles) {
|
2023-04-18 16:11:23 +00:00
|
|
|
roles, err := provider.dumpRoles()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
data.Roles = roles
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func dumpIPLists(data *BackupData, scopes []string) error {
|
2024-07-24 16:27:13 +00:00
|
|
|
if len(scopes) == 0 || slices.Contains(scopes, DumpScopeIPLists) {
|
2023-04-18 16:11:23 +00:00
|
|
|
ipLists, err := provider.dumpIPListEntries()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
data.IPLists = ipLists
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func dumpConfigs(data *BackupData, scopes []string) error {
|
2024-07-24 16:27:13 +00:00
|
|
|
if len(scopes) == 0 || slices.Contains(scopes, DumpScopeConfigs) {
|
2023-04-18 16:11:23 +00:00
|
|
|
configs, err := provider.getConfigs()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
data.Configs = &configs
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// DumpData returns a dump containing the requested scopes.
|
|
|
|
// Empty scopes means all
|
|
|
|
func DumpData(scopes []string) (BackupData, error) {
|
|
|
|
data := BackupData{
|
|
|
|
Version: DumpVersion,
|
|
|
|
}
|
|
|
|
if err := dumpGroups(&data, scopes); err != nil {
|
2022-04-25 13:49:11 +00:00
|
|
|
return data, err
|
|
|
|
}
|
2023-04-18 16:11:23 +00:00
|
|
|
if err := dumpUsers(&data, scopes); err != nil {
|
2020-06-07 21:30:18 +00:00
|
|
|
return data, err
|
|
|
|
}
|
2023-04-18 16:11:23 +00:00
|
|
|
if err := dumpFolders(&data, scopes); err != nil {
|
2020-06-07 21:30:18 +00:00
|
|
|
return data, err
|
|
|
|
}
|
2023-04-18 16:11:23 +00:00
|
|
|
if err := dumpAdmins(&data, scopes); err != nil {
|
2021-01-17 21:29:08 +00:00
|
|
|
return data, err
|
|
|
|
}
|
2023-04-18 16:11:23 +00:00
|
|
|
if err := dumpAPIKeys(&data, scopes); err != nil {
|
2021-08-17 16:08:32 +00:00
|
|
|
return data, err
|
|
|
|
}
|
2023-04-18 16:11:23 +00:00
|
|
|
if err := dumpShares(&data, scopes); err != nil {
|
2021-11-06 13:13:20 +00:00
|
|
|
return data, err
|
|
|
|
}
|
2023-04-18 16:11:23 +00:00
|
|
|
if err := dumpActions(&data, scopes); err != nil {
|
2022-07-11 06:17:36 +00:00
|
|
|
return data, err
|
|
|
|
}
|
2023-04-18 16:11:23 +00:00
|
|
|
if err := dumpRules(&data, scopes); err != nil {
|
2022-07-11 06:17:36 +00:00
|
|
|
return data, err
|
|
|
|
}
|
2023-04-18 16:11:23 +00:00
|
|
|
if err := dumpRoles(&data, scopes); err != nil {
|
2022-11-16 18:04:50 +00:00
|
|
|
return data, err
|
|
|
|
}
|
2023-04-18 16:11:23 +00:00
|
|
|
if err := dumpIPLists(&data, scopes); err != nil {
|
2023-02-09 08:33:33 +00:00
|
|
|
return data, err
|
|
|
|
}
|
2023-04-18 16:11:23 +00:00
|
|
|
if err := dumpConfigs(&data, scopes); err != nil {
|
2023-02-19 18:03:45 +00:00
|
|
|
return data, err
|
|
|
|
}
|
2023-04-18 16:11:23 +00:00
|
|
|
|
|
|
|
return data, nil
|
2020-06-07 21:30:18 +00:00
|
|
|
}
|
|
|
|
|
2020-11-22 20:53:04 +00:00
|
|
|
// ParseDumpData tries to parse data as BackupData
|
|
|
|
func ParseDumpData(data []byte) (BackupData, error) {
|
|
|
|
var dump BackupData
|
|
|
|
err := json.Unmarshal(data, &dump)
|
|
|
|
return dump, err
|
|
|
|
}
|
|
|
|
|
2021-12-25 11:08:07 +00:00
|
|
|
// GetProviderConfig returns the current provider configuration
|
|
|
|
func GetProviderConfig() Config {
|
|
|
|
return config
|
|
|
|
}
|
|
|
|
|
2019-11-14 17:48:01 +00:00
|
|
|
// GetProviderStatus returns an error if the provider is not available
|
2020-12-08 10:18:34 +00:00
|
|
|
func GetProviderStatus() ProviderStatus {
|
|
|
|
err := provider.checkAvailability()
|
|
|
|
status := ProviderStatus{
|
|
|
|
Driver: config.Driver,
|
|
|
|
}
|
|
|
|
if err == nil {
|
|
|
|
status.IsActive = true
|
|
|
|
} else {
|
|
|
|
status.IsActive = false
|
|
|
|
status.Error = err.Error()
|
|
|
|
}
|
|
|
|
return status
|
2019-11-14 17:48:01 +00:00
|
|
|
}
|
|
|
|
|
2019-09-29 06:38:09 +00:00
|
|
|
// Close releases all provider resources.
|
|
|
|
// This method is used in test cases.
|
|
|
|
// Closing an uninitialized provider is not supported
|
2020-07-08 17:59:31 +00:00
|
|
|
func Close() error {
|
2022-03-13 12:45:07 +00:00
|
|
|
stopScheduler()
|
2020-07-08 17:59:31 +00:00
|
|
|
return provider.close()
|
2019-09-28 20:48:52 +00:00
|
|
|
}
|
|
|
|
|
2020-02-08 13:44:25 +00:00
|
|
|
func createProvider(basePath string) error {
|
2020-06-07 21:30:18 +00:00
|
|
|
sqlPlaceholders = getSQLPlaceholders()
|
2024-04-20 14:45:20 +00:00
|
|
|
if err := validateSQLTablesPrefix(); err != nil {
|
2020-06-07 21:30:18 +00:00
|
|
|
return err
|
|
|
|
}
|
2021-03-23 18:14:15 +00:00
|
|
|
logSender = fmt.Sprintf("dataprovider_%v", config.Driver)
|
|
|
|
|
|
|
|
switch config.Driver {
|
|
|
|
case SQLiteDataProviderName:
|
|
|
|
return initializeSQLiteProvider(basePath)
|
|
|
|
case PGSQLDataProviderName, CockroachDataProviderName:
|
|
|
|
return initializePGSQLProvider()
|
|
|
|
case MySQLDataProviderName:
|
|
|
|
return initializeMySQLProvider()
|
|
|
|
case BoltDataProviderName:
|
|
|
|
return initializeBoltProvider(basePath)
|
|
|
|
case MemoryDataProviderName:
|
2024-04-20 14:45:20 +00:00
|
|
|
if err := initializeMemoryProvider(basePath); err != nil {
|
2024-08-14 06:46:18 +00:00
|
|
|
logger.Warn(logSender, "", "provider initialized but data loading failed: %v", err)
|
|
|
|
logger.WarnToConsole("provider initialized but data loading failed: %v", err)
|
2024-04-20 14:45:20 +00:00
|
|
|
}
|
2021-03-23 18:14:15 +00:00
|
|
|
return nil
|
|
|
|
default:
|
|
|
|
return fmt.Errorf("unsupported data provider: %v", config.Driver)
|
2020-02-08 13:44:25 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-25 13:49:11 +00:00
|
|
|
func copyBaseUserFilters(in sdk.BaseUserFilters) sdk.BaseUserFilters {
|
|
|
|
filters := sdk.BaseUserFilters{}
|
|
|
|
filters.MaxUploadFileSize = in.MaxUploadFileSize
|
|
|
|
filters.TLSUsername = in.TLSUsername
|
|
|
|
filters.UserType = in.UserType
|
|
|
|
filters.AllowedIP = make([]string, len(in.AllowedIP))
|
|
|
|
copy(filters.AllowedIP, in.AllowedIP)
|
|
|
|
filters.DeniedIP = make([]string, len(in.DeniedIP))
|
|
|
|
copy(filters.DeniedIP, in.DeniedIP)
|
|
|
|
filters.DeniedLoginMethods = make([]string, len(in.DeniedLoginMethods))
|
|
|
|
copy(filters.DeniedLoginMethods, in.DeniedLoginMethods)
|
|
|
|
filters.FilePatterns = make([]sdk.PatternsFilter, len(in.FilePatterns))
|
|
|
|
copy(filters.FilePatterns, in.FilePatterns)
|
|
|
|
filters.DeniedProtocols = make([]string, len(in.DeniedProtocols))
|
|
|
|
copy(filters.DeniedProtocols, in.DeniedProtocols)
|
|
|
|
filters.TwoFactorAuthProtocols = make([]string, len(in.TwoFactorAuthProtocols))
|
|
|
|
copy(filters.TwoFactorAuthProtocols, in.TwoFactorAuthProtocols)
|
|
|
|
filters.Hooks.ExternalAuthDisabled = in.Hooks.ExternalAuthDisabled
|
|
|
|
filters.Hooks.PreLoginDisabled = in.Hooks.PreLoginDisabled
|
|
|
|
filters.Hooks.CheckPasswordDisabled = in.Hooks.CheckPasswordDisabled
|
|
|
|
filters.DisableFsChecks = in.DisableFsChecks
|
|
|
|
filters.StartDirectory = in.StartDirectory
|
2022-07-26 16:51:39 +00:00
|
|
|
filters.FTPSecurity = in.FTPSecurity
|
2022-07-27 16:54:25 +00:00
|
|
|
filters.IsAnonymous = in.IsAnonymous
|
2022-04-25 13:49:11 +00:00
|
|
|
filters.AllowAPIKeyAuth = in.AllowAPIKeyAuth
|
|
|
|
filters.ExternalAuthCacheTime = in.ExternalAuthCacheTime
|
2022-08-28 12:41:42 +00:00
|
|
|
filters.DefaultSharesExpiration = in.DefaultSharesExpiration
|
2023-08-07 17:07:20 +00:00
|
|
|
filters.MaxSharesExpiration = in.MaxSharesExpiration
|
2022-12-11 16:15:34 +00:00
|
|
|
filters.PasswordExpiration = in.PasswordExpiration
|
2023-03-02 08:11:30 +00:00
|
|
|
filters.PasswordStrength = in.PasswordStrength
|
2022-04-25 13:49:11 +00:00
|
|
|
filters.WebClient = make([]string, len(in.WebClient))
|
|
|
|
copy(filters.WebClient, in.WebClient)
|
2024-01-14 20:36:23 +00:00
|
|
|
filters.TLSCerts = make([]string, len(in.TLSCerts))
|
|
|
|
copy(filters.TLSCerts, in.TLSCerts)
|
2022-04-25 13:49:11 +00:00
|
|
|
filters.BandwidthLimits = make([]sdk.BandwidthLimit, 0, len(in.BandwidthLimits))
|
|
|
|
for _, limit := range in.BandwidthLimits {
|
|
|
|
bwLimit := sdk.BandwidthLimit{
|
|
|
|
UploadBandwidth: limit.UploadBandwidth,
|
|
|
|
DownloadBandwidth: limit.DownloadBandwidth,
|
|
|
|
Sources: make([]string, 0, len(limit.Sources)),
|
|
|
|
}
|
|
|
|
bwLimit.Sources = make([]string, len(limit.Sources))
|
|
|
|
copy(bwLimit.Sources, limit.Sources)
|
|
|
|
filters.BandwidthLimits = append(filters.BandwidthLimits, bwLimit)
|
|
|
|
}
|
2024-03-17 10:30:03 +00:00
|
|
|
filters.AccessTime = make([]sdk.TimePeriod, 0, len(in.AccessTime))
|
|
|
|
for _, period := range in.AccessTime {
|
|
|
|
filters.AccessTime = append(filters.AccessTime, sdk.TimePeriod{
|
|
|
|
DayOfWeek: period.DayOfWeek,
|
|
|
|
From: period.From,
|
|
|
|
To: period.To,
|
|
|
|
})
|
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
return filters
|
|
|
|
}
|
|
|
|
|
2019-09-28 21:44:36 +00:00
|
|
|
func buildUserHomeDir(user *User) {
|
2020-12-12 09:31:09 +00:00
|
|
|
if user.HomeDir == "" {
|
|
|
|
if config.UsersBaseDir != "" {
|
2019-09-28 20:48:52 +00:00
|
|
|
user.HomeDir = filepath.Join(config.UsersBaseDir, user.Username)
|
2021-05-31 19:45:29 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
switch user.FsConfig.Provider {
|
2022-07-21 16:42:22 +00:00
|
|
|
case sdk.SFTPFilesystemProvider, sdk.S3FilesystemProvider, sdk.AzureBlobFilesystemProvider, sdk.GCSFilesystemProvider, sdk.HTTPFilesystemProvider:
|
2021-05-31 19:45:29 +00:00
|
|
|
if tempPath != "" {
|
|
|
|
user.HomeDir = filepath.Join(tempPath, user.Username)
|
|
|
|
} else {
|
|
|
|
user.HomeDir = filepath.Join(os.TempDir(), user.Username)
|
|
|
|
}
|
2019-09-28 20:48:52 +00:00
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
} else {
|
|
|
|
user.HomeDir = filepath.Clean(user.HomeDir)
|
2019-09-28 20:48:52 +00:00
|
|
|
}
|
2019-09-28 21:44:36 +00:00
|
|
|
}
|
|
|
|
|
2020-06-07 21:30:18 +00:00
|
|
|
func validateFolderQuotaLimits(folder vfs.VirtualFolder) error {
|
|
|
|
if folder.QuotaSize < -1 {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError(fmt.Sprintf("invalid quota_size: %v folder path %q", folder.QuotaSize, folder.MappedPath)),
|
|
|
|
util.I18nErrorFolderQuotaSizeInvalid,
|
|
|
|
)
|
2020-06-07 21:30:18 +00:00
|
|
|
}
|
|
|
|
if folder.QuotaFiles < -1 {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError(fmt.Sprintf("invalid quota_file: %v folder path %q", folder.QuotaFiles, folder.MappedPath)),
|
|
|
|
util.I18nErrorFolderQuotaFileInvalid,
|
|
|
|
)
|
2020-06-07 21:30:18 +00:00
|
|
|
}
|
|
|
|
if (folder.QuotaSize == -1 && folder.QuotaFiles != -1) || (folder.QuotaFiles == -1 && folder.QuotaSize != -1) {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError(fmt.Sprintf("virtual folder quota_size and quota_files must be both -1 or >= 0, quota_size: %v quota_files: %v",
|
|
|
|
folder.QuotaFiles, folder.QuotaSize)),
|
|
|
|
util.I18nErrorFolderQuotaInvalid,
|
|
|
|
)
|
2020-06-07 21:30:18 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-04-25 13:49:11 +00:00
|
|
|
func validateUserGroups(user *User) error {
|
|
|
|
if len(user.Groups) == 0 {
|
2020-02-23 10:30:26 +00:00
|
|
|
return nil
|
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
hasPrimary := false
|
|
|
|
groupNames := make(map[string]bool)
|
|
|
|
|
|
|
|
for _, g := range user.Groups {
|
2022-09-13 16:04:27 +00:00
|
|
|
if g.Type < sdk.GroupTypePrimary && g.Type > sdk.GroupTypeMembership {
|
2022-04-25 13:49:11 +00:00
|
|
|
return util.NewValidationError(fmt.Sprintf("invalid group type: %v", g.Type))
|
|
|
|
}
|
|
|
|
if g.Type == sdk.GroupTypePrimary {
|
|
|
|
if hasPrimary {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError("only one primary group is allowed"),
|
|
|
|
util.I18nErrorPrimaryGroup,
|
|
|
|
)
|
2022-04-25 13:49:11 +00:00
|
|
|
}
|
|
|
|
hasPrimary = true
|
|
|
|
}
|
|
|
|
if groupNames[g.Name] {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError(fmt.Sprintf("the group %q is duplicated", g.Name)),
|
|
|
|
util.I18nErrorDuplicateGroup,
|
|
|
|
)
|
2022-04-25 13:49:11 +00:00
|
|
|
}
|
|
|
|
groupNames[g.Name] = true
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func validateAssociatedVirtualFolders(vfolders []vfs.VirtualFolder) ([]vfs.VirtualFolder, error) {
|
|
|
|
if len(vfolders) == 0 {
|
|
|
|
return []vfs.VirtualFolder{}, nil
|
|
|
|
}
|
2020-02-23 10:30:26 +00:00
|
|
|
var virtualFolders []vfs.VirtualFolder
|
2022-04-02 16:32:46 +00:00
|
|
|
folderNames := make(map[string]bool)
|
|
|
|
|
2022-04-25 13:49:11 +00:00
|
|
|
for _, v := range vfolders {
|
|
|
|
if v.VirtualPath == "" {
|
2023-12-10 15:40:13 +00:00
|
|
|
return nil, util.NewI18nError(
|
|
|
|
util.NewValidationError("mount/virtual path is mandatory"),
|
|
|
|
util.I18nErrorFolderMountPathRequired,
|
|
|
|
)
|
2022-04-25 13:49:11 +00:00
|
|
|
}
|
2022-04-02 16:32:46 +00:00
|
|
|
cleanedVPath := util.CleanPath(v.VirtualPath)
|
2020-06-07 21:30:18 +00:00
|
|
|
if err := validateFolderQuotaLimits(v); err != nil {
|
2022-04-25 13:49:11 +00:00
|
|
|
return nil, err
|
2020-06-07 21:30:18 +00:00
|
|
|
}
|
2023-07-23 16:48:49 +00:00
|
|
|
if v.Name == "" {
|
2023-12-10 15:40:13 +00:00
|
|
|
return nil, util.NewI18nError(util.NewValidationError("folder name is mandatory"), util.I18nErrorFolderNameRequired)
|
2020-02-23 10:30:26 +00:00
|
|
|
}
|
2023-07-23 16:48:49 +00:00
|
|
|
if folderNames[v.Name] {
|
2023-12-10 15:40:13 +00:00
|
|
|
return nil, util.NewI18nError(
|
|
|
|
util.NewValidationError(fmt.Sprintf("the folder %q is duplicated", v.Name)),
|
|
|
|
util.I18nErrorDuplicatedFolders,
|
|
|
|
)
|
2020-02-23 10:30:26 +00:00
|
|
|
}
|
2022-04-02 16:32:46 +00:00
|
|
|
for _, vFolder := range virtualFolders {
|
2022-12-27 17:51:53 +00:00
|
|
|
if util.IsDirOverlapped(vFolder.VirtualPath, cleanedVPath, false, "/") {
|
2023-12-10 15:40:13 +00:00
|
|
|
return nil, util.NewI18nError(
|
|
|
|
util.NewValidationError(fmt.Sprintf("invalid virtual folder %q, it overlaps with virtual folder %q",
|
|
|
|
v.VirtualPath, vFolder.VirtualPath)),
|
|
|
|
util.I18nErrorOverlappedFolders,
|
|
|
|
)
|
2021-03-21 18:15:47 +00:00
|
|
|
}
|
|
|
|
}
|
2020-02-23 10:30:26 +00:00
|
|
|
virtualFolders = append(virtualFolders, vfs.VirtualFolder{
|
2023-07-23 16:48:49 +00:00
|
|
|
BaseVirtualFolder: vfs.BaseVirtualFolder{
|
|
|
|
Name: v.Name,
|
|
|
|
},
|
|
|
|
VirtualPath: cleanedVPath,
|
|
|
|
QuotaSize: v.QuotaSize,
|
|
|
|
QuotaFiles: v.QuotaFiles,
|
2020-02-23 10:30:26 +00:00
|
|
|
})
|
2023-07-23 16:48:49 +00:00
|
|
|
folderNames[v.Name] = true
|
2020-02-23 10:30:26 +00:00
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
return virtualFolders, nil
|
2020-02-23 10:30:26 +00:00
|
|
|
}
|
|
|
|
|
2022-01-06 09:11:47 +00:00
|
|
|
func validateUserTOTPConfig(c *UserTOTPConfig, username string) error {
|
2021-09-04 10:11:04 +00:00
|
|
|
if !c.Enabled {
|
|
|
|
c.ConfigName = ""
|
|
|
|
c.Secret = kms.NewEmptySecret()
|
|
|
|
c.Protocols = nil
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if c.ConfigName == "" {
|
|
|
|
return util.NewValidationError("totp: config name is mandatory")
|
|
|
|
}
|
2024-07-24 16:27:13 +00:00
|
|
|
if !slices.Contains(mfa.GetAvailableTOTPConfigNames(), c.ConfigName) {
|
2023-02-26 14:15:34 +00:00
|
|
|
return util.NewValidationError(fmt.Sprintf("totp: config name %q not found", c.ConfigName))
|
2021-09-04 10:11:04 +00:00
|
|
|
}
|
|
|
|
if c.Secret.IsEmpty() {
|
|
|
|
return util.NewValidationError("totp: secret is mandatory")
|
|
|
|
}
|
|
|
|
if c.Secret.IsPlain() {
|
2021-09-05 12:10:12 +00:00
|
|
|
c.Secret.SetAdditionalData(username)
|
2021-09-04 10:11:04 +00:00
|
|
|
if err := c.Secret.Encrypt(); err != nil {
|
|
|
|
return util.NewValidationError(fmt.Sprintf("totp: unable to encrypt secret: %v", err))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if len(c.Protocols) == 0 {
|
|
|
|
return util.NewValidationError("totp: specify at least one protocol")
|
|
|
|
}
|
|
|
|
for _, protocol := range c.Protocols {
|
2024-07-24 16:27:13 +00:00
|
|
|
if !slices.Contains(MFAProtocols, protocol) {
|
2023-02-26 14:15:34 +00:00
|
|
|
return util.NewValidationError(fmt.Sprintf("totp: invalid protocol %q", protocol))
|
2021-09-04 10:11:04 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func validateUserRecoveryCodes(user *User) error {
|
|
|
|
for i := 0; i < len(user.Filters.RecoveryCodes); i++ {
|
|
|
|
code := &user.Filters.RecoveryCodes[i]
|
|
|
|
if code.Secret.IsEmpty() {
|
|
|
|
return util.NewValidationError("mfa: recovery code cannot be empty")
|
|
|
|
}
|
|
|
|
if code.Secret.IsPlain() {
|
2021-09-05 12:10:12 +00:00
|
|
|
code.Secret.SetAdditionalData(user.Username)
|
2021-09-04 10:11:04 +00:00
|
|
|
if err := code.Secret.Encrypt(); err != nil {
|
|
|
|
return util.NewValidationError(fmt.Sprintf("mfa: unable to encrypt recovery code: %v", err))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-04-25 13:49:11 +00:00
|
|
|
func validateUserPermissions(permsToCheck map[string][]string) (map[string][]string, error) {
|
2019-12-25 17:20:19 +00:00
|
|
|
permissions := make(map[string][]string)
|
2022-04-25 13:49:11 +00:00
|
|
|
for dir, perms := range permsToCheck {
|
2020-02-10 18:28:35 +00:00
|
|
|
if len(perms) == 0 && dir == "/" {
|
2023-02-26 14:15:34 +00:00
|
|
|
return permissions, util.NewValidationError(fmt.Sprintf("no permissions granted for the directory: %q", dir))
|
2019-12-25 17:20:19 +00:00
|
|
|
}
|
2020-02-19 21:39:30 +00:00
|
|
|
if len(perms) > len(ValidPerms) {
|
2022-04-25 13:49:11 +00:00
|
|
|
return permissions, util.NewValidationError("invalid permissions")
|
2020-02-19 21:39:30 +00:00
|
|
|
}
|
2019-12-25 17:20:19 +00:00
|
|
|
for _, p := range perms {
|
2024-07-24 16:27:13 +00:00
|
|
|
if !slices.Contains(ValidPerms, p) {
|
2023-02-26 14:15:34 +00:00
|
|
|
return permissions, util.NewValidationError(fmt.Sprintf("invalid permission: %q", p))
|
2019-12-25 17:20:19 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
cleanedDir := filepath.ToSlash(path.Clean(dir))
|
|
|
|
if cleanedDir != "/" {
|
|
|
|
cleanedDir = strings.TrimSuffix(cleanedDir, "/")
|
|
|
|
}
|
|
|
|
if !path.IsAbs(cleanedDir) {
|
2023-02-26 14:15:34 +00:00
|
|
|
return permissions, util.NewValidationError(fmt.Sprintf("cannot set permissions for non absolute path: %q", dir))
|
2019-12-25 17:20:19 +00:00
|
|
|
}
|
2020-02-10 18:28:35 +00:00
|
|
|
if dir != cleanedDir && cleanedDir == "/" {
|
2023-02-26 14:15:34 +00:00
|
|
|
return permissions, util.NewValidationError(fmt.Sprintf("cannot set permissions for invalid subdirectory: %q is an alias for \"/\"", dir))
|
2020-02-10 18:28:35 +00:00
|
|
|
}
|
2024-07-24 16:27:13 +00:00
|
|
|
if slices.Contains(perms, PermAny) {
|
2019-12-25 17:20:19 +00:00
|
|
|
permissions[cleanedDir] = []string{PermAny}
|
|
|
|
} else {
|
2022-05-31 16:22:18 +00:00
|
|
|
permissions[cleanedDir] = util.RemoveDuplicates(perms, false)
|
2019-12-25 17:20:19 +00:00
|
|
|
}
|
2019-10-07 16:19:01 +00:00
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
|
|
|
|
return permissions, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func validatePermissions(user *User) error {
|
|
|
|
if len(user.Permissions) == 0 {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(util.NewValidationError("please grant some permissions to this user"), util.I18nErrorNoPermission)
|
2022-04-25 13:49:11 +00:00
|
|
|
}
|
|
|
|
if _, ok := user.Permissions["/"]; !ok {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(util.NewValidationError("permissions for the root dir \"/\" must be set"), util.I18nErrorNoRootPermission)
|
2022-04-25 13:49:11 +00:00
|
|
|
}
|
|
|
|
permissions, err := validateUserPermissions(user.Permissions)
|
|
|
|
if err != nil {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(err, util.I18nErrorGenericPermission)
|
2022-04-25 13:49:11 +00:00
|
|
|
}
|
2019-12-25 17:20:19 +00:00
|
|
|
user.Permissions = permissions
|
2019-10-07 16:19:01 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-12-30 17:37:50 +00:00
|
|
|
func validatePublicKeys(user *User) error {
|
|
|
|
if len(user.PublicKeys) == 0 {
|
|
|
|
user.PublicKeys = []string{}
|
|
|
|
}
|
2021-05-22 07:54:27 +00:00
|
|
|
var validatedKeys []string
|
2024-02-25 10:12:57 +00:00
|
|
|
for idx, key := range user.PublicKeys {
|
|
|
|
if key == "" {
|
2021-05-22 07:54:27 +00:00
|
|
|
continue
|
|
|
|
}
|
2024-02-25 10:12:57 +00:00
|
|
|
out, _, _, _, err := ssh.ParseAuthorizedKey([]byte(key))
|
2019-12-30 17:37:50 +00:00
|
|
|
if err != nil {
|
2024-02-25 10:12:57 +00:00
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError(fmt.Sprintf("error parsing public key at position %d: %v", idx, err)),
|
|
|
|
util.I18nErrorPubKeyInvalid,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
if k, ok := out.(ssh.CryptoPublicKey); ok {
|
|
|
|
cryptoKey := k.CryptoPublicKey()
|
|
|
|
if rsaKey, ok := cryptoKey.(*rsa.PublicKey); ok {
|
|
|
|
if size := rsaKey.N.BitLen(); size < 2048 {
|
|
|
|
providerLog(logger.LevelError, "rsa key with size %d not accepted, minimum 2048", size)
|
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError(fmt.Sprintf("invalid size %d for rsa key at position %d, minimum 2048",
|
|
|
|
size, idx)),
|
|
|
|
util.I18nErrorKeySizeInvalid,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
2019-12-30 17:37:50 +00:00
|
|
|
}
|
2024-02-25 10:12:57 +00:00
|
|
|
|
|
|
|
validatedKeys = append(validatedKeys, key)
|
2019-12-30 17:37:50 +00:00
|
|
|
}
|
2022-05-31 16:22:18 +00:00
|
|
|
user.PublicKeys = util.RemoveDuplicates(validatedKeys, false)
|
2019-12-30 17:37:50 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-04-25 13:49:11 +00:00
|
|
|
func validateFiltersPatternExtensions(baseFilters *sdk.BaseUserFilters) error {
|
|
|
|
if len(baseFilters.FilePatterns) == 0 {
|
|
|
|
baseFilters.FilePatterns = []sdk.PatternsFilter{}
|
2020-11-15 21:04:48 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
filteredPaths := []string{}
|
2021-07-11 13:26:51 +00:00
|
|
|
var filters []sdk.PatternsFilter
|
2022-04-25 13:49:11 +00:00
|
|
|
for _, f := range baseFilters.FilePatterns {
|
2020-11-15 21:04:48 +00:00
|
|
|
cleanedPath := filepath.ToSlash(path.Clean(f.Path))
|
|
|
|
if !path.IsAbs(cleanedPath) {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError(fmt.Sprintf("invalid path %q for file patterns filter", f.Path)),
|
|
|
|
util.I18nErrorFilePatternPathInvalid,
|
|
|
|
)
|
2020-11-15 21:04:48 +00:00
|
|
|
}
|
2024-07-24 16:27:13 +00:00
|
|
|
if slices.Contains(filteredPaths, cleanedPath) {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError(fmt.Sprintf("duplicate file patterns filter for path %q", f.Path)),
|
|
|
|
util.I18nErrorFilePatternDuplicated,
|
|
|
|
)
|
2020-11-15 21:04:48 +00:00
|
|
|
}
|
|
|
|
if len(f.AllowedPatterns) == 0 && len(f.DeniedPatterns) == 0 {
|
2023-02-26 14:15:34 +00:00
|
|
|
return util.NewValidationError(fmt.Sprintf("empty file patterns filter for path %q", f.Path))
|
2020-11-15 21:04:48 +00:00
|
|
|
}
|
2022-01-15 16:16:49 +00:00
|
|
|
if f.DenyPolicy < sdk.DenyPolicyDefault || f.DenyPolicy > sdk.DenyPolicyHide {
|
2023-02-26 14:15:34 +00:00
|
|
|
return util.NewValidationError(fmt.Sprintf("invalid deny policy %v for path %q", f.DenyPolicy, f.Path))
|
2022-01-15 16:16:49 +00:00
|
|
|
}
|
2020-11-15 21:04:48 +00:00
|
|
|
f.Path = cleanedPath
|
|
|
|
allowed := make([]string, 0, len(f.AllowedPatterns))
|
|
|
|
denied := make([]string, 0, len(f.DeniedPatterns))
|
|
|
|
for _, pattern := range f.AllowedPatterns {
|
|
|
|
_, err := path.Match(pattern, "abc")
|
|
|
|
if err != nil {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError(fmt.Sprintf("invalid file pattern filter %q", pattern)),
|
|
|
|
util.I18nErrorFilePatternInvalid,
|
|
|
|
)
|
2020-11-15 21:04:48 +00:00
|
|
|
}
|
|
|
|
allowed = append(allowed, strings.ToLower(pattern))
|
|
|
|
}
|
|
|
|
for _, pattern := range f.DeniedPatterns {
|
|
|
|
_, err := path.Match(pattern, "abc")
|
|
|
|
if err != nil {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError(fmt.Sprintf("invalid file pattern filter %q", pattern)),
|
|
|
|
util.I18nErrorFilePatternInvalid,
|
|
|
|
)
|
2020-11-15 21:04:48 +00:00
|
|
|
}
|
|
|
|
denied = append(denied, strings.ToLower(pattern))
|
|
|
|
}
|
2022-05-31 16:22:18 +00:00
|
|
|
f.AllowedPatterns = util.RemoveDuplicates(allowed, false)
|
|
|
|
f.DeniedPatterns = util.RemoveDuplicates(denied, false)
|
2020-11-15 21:04:48 +00:00
|
|
|
filters = append(filters, f)
|
|
|
|
filteredPaths = append(filteredPaths, cleanedPath)
|
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
baseFilters.FilePatterns = filters
|
2020-11-15 21:04:48 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-04-25 13:49:11 +00:00
|
|
|
func checkEmptyFiltersStruct(filters *sdk.BaseUserFilters) {
|
|
|
|
if len(filters.AllowedIP) == 0 {
|
|
|
|
filters.AllowedIP = []string{}
|
2019-12-30 17:37:50 +00:00
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
if len(filters.DeniedIP) == 0 {
|
|
|
|
filters.DeniedIP = []string{}
|
2019-12-30 17:37:50 +00:00
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
if len(filters.DeniedLoginMethods) == 0 {
|
|
|
|
filters.DeniedLoginMethods = []string{}
|
2020-02-19 21:39:30 +00:00
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
if len(filters.DeniedProtocols) == 0 {
|
|
|
|
filters.DeniedProtocols = []string{}
|
2020-08-17 10:49:20 +00:00
|
|
|
}
|
2021-02-28 11:10:40 +00:00
|
|
|
}
|
|
|
|
|
2022-04-25 13:49:11 +00:00
|
|
|
func validateIPFilters(filters *sdk.BaseUserFilters) error {
|
2022-05-31 16:22:18 +00:00
|
|
|
filters.DeniedIP = util.RemoveDuplicates(filters.DeniedIP, false)
|
2022-04-25 13:49:11 +00:00
|
|
|
for _, IPMask := range filters.DeniedIP {
|
2019-12-30 17:37:50 +00:00
|
|
|
_, _, err := net.ParseCIDR(IPMask)
|
|
|
|
if err != nil {
|
2023-02-26 14:15:34 +00:00
|
|
|
return util.NewValidationError(fmt.Sprintf("could not parse denied IP/Mask %q: %v", IPMask, err))
|
2019-12-30 17:37:50 +00:00
|
|
|
}
|
|
|
|
}
|
2022-05-31 16:22:18 +00:00
|
|
|
filters.AllowedIP = util.RemoveDuplicates(filters.AllowedIP, false)
|
2022-04-25 13:49:11 +00:00
|
|
|
for _, IPMask := range filters.AllowedIP {
|
2019-12-30 17:37:50 +00:00
|
|
|
_, _, err := net.ParseCIDR(IPMask)
|
|
|
|
if err != nil {
|
2023-02-26 14:15:34 +00:00
|
|
|
return util.NewValidationError(fmt.Sprintf("could not parse allowed IP/Mask %q: %v", IPMask, err))
|
2019-12-30 17:37:50 +00:00
|
|
|
}
|
|
|
|
}
|
2021-12-10 17:43:26 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-01-02 14:16:35 +00:00
|
|
|
func validateBandwidthLimit(bl sdk.BandwidthLimit) error {
|
2022-01-30 10:42:36 +00:00
|
|
|
if len(bl.Sources) == 0 {
|
|
|
|
return util.NewValidationError("no bandwidth limit source specified")
|
|
|
|
}
|
2022-01-02 14:16:35 +00:00
|
|
|
for _, source := range bl.Sources {
|
|
|
|
_, _, err := net.ParseCIDR(source)
|
|
|
|
if err != nil {
|
2023-02-26 14:15:34 +00:00
|
|
|
return util.NewValidationError(fmt.Sprintf("could not parse bandwidth limit source %q: %v", source, err))
|
2022-01-02 14:16:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-04-25 13:49:11 +00:00
|
|
|
func validateBandwidthLimitsFilter(filters *sdk.BaseUserFilters) error {
|
|
|
|
for idx, bandwidthLimit := range filters.BandwidthLimits {
|
2022-01-02 14:16:35 +00:00
|
|
|
if err := validateBandwidthLimit(bandwidthLimit); err != nil {
|
2021-12-10 17:43:26 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
if bandwidthLimit.DownloadBandwidth < 0 {
|
2022-04-25 13:49:11 +00:00
|
|
|
filters.BandwidthLimits[idx].DownloadBandwidth = 0
|
2021-12-10 17:43:26 +00:00
|
|
|
}
|
|
|
|
if bandwidthLimit.UploadBandwidth < 0 {
|
2022-04-25 13:49:11 +00:00
|
|
|
filters.BandwidthLimits[idx].UploadBandwidth = 0
|
2021-12-10 17:43:26 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-04-25 13:49:11 +00:00
|
|
|
func updateFiltersValues(filters *sdk.BaseUserFilters) {
|
|
|
|
if filters.StartDirectory != "" {
|
|
|
|
filters.StartDirectory = util.CleanPath(filters.StartDirectory)
|
|
|
|
if filters.StartDirectory == "/" {
|
|
|
|
filters.StartDirectory = ""
|
2022-03-03 11:44:56 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-25 13:49:11 +00:00
|
|
|
func validateFilterProtocols(filters *sdk.BaseUserFilters) error {
|
|
|
|
if len(filters.DeniedProtocols) >= len(ValidProtocols) {
|
2022-03-06 15:57:13 +00:00
|
|
|
return util.NewValidationError("invalid denied_protocols")
|
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
for _, p := range filters.DeniedProtocols {
|
2024-07-24 16:27:13 +00:00
|
|
|
if !slices.Contains(ValidProtocols, p) {
|
2023-02-26 14:15:34 +00:00
|
|
|
return util.NewValidationError(fmt.Sprintf("invalid denied protocol %q", p))
|
2022-03-06 15:57:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-25 13:49:11 +00:00
|
|
|
for _, p := range filters.TwoFactorAuthProtocols {
|
2024-07-24 16:27:13 +00:00
|
|
|
if !slices.Contains(MFAProtocols, p) {
|
2023-02-26 14:15:34 +00:00
|
|
|
return util.NewValidationError(fmt.Sprintf("invalid two factor protocol %q", p))
|
2022-03-06 15:57:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-05-03 16:30:03 +00:00
|
|
|
func validateTLSCerts(certs []string) ([]string, error) {
|
|
|
|
var validateCerts []string
|
2024-01-14 20:36:23 +00:00
|
|
|
for idx, cert := range certs {
|
2024-05-03 16:30:03 +00:00
|
|
|
if cert == "" {
|
|
|
|
continue
|
|
|
|
}
|
2024-01-14 20:36:23 +00:00
|
|
|
derBlock, _ := pem.Decode([]byte(cert))
|
|
|
|
if derBlock == nil {
|
2024-05-03 16:30:03 +00:00
|
|
|
return nil, util.NewI18nError(
|
2024-01-14 20:36:23 +00:00
|
|
|
util.NewValidationError(fmt.Sprintf("invalid TLS certificate %d", idx)),
|
|
|
|
util.I18nErrorInvalidTLSCert,
|
|
|
|
)
|
|
|
|
}
|
2024-05-03 16:30:03 +00:00
|
|
|
crt, err := x509.ParseCertificate(derBlock.Bytes)
|
2024-02-25 10:12:57 +00:00
|
|
|
if err != nil {
|
2024-05-03 16:30:03 +00:00
|
|
|
return nil, util.NewI18nError(
|
2024-01-14 20:36:23 +00:00
|
|
|
util.NewValidationError(fmt.Sprintf("error parsing TLS certificate %d", idx)),
|
|
|
|
util.I18nErrorInvalidTLSCert,
|
|
|
|
)
|
|
|
|
}
|
2024-05-03 16:30:03 +00:00
|
|
|
if crt.PublicKeyAlgorithm == x509.RSA {
|
|
|
|
if rsaCert, ok := crt.PublicKey.(*rsa.PublicKey); ok {
|
2024-02-25 10:12:57 +00:00
|
|
|
if size := rsaCert.N.BitLen(); size < 2048 {
|
|
|
|
providerLog(logger.LevelError, "rsa cert with size %d not accepted, minimum 2048", size)
|
2024-05-03 16:30:03 +00:00
|
|
|
return nil, util.NewI18nError(
|
2024-02-25 10:12:57 +00:00
|
|
|
util.NewValidationError(fmt.Sprintf("invalid size %d for rsa cert at position %d, minimum 2048",
|
|
|
|
size, idx)),
|
|
|
|
util.I18nErrorKeySizeInvalid,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-05-03 16:30:03 +00:00
|
|
|
validateCerts = append(validateCerts, cert)
|
2024-01-14 20:36:23 +00:00
|
|
|
}
|
2024-05-03 16:30:03 +00:00
|
|
|
return validateCerts, nil
|
2024-01-14 20:36:23 +00:00
|
|
|
}
|
|
|
|
|
2022-04-25 13:49:11 +00:00
|
|
|
func validateBaseFilters(filters *sdk.BaseUserFilters) error {
|
|
|
|
checkEmptyFiltersStruct(filters)
|
|
|
|
if err := validateIPFilters(filters); err != nil {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(err, util.I18nErrorIPFiltersInvalid)
|
2021-12-10 17:43:26 +00:00
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
if err := validateBandwidthLimitsFilter(filters); err != nil {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(err, util.I18nErrorSourceBWLimitInvalid)
|
2022-01-30 10:42:36 +00:00
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
if len(filters.DeniedLoginMethods) >= len(ValidLoginMethods) {
|
2021-07-11 13:26:51 +00:00
|
|
|
return util.NewValidationError("invalid denied_login_methods")
|
2020-02-19 21:39:30 +00:00
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
for _, loginMethod := range filters.DeniedLoginMethods {
|
2024-07-24 16:27:13 +00:00
|
|
|
if !slices.Contains(ValidLoginMethods, loginMethod) {
|
2023-02-26 14:15:34 +00:00
|
|
|
return util.NewValidationError(fmt.Sprintf("invalid login method: %q", loginMethod))
|
2020-02-19 21:39:30 +00:00
|
|
|
}
|
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
if err := validateFilterProtocols(filters); err != nil {
|
2022-03-06 15:57:13 +00:00
|
|
|
return err
|
2020-08-17 10:49:20 +00:00
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
if filters.TLSUsername != "" {
|
2024-07-24 16:27:13 +00:00
|
|
|
if !slices.Contains(validTLSUsernames, string(filters.TLSUsername)) {
|
2023-02-26 14:15:34 +00:00
|
|
|
return util.NewValidationError(fmt.Sprintf("invalid TLS username: %q", filters.TLSUsername))
|
2021-02-28 11:10:40 +00:00
|
|
|
}
|
|
|
|
}
|
2024-05-03 16:30:03 +00:00
|
|
|
certs, err := validateTLSCerts(filters.TLSCerts)
|
|
|
|
if err != nil {
|
2024-01-14 20:36:23 +00:00
|
|
|
return err
|
|
|
|
}
|
2024-05-03 16:30:03 +00:00
|
|
|
filters.TLSCerts = certs
|
2022-04-25 13:49:11 +00:00
|
|
|
for _, opts := range filters.WebClient {
|
2024-07-24 16:27:13 +00:00
|
|
|
if !slices.Contains(sdk.WebClientOptions, opts) {
|
2023-02-26 14:15:34 +00:00
|
|
|
return util.NewValidationError(fmt.Sprintf("invalid web client options %q", opts))
|
2021-05-06 19:35:43 +00:00
|
|
|
}
|
|
|
|
}
|
2023-08-07 17:07:20 +00:00
|
|
|
if filters.MaxSharesExpiration > 0 && filters.MaxSharesExpiration < filters.DefaultSharesExpiration {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError(fmt.Sprintf("default shares expiration: %d must be less than or equal to max shares expiration: %d",
|
|
|
|
filters.DefaultSharesExpiration, filters.MaxSharesExpiration)),
|
|
|
|
util.I18nErrorShareExpirationInvalid,
|
|
|
|
)
|
2023-08-07 17:07:20 +00:00
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
updateFiltersValues(filters)
|
2021-12-10 17:43:26 +00:00
|
|
|
|
2024-03-17 10:30:03 +00:00
|
|
|
if err := validateAccessTimeFilters(filters); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-04-25 13:49:11 +00:00
|
|
|
return validateFiltersPatternExtensions(filters)
|
2019-12-30 17:37:50 +00:00
|
|
|
}
|
|
|
|
|
2024-03-17 10:30:03 +00:00
|
|
|
func isTimeOfDayValid(value string) bool {
|
|
|
|
if len(value) != 5 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
parts := strings.Split(value, ":")
|
|
|
|
if len(parts) != 2 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
hour, err := strconv.Atoi(parts[0])
|
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if hour < 0 || hour > 23 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
minute, err := strconv.Atoi(parts[1])
|
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if minute < 0 || minute > 59 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
func validateAccessTimeFilters(filters *sdk.BaseUserFilters) error {
|
|
|
|
for _, period := range filters.AccessTime {
|
|
|
|
if period.DayOfWeek < int(time.Sunday) || period.DayOfWeek > int(time.Saturday) {
|
|
|
|
return util.NewValidationError(fmt.Sprintf("invalid day of week: %d", period.DayOfWeek))
|
|
|
|
}
|
|
|
|
if !isTimeOfDayValid(period.From) || !isTimeOfDayValid(period.To) {
|
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError("invalid time of day. Supported format: HH:MM"),
|
|
|
|
util.I18nErrorTimeOfDayInvalid,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
if period.To <= period.From {
|
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError("invalid time of day. The end time cannot be earlier than the start time"),
|
|
|
|
util.I18nErrorTimeOfDayConflict,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-12-11 16:15:34 +00:00
|
|
|
func validateCombinedUserFilters(user *User) error {
|
2024-07-24 16:27:13 +00:00
|
|
|
if user.Filters.TOTPConfig.Enabled && slices.Contains(user.Filters.WebClient, sdk.WebClientMFADisabled) {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError("two-factor authentication cannot be disabled for a user with an active configuration"),
|
|
|
|
util.I18nErrorDisableActive2FA,
|
|
|
|
)
|
2022-12-11 16:15:34 +00:00
|
|
|
}
|
2024-07-24 16:27:13 +00:00
|
|
|
if user.Filters.RequirePasswordChange && slices.Contains(user.Filters.WebClient, sdk.WebClientPasswordChangeDisabled) {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError("you cannot require password change and at the same time disallow it"),
|
|
|
|
util.I18nErrorPwdChangeConflict,
|
|
|
|
)
|
2022-12-11 16:15:34 +00:00
|
|
|
}
|
2024-07-24 16:27:13 +00:00
|
|
|
if len(user.Filters.TwoFactorAuthProtocols) > 0 && slices.Contains(user.Filters.WebClient, sdk.WebClientMFADisabled) {
|
2024-02-22 17:20:51 +00:00
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError("you cannot require two-factor authentication and at the same time disallow it"),
|
|
|
|
util.I18nError2FAConflict,
|
|
|
|
)
|
|
|
|
}
|
2022-12-11 16:15:34 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-01-31 22:26:56 +00:00
|
|
|
func validateBaseParams(user *User) error {
|
2020-09-18 17:21:24 +00:00
|
|
|
if user.Username == "" {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(util.NewValidationError("username is mandatory"), util.I18nErrorUsernameRequired)
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
2022-09-13 16:04:27 +00:00
|
|
|
if err := checkReservedUsernames(user.Username); err != nil {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(err, util.I18nErrorReservedUsername)
|
2022-09-13 16:04:27 +00:00
|
|
|
}
|
2022-05-27 05:39:55 +00:00
|
|
|
if user.Email != "" && !util.IsEmailValid(user.Email) {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError(fmt.Sprintf("email %q is not valid", user.Email)),
|
|
|
|
util.I18nErrorInvalidEmail,
|
|
|
|
)
|
2021-09-25 17:06:13 +00:00
|
|
|
}
|
2022-01-31 17:01:37 +00:00
|
|
|
if config.NamingRules&1 == 0 && !usernameRegex.MatchString(user.Username) {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError(fmt.Sprintf("username %q is not valid, the following characters are allowed: a-zA-Z0-9-_.~", user.Username)),
|
|
|
|
util.I18nErrorInvalidUser,
|
|
|
|
)
|
2021-01-17 21:29:08 +00:00
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
if user.hasRedactedSecret() {
|
|
|
|
return util.NewValidationError("cannot save a user with a redacted secret")
|
|
|
|
}
|
2020-09-18 17:21:24 +00:00
|
|
|
if user.HomeDir == "" {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(util.NewValidationError("home_dir is mandatory"), util.I18nErrorHomeRequired)
|
2020-09-18 17:21:24 +00:00
|
|
|
}
|
2022-03-31 16:16:50 +00:00
|
|
|
// we can have users with no passwords and public keys, they can authenticate via SSH user certs or OIDC
|
|
|
|
/*if user.Password == "" && len(user.PublicKeys) == 0 {
|
2021-07-11 13:26:51 +00:00
|
|
|
return util.NewValidationError("please set a password or at least a public_key")
|
2022-03-31 16:16:50 +00:00
|
|
|
}*/
|
2019-07-20 10:26:52 +00:00
|
|
|
if !filepath.IsAbs(user.HomeDir) {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError(fmt.Sprintf("home_dir must be an absolute path, actual value: %v", user.HomeDir)),
|
|
|
|
util.I18nErrorHomeInvalid,
|
|
|
|
)
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
2021-12-10 17:43:26 +00:00
|
|
|
if user.DownloadBandwidth < 0 {
|
|
|
|
user.DownloadBandwidth = 0
|
|
|
|
}
|
|
|
|
if user.UploadBandwidth < 0 {
|
|
|
|
user.UploadBandwidth = 0
|
|
|
|
}
|
2022-01-30 10:42:36 +00:00
|
|
|
if user.TotalDataTransfer > 0 {
|
|
|
|
// if a total data transfer is defined we reset the separate upload and download limits
|
|
|
|
user.UploadDataTransfer = 0
|
|
|
|
user.DownloadDataTransfer = 0
|
|
|
|
}
|
2022-07-27 16:54:25 +00:00
|
|
|
if user.Filters.IsAnonymous {
|
|
|
|
user.setAnonymousSettings()
|
|
|
|
}
|
2023-12-10 15:40:13 +00:00
|
|
|
err := user.FsConfig.Validate(user.GetEncryptionAdditionalData())
|
|
|
|
if err != nil {
|
2024-01-11 18:26:13 +00:00
|
|
|
return err
|
2023-12-10 15:40:13 +00:00
|
|
|
}
|
|
|
|
return nil
|
2020-01-31 22:26:56 +00:00
|
|
|
}
|
|
|
|
|
2022-04-02 20:20:21 +00:00
|
|
|
func hashPlainPassword(plainPwd string) (string, error) {
|
|
|
|
if config.PasswordHashing.Algo == HashingAlgoBcrypt {
|
|
|
|
pwd, err := bcrypt.GenerateFromPassword([]byte(plainPwd), config.PasswordHashing.BcryptOptions.Cost)
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("bcrypt hashing error: %w", err)
|
|
|
|
}
|
2024-05-08 17:01:58 +00:00
|
|
|
return util.BytesToString(pwd), nil
|
2022-04-02 20:20:21 +00:00
|
|
|
}
|
|
|
|
pwd, err := argon2id.CreateHash(plainPwd, argon2Params)
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("argon2ID hashing error: %w", err)
|
|
|
|
}
|
|
|
|
return pwd, nil
|
|
|
|
}
|
|
|
|
|
2020-03-22 13:03:06 +00:00
|
|
|
func createUserPasswordHash(user *User) error {
|
2021-02-15 18:38:53 +00:00
|
|
|
if user.Password != "" && !user.IsPasswordHashed() {
|
2023-03-02 08:11:30 +00:00
|
|
|
if minEntropy := user.getMinPasswordEntropy(); minEntropy > 0 {
|
|
|
|
if err := passwordvalidator.Validate(user.Password, minEntropy); err != nil {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(util.NewValidationError(err.Error()), util.I18nErrorPasswordComplexity)
|
2021-08-06 16:56:07 +00:00
|
|
|
}
|
|
|
|
}
|
2022-04-02 20:20:21 +00:00
|
|
|
hashedPwd, err := hashPlainPassword(user.Password)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2020-03-22 13:03:06 +00:00
|
|
|
}
|
2022-04-02 20:20:21 +00:00
|
|
|
user.Password = hashedPwd
|
2022-12-11 16:15:34 +00:00
|
|
|
user.LastPasswordChange = util.GetTimeAsMsSinceEpoch(time.Now())
|
2020-03-22 13:03:06 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-02-04 18:09:43 +00:00
|
|
|
// ValidateFolder returns an error if the folder is not valid
|
|
|
|
// FIXME: this should be defined as Folder struct method
|
|
|
|
func ValidateFolder(folder *vfs.BaseVirtualFolder) error {
|
2021-08-19 09:28:53 +00:00
|
|
|
folder.FsConfig.SetEmptySecretsIfNil()
|
2024-08-17 07:11:42 +00:00
|
|
|
if fnPreFolderValidation != nil {
|
|
|
|
fnPreFolderValidation(folder)
|
|
|
|
}
|
2021-02-01 18:04:15 +00:00
|
|
|
if folder.Name == "" {
|
2024-01-11 18:26:13 +00:00
|
|
|
return util.NewI18nError(util.NewValidationError("folder name is mandatory"), util.I18nErrorNameRequired)
|
2021-02-01 18:04:15 +00:00
|
|
|
}
|
2022-01-31 17:01:37 +00:00
|
|
|
if config.NamingRules&1 == 0 && !usernameRegex.MatchString(folder.Name) {
|
2024-01-11 18:26:13 +00:00
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError(fmt.Sprintf("folder name %q is not valid, the following characters are allowed: a-zA-Z0-9-_.~", folder.Name)),
|
|
|
|
util.I18nErrorInvalidName,
|
|
|
|
)
|
2021-02-01 18:04:15 +00:00
|
|
|
}
|
2021-07-11 13:26:51 +00:00
|
|
|
if folder.FsConfig.Provider == sdk.LocalFilesystemProvider || folder.FsConfig.Provider == sdk.CryptedFilesystemProvider ||
|
2021-03-21 18:15:47 +00:00
|
|
|
folder.MappedPath != "" {
|
|
|
|
cleanedMPath := filepath.Clean(folder.MappedPath)
|
|
|
|
if !filepath.IsAbs(cleanedMPath) {
|
2024-01-11 18:26:13 +00:00
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError(fmt.Sprintf("invalid folder mapped path %q", folder.MappedPath)),
|
|
|
|
util.I18nErrorInvalidHomeDir,
|
|
|
|
)
|
2021-03-21 18:15:47 +00:00
|
|
|
}
|
|
|
|
folder.MappedPath = cleanedMPath
|
|
|
|
}
|
|
|
|
if folder.HasRedactedSecret() {
|
|
|
|
return errors.New("cannot save a folder with a redacted secret")
|
|
|
|
}
|
2022-04-28 10:55:01 +00:00
|
|
|
return folder.FsConfig.Validate(folder.GetEncryptionAdditionalData())
|
2020-06-07 21:30:18 +00:00
|
|
|
}
|
|
|
|
|
2021-01-25 20:31:33 +00:00
|
|
|
// ValidateUser returns an error if the user is not valid
|
|
|
|
// FIXME: this should be defined as User struct method
|
|
|
|
func ValidateUser(user *User) error {
|
2022-04-12 17:31:25 +00:00
|
|
|
user.OIDCCustomFields = nil
|
2023-04-06 16:22:09 +00:00
|
|
|
user.HasPassword = false
|
2020-11-30 20:46:34 +00:00
|
|
|
user.SetEmptySecretsIfNil()
|
2024-08-17 07:11:42 +00:00
|
|
|
if fnPreUserValidation != nil {
|
|
|
|
fnPreUserValidation(user)
|
|
|
|
}
|
2020-01-31 22:26:56 +00:00
|
|
|
buildUserHomeDir(user)
|
|
|
|
if err := validateBaseParams(user); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
if err := validateUserGroups(user); err != nil {
|
2019-10-07 16:19:01 +00:00
|
|
|
return err
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
if err := validatePermissions(user); err != nil {
|
|
|
|
return err
|
2021-09-04 10:11:04 +00:00
|
|
|
}
|
2021-09-05 12:10:12 +00:00
|
|
|
if err := validateUserTOTPConfig(&user.Filters.TOTPConfig, user.Username); err != nil {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(err, util.I18nError2FAInvalid)
|
2021-09-04 10:11:04 +00:00
|
|
|
}
|
|
|
|
if err := validateUserRecoveryCodes(user); err != nil {
|
2023-12-10 15:40:13 +00:00
|
|
|
return util.NewI18nError(err, util.I18nErrorRecoveryCodesInvalid)
|
2021-03-21 18:15:47 +00:00
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
vfolders, err := validateAssociatedVirtualFolders(user.VirtualFolders)
|
|
|
|
if err != nil {
|
2020-02-23 10:30:26 +00:00
|
|
|
return err
|
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
user.VirtualFolders = vfolders
|
2019-11-13 10:36:21 +00:00
|
|
|
if user.Status < 0 || user.Status > 1 {
|
2021-07-11 13:26:51 +00:00
|
|
|
return util.NewValidationError(fmt.Sprintf("invalid user status: %v", user.Status))
|
2019-11-13 10:36:21 +00:00
|
|
|
}
|
2020-03-22 13:03:06 +00:00
|
|
|
if err := createUserPasswordHash(user); err != nil {
|
|
|
|
return err
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
2019-12-30 17:37:50 +00:00
|
|
|
if err := validatePublicKeys(user); err != nil {
|
2024-02-25 10:12:57 +00:00
|
|
|
return err
|
2019-12-29 16:21:25 +00:00
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
if err := validateBaseFilters(&user.Filters.BaseUserFilters); err != nil {
|
2019-12-30 17:37:50 +00:00
|
|
|
return err
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
if !user.HasExternalAuth() {
|
|
|
|
user.Filters.ExternalAuthCacheTime = 0
|
|
|
|
}
|
2022-12-11 16:15:34 +00:00
|
|
|
return validateCombinedUserFilters(user)
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
2020-08-19 17:36:12 +00:00
|
|
|
func isPasswordOK(user *User, password string) (bool, error) {
|
2021-04-20 07:39:36 +00:00
|
|
|
if config.PasswordCaching {
|
2023-04-13 16:23:42 +00:00
|
|
|
found, match := cachedUserPasswords.Check(user.Username, password, user.Password)
|
2021-04-20 07:39:36 +00:00
|
|
|
if found {
|
|
|
|
return match, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-29 06:43:59 +00:00
|
|
|
match := false
|
2022-04-02 20:20:21 +00:00
|
|
|
updatePwd := true
|
2020-08-19 17:36:12 +00:00
|
|
|
var err error
|
2024-04-18 16:23:16 +00:00
|
|
|
|
|
|
|
switch {
|
|
|
|
case strings.HasPrefix(user.Password, bcryptPwdPrefix):
|
|
|
|
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
|
2021-08-17 16:08:32 +00:00
|
|
|
return match, ErrInvalidCredentials
|
|
|
|
}
|
|
|
|
match = true
|
2022-04-02 20:20:21 +00:00
|
|
|
updatePwd = config.PasswordHashing.Algo != HashingAlgoBcrypt
|
2024-04-18 16:23:16 +00:00
|
|
|
case strings.HasPrefix(user.Password, argonPwdPrefix):
|
2019-08-12 16:31:31 +00:00
|
|
|
match, err = argon2id.ComparePasswordAndHash(password, user.Password)
|
|
|
|
if err != nil {
|
2021-12-16 18:53:00 +00:00
|
|
|
providerLog(logger.LevelError, "error comparing password with argon hash: %v", err)
|
2020-08-19 17:36:12 +00:00
|
|
|
return match, err
|
2019-08-12 16:31:31 +00:00
|
|
|
}
|
2022-04-02 20:20:21 +00:00
|
|
|
updatePwd = config.PasswordHashing.Algo != HashingAlgoArgon2ID
|
2024-04-18 16:23:16 +00:00
|
|
|
case util.IsStringPrefixInSlice(user.Password, unixPwdPrefixes):
|
2023-03-26 08:33:30 +00:00
|
|
|
match, err = compareUnixPasswordAndHash(user, password)
|
2019-08-17 13:20:49 +00:00
|
|
|
if err != nil {
|
2020-08-19 17:36:12 +00:00
|
|
|
return match, err
|
2019-08-17 13:20:49 +00:00
|
|
|
}
|
2024-04-18 16:23:16 +00:00
|
|
|
case util.IsStringPrefixInSlice(user.Password, pbkdfPwdPrefixes):
|
2023-03-26 08:33:30 +00:00
|
|
|
match, err = comparePbkdf2PasswordAndHash(password, user.Password)
|
2019-12-29 06:43:59 +00:00
|
|
|
if err != nil {
|
2020-08-19 17:36:12 +00:00
|
|
|
return match, err
|
2019-09-15 06:34:44 +00:00
|
|
|
}
|
2024-04-18 16:23:16 +00:00
|
|
|
case util.IsStringPrefixInSlice(user.Password, digestPwdPrefixes):
|
2023-06-03 14:58:45 +00:00
|
|
|
match = compareDigestPasswordAndHash(user, password)
|
2019-08-12 16:31:31 +00:00
|
|
|
}
|
2024-04-18 16:23:16 +00:00
|
|
|
|
2021-04-20 07:39:36 +00:00
|
|
|
if err == nil && match {
|
2023-04-13 16:23:42 +00:00
|
|
|
cachedUserPasswords.Add(user.Username, password, user.Password)
|
2022-04-02 20:20:21 +00:00
|
|
|
if updatePwd {
|
|
|
|
convertUserPassword(user.Username, password)
|
|
|
|
}
|
2021-04-20 07:39:36 +00:00
|
|
|
}
|
2020-08-19 17:36:12 +00:00
|
|
|
return match, err
|
|
|
|
}
|
|
|
|
|
2022-04-02 20:20:21 +00:00
|
|
|
func convertUserPassword(username, plainPwd string) {
|
|
|
|
hashedPwd, err := hashPlainPassword(plainPwd)
|
|
|
|
if err == nil {
|
|
|
|
err = provider.updateUserPassword(username, hashedPwd)
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
providerLog(logger.LevelWarn, "unable to convert password for user %s: %v", username, err)
|
|
|
|
} else {
|
|
|
|
providerLog(logger.LevelDebug, "password converted for user %s", username)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-28 11:10:40 +00:00
|
|
|
func checkUserAndTLSCertificate(user *User, protocol string, tlsCert *x509.Certificate) (User, error) {
|
2022-04-25 13:49:11 +00:00
|
|
|
err := user.LoadAndApplyGroupSettings()
|
|
|
|
if err != nil {
|
|
|
|
return *user, err
|
|
|
|
}
|
|
|
|
err = user.CheckLoginConditions()
|
2021-02-28 11:10:40 +00:00
|
|
|
if err != nil {
|
|
|
|
return *user, err
|
|
|
|
}
|
|
|
|
switch protocol {
|
2021-09-04 10:11:04 +00:00
|
|
|
case protocolFTP, protocolWebDAV:
|
2024-01-14 20:36:23 +00:00
|
|
|
for _, cert := range user.Filters.TLSCerts {
|
2024-05-12 16:10:03 +00:00
|
|
|
derBlock, _ := pem.Decode(util.StringToBytes(cert))
|
2024-01-14 20:36:23 +00:00
|
|
|
if derBlock != nil && bytes.Equal(derBlock.Bytes, tlsCert.Raw) {
|
|
|
|
return *user, nil
|
|
|
|
}
|
|
|
|
}
|
2021-07-11 13:26:51 +00:00
|
|
|
if user.Filters.TLSUsername == sdk.TLSUsernameCN {
|
2021-02-28 11:10:40 +00:00
|
|
|
if user.Username == tlsCert.Subject.CommonName {
|
|
|
|
return *user, nil
|
|
|
|
}
|
2023-02-26 14:15:34 +00:00
|
|
|
return *user, fmt.Errorf("CN %q does not match username %q", tlsCert.Subject.CommonName, user.Username)
|
2021-02-28 11:10:40 +00:00
|
|
|
}
|
|
|
|
return *user, errors.New("TLS certificate is not valid")
|
|
|
|
default:
|
|
|
|
return *user, fmt.Errorf("certificate authentication is not supported for protocol %v", protocol)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-16 18:11:36 +00:00
|
|
|
func checkUserAndPass(user *User, password, ip, protocol string) (User, error) {
|
2022-04-25 13:49:11 +00:00
|
|
|
err := user.LoadAndApplyGroupSettings()
|
|
|
|
if err != nil {
|
|
|
|
return *user, err
|
|
|
|
}
|
|
|
|
err = user.CheckLoginConditions()
|
2020-08-19 17:36:12 +00:00
|
|
|
if err != nil {
|
2021-02-16 18:11:36 +00:00
|
|
|
return *user, err
|
2020-08-19 17:36:12 +00:00
|
|
|
}
|
2022-12-11 16:15:34 +00:00
|
|
|
if protocol != protocolHTTP && user.MustChangePassword() {
|
|
|
|
return *user, errors.New("login not allowed, password change required")
|
|
|
|
}
|
2022-07-27 16:54:25 +00:00
|
|
|
if user.Filters.IsAnonymous {
|
|
|
|
user.setAnonymousSettings()
|
|
|
|
return *user, nil
|
|
|
|
}
|
2021-09-04 10:11:04 +00:00
|
|
|
password, err = checkUserPasscode(user, password, protocol)
|
|
|
|
if err != nil {
|
|
|
|
return *user, ErrInvalidCredentials
|
|
|
|
}
|
2022-07-27 16:54:25 +00:00
|
|
|
if user.Password == "" || password == "" {
|
2021-03-21 18:15:47 +00:00
|
|
|
return *user, errors.New("credentials cannot be null or empty")
|
2020-08-19 17:36:12 +00:00
|
|
|
}
|
2021-04-04 20:32:25 +00:00
|
|
|
if !user.Filters.Hooks.CheckPasswordDisabled {
|
|
|
|
hookResponse, err := executeCheckPasswordHook(user.Username, password, ip, protocol)
|
|
|
|
if err != nil {
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelDebug, "error executing check password hook for user %q, ip %v, protocol %v: %v",
|
2021-07-24 18:11:17 +00:00
|
|
|
user.Username, ip, protocol, err)
|
2021-04-04 20:32:25 +00:00
|
|
|
return *user, errors.New("unable to check credentials")
|
|
|
|
}
|
|
|
|
switch hookResponse.Status {
|
|
|
|
case -1:
|
|
|
|
// no hook configured
|
|
|
|
case 1:
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelDebug, "password accepted by check password hook for user %q, ip %v, protocol %v",
|
2021-07-24 18:11:17 +00:00
|
|
|
user.Username, ip, protocol)
|
2021-04-04 20:32:25 +00:00
|
|
|
return *user, nil
|
|
|
|
case 2:
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelDebug, "partial success from check password hook for user %q, ip %v, protocol %v",
|
2021-07-24 18:11:17 +00:00
|
|
|
user.Username, ip, protocol)
|
2021-04-04 20:32:25 +00:00
|
|
|
password = hookResponse.ToVerify
|
|
|
|
default:
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelDebug, "password rejected by check password hook for user %q, ip %v, protocol %v, status: %v",
|
2021-07-24 18:11:17 +00:00
|
|
|
user.Username, ip, protocol, hookResponse.Status)
|
2021-04-04 20:32:25 +00:00
|
|
|
return *user, ErrInvalidCredentials
|
|
|
|
}
|
2020-08-19 17:36:12 +00:00
|
|
|
}
|
|
|
|
|
2021-02-16 18:11:36 +00:00
|
|
|
match, err := isPasswordOK(user, password)
|
2019-08-12 16:31:31 +00:00
|
|
|
if !match {
|
2020-08-31 17:25:17 +00:00
|
|
|
err = ErrInvalidCredentials
|
2019-08-12 16:31:31 +00:00
|
|
|
}
|
2021-02-16 18:11:36 +00:00
|
|
|
return *user, err
|
2019-08-12 16:31:31 +00:00
|
|
|
}
|
|
|
|
|
2021-09-04 10:11:04 +00:00
|
|
|
func checkUserPasscode(user *User, password, protocol string) (string, error) {
|
|
|
|
if user.Filters.TOTPConfig.Enabled {
|
|
|
|
switch protocol {
|
|
|
|
case protocolFTP:
|
2024-07-24 16:27:13 +00:00
|
|
|
if slices.Contains(user.Filters.TOTPConfig.Protocols, protocol) {
|
2021-09-04 10:11:04 +00:00
|
|
|
// the TOTP passcode has six digits
|
|
|
|
pwdLen := len(password)
|
|
|
|
if pwdLen < 7 {
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelDebug, "password len %v is too short to contain a passcode, user %q, protocol %v",
|
2021-09-04 10:11:04 +00:00
|
|
|
pwdLen, user.Username, protocol)
|
|
|
|
return "", util.NewValidationError("password too short, cannot contain the passcode")
|
|
|
|
}
|
|
|
|
err := user.Filters.TOTPConfig.Secret.TryDecrypt()
|
|
|
|
if err != nil {
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelError, "unable to decrypt TOTP secret for user %q, protocol %v, err: %v",
|
2021-09-04 10:11:04 +00:00
|
|
|
user.Username, protocol, err)
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
pwd := password[0:(pwdLen - 6)]
|
|
|
|
passcode := password[(pwdLen - 6):]
|
|
|
|
match, err := mfa.ValidateTOTPPasscode(user.Filters.TOTPConfig.ConfigName, passcode,
|
|
|
|
user.Filters.TOTPConfig.Secret.GetPayload())
|
|
|
|
if !match || err != nil {
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelWarn, "invalid passcode for user %q, protocol %v, err: %v",
|
2021-09-04 10:11:04 +00:00
|
|
|
user.Username, protocol, err)
|
|
|
|
return "", util.NewValidationError("invalid passcode")
|
|
|
|
}
|
|
|
|
return pwd, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return password, nil
|
|
|
|
}
|
|
|
|
|
2022-03-31 16:16:50 +00:00
|
|
|
func checkUserAndPubKey(user *User, pubKey []byte, isSSHCert bool) (User, string, error) {
|
2022-04-25 13:49:11 +00:00
|
|
|
err := user.LoadAndApplyGroupSettings()
|
|
|
|
if err != nil {
|
|
|
|
return *user, "", err
|
|
|
|
}
|
|
|
|
err = user.CheckLoginConditions()
|
2019-11-13 10:36:21 +00:00
|
|
|
if err != nil {
|
2021-02-16 18:11:36 +00:00
|
|
|
return *user, "", err
|
2019-11-13 10:36:21 +00:00
|
|
|
}
|
2022-03-31 16:16:50 +00:00
|
|
|
if isSSHCert {
|
|
|
|
return *user, "", nil
|
|
|
|
}
|
2019-08-12 16:31:31 +00:00
|
|
|
if len(user.PublicKeys) == 0 {
|
2021-02-16 18:11:36 +00:00
|
|
|
return *user, "", ErrInvalidCredentials
|
2019-08-12 16:31:31 +00:00
|
|
|
}
|
2024-02-25 10:12:57 +00:00
|
|
|
for idx, key := range user.PublicKeys {
|
2024-05-12 16:10:03 +00:00
|
|
|
storedKey, comment, _, _, err := ssh.ParseAuthorizedKey(util.StringToBytes(key))
|
2019-08-12 16:31:31 +00:00
|
|
|
if err != nil {
|
2024-02-25 10:12:57 +00:00
|
|
|
providerLog(logger.LevelError, "error parsing stored public key %d for user %s: %v", idx, user.Username, err)
|
2021-02-16 18:11:36 +00:00
|
|
|
return *user, "", err
|
2019-08-12 16:31:31 +00:00
|
|
|
}
|
2024-02-25 10:12:57 +00:00
|
|
|
if bytes.Equal(storedKey.Marshal(), pubKey) {
|
|
|
|
return *user, fmt.Sprintf("%s:%s", ssh.FingerprintSHA256(storedKey), comment), nil
|
2019-08-12 16:31:31 +00:00
|
|
|
}
|
|
|
|
}
|
2021-02-16 18:11:36 +00:00
|
|
|
return *user, "", ErrInvalidCredentials
|
2019-08-12 16:31:31 +00:00
|
|
|
}
|
|
|
|
|
2023-06-03 14:58:45 +00:00
|
|
|
func compareDigestPasswordAndHash(user *User, password string) bool {
|
|
|
|
if strings.HasPrefix(user.Password, md5DigestPwdPrefix) {
|
|
|
|
h := md5.New()
|
|
|
|
h.Write([]byte(password))
|
|
|
|
return fmt.Sprintf("%s%x", md5DigestPwdPrefix, h.Sum(nil)) == user.Password
|
|
|
|
}
|
|
|
|
if strings.HasPrefix(user.Password, sha256DigestPwdPrefix) {
|
|
|
|
h := sha256.New()
|
|
|
|
h.Write([]byte(password))
|
|
|
|
return fmt.Sprintf("%s%x", sha256DigestPwdPrefix, h.Sum(nil)) == user.Password
|
|
|
|
}
|
|
|
|
if strings.HasPrefix(user.Password, sha512DigestPwdPrefix) {
|
|
|
|
h := sha512.New()
|
|
|
|
h.Write([]byte(password))
|
|
|
|
return fmt.Sprintf("%s%x", sha512DigestPwdPrefix, h.Sum(nil)) == user.Password
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2020-08-19 17:36:12 +00:00
|
|
|
func compareUnixPasswordAndHash(user *User, password string) (bool, error) {
|
2023-03-26 08:33:30 +00:00
|
|
|
if strings.HasPrefix(user.Password, yescryptPwdPrefix) {
|
|
|
|
return compareYescryptPassword(user.Password, password)
|
|
|
|
}
|
2020-09-04 19:08:09 +00:00
|
|
|
var crypter crypt.Crypter
|
2019-12-29 06:43:59 +00:00
|
|
|
if strings.HasPrefix(user.Password, sha512cryptPwdPrefix) {
|
2020-09-04 19:08:09 +00:00
|
|
|
crypter = sha512_crypt.New()
|
2022-09-28 17:15:02 +00:00
|
|
|
} else if strings.HasPrefix(user.Password, sha256cryptPwdPrefix) {
|
|
|
|
crypter = sha256_crypt.New()
|
2020-09-04 19:08:09 +00:00
|
|
|
} else if strings.HasPrefix(user.Password, md5cryptPwdPrefix) {
|
|
|
|
crypter = md5_crypt.New()
|
|
|
|
} else if strings.HasPrefix(user.Password, md5cryptApr1PwdPrefix) {
|
|
|
|
crypter = apr1_crypt.New()
|
2019-12-29 06:43:59 +00:00
|
|
|
} else {
|
2020-09-04 19:08:09 +00:00
|
|
|
return false, errors.New("unix crypt: invalid or unsupported hash format")
|
2019-12-29 06:43:59 +00:00
|
|
|
}
|
2020-09-04 19:08:09 +00:00
|
|
|
if err := crypter.Verify(user.Password, []byte(password)); err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
return true, nil
|
2019-12-29 06:43:59 +00:00
|
|
|
}
|
|
|
|
|
2019-08-17 13:20:49 +00:00
|
|
|
func comparePbkdf2PasswordAndHash(password, hashedPassword string) (bool, error) {
|
|
|
|
vals := strings.Split(hashedPassword, "$")
|
|
|
|
if len(vals) != 5 {
|
|
|
|
return false, fmt.Errorf("pbkdf2: hash is not in the correct format")
|
|
|
|
}
|
2020-04-11 10:25:21 +00:00
|
|
|
iterations, err := strconv.Atoi(vals[2])
|
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
expected, err := base64.StdEncoding.DecodeString(vals[4])
|
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
var salt []byte
|
2021-07-11 13:26:51 +00:00
|
|
|
if util.IsStringPrefixInSlice(hashedPassword, pbkdfPwdB64SaltPrefixes) {
|
2020-04-11 10:25:21 +00:00
|
|
|
salt, err = base64.StdEncoding.DecodeString(vals[3])
|
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
salt = []byte(vals[3])
|
|
|
|
}
|
2019-08-17 13:20:49 +00:00
|
|
|
var hashFunc func() hash.Hash
|
2020-04-11 10:25:21 +00:00
|
|
|
if strings.HasPrefix(hashedPassword, pbkdf2SHA256Prefix) || strings.HasPrefix(hashedPassword, pbkdf2SHA256B64SaltPrefix) {
|
2019-08-17 13:20:49 +00:00
|
|
|
hashFunc = sha256.New
|
|
|
|
} else if strings.HasPrefix(hashedPassword, pbkdf2SHA512Prefix) {
|
|
|
|
hashFunc = sha512.New
|
|
|
|
} else if strings.HasPrefix(hashedPassword, pbkdf2SHA1Prefix) {
|
|
|
|
hashFunc = sha1.New
|
|
|
|
} else {
|
|
|
|
return false, fmt.Errorf("pbkdf2: invalid or unsupported hash format %v", vals[1])
|
|
|
|
}
|
2020-04-11 10:25:21 +00:00
|
|
|
df := pbkdf2.Key([]byte(password), salt, iterations, len(expected), hashFunc)
|
2020-03-28 15:09:06 +00:00
|
|
|
return subtle.ConstantTimeCompare(df, expected) == 1, nil
|
2019-08-17 13:20:49 +00:00
|
|
|
}
|
|
|
|
|
2019-07-20 10:26:52 +00:00
|
|
|
func getSSLMode() string {
|
2021-03-23 18:14:15 +00:00
|
|
|
if config.Driver == PGSQLDataProviderName || config.Driver == CockroachDataProviderName {
|
2022-01-30 17:04:03 +00:00
|
|
|
switch config.SSLMode {
|
|
|
|
case 0:
|
2019-07-20 10:26:52 +00:00
|
|
|
return "disable"
|
2022-01-30 17:04:03 +00:00
|
|
|
case 1:
|
2019-07-20 10:26:52 +00:00
|
|
|
return "require"
|
2022-01-30 17:04:03 +00:00
|
|
|
case 2:
|
2019-07-20 10:26:52 +00:00
|
|
|
return "verify-ca"
|
2022-01-30 17:04:03 +00:00
|
|
|
case 3:
|
2019-07-20 10:26:52 +00:00
|
|
|
return "verify-full"
|
2023-08-05 18:01:14 +00:00
|
|
|
case 4:
|
|
|
|
return "prefer"
|
|
|
|
case 5:
|
|
|
|
return "allow"
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
} else if config.Driver == MySQLDataProviderName {
|
2022-01-30 17:04:03 +00:00
|
|
|
if config.requireCustomTLSForMySQL() {
|
|
|
|
return "custom"
|
|
|
|
}
|
|
|
|
switch config.SSLMode {
|
|
|
|
case 0:
|
2019-07-20 10:26:52 +00:00
|
|
|
return "false"
|
2022-01-30 17:04:03 +00:00
|
|
|
case 1:
|
2019-07-20 10:26:52 +00:00
|
|
|
return "true"
|
2022-01-30 17:04:03 +00:00
|
|
|
case 2:
|
2019-07-20 10:26:52 +00:00
|
|
|
return "skip-verify"
|
2022-01-30 17:04:03 +00:00
|
|
|
case 3:
|
2019-07-20 10:26:52 +00:00
|
|
|
return "preferred"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|
2019-09-06 13:19:01 +00:00
|
|
|
|
2020-01-21 09:54:05 +00:00
|
|
|
func terminateInteractiveAuthProgram(cmd *exec.Cmd, isFinished bool) {
|
|
|
|
if isFinished {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
providerLog(logger.LevelInfo, "kill interactive auth program after an unexpected error")
|
2020-04-30 12:23:55 +00:00
|
|
|
err := cmd.Process.Kill()
|
|
|
|
if err != nil {
|
|
|
|
providerLog(logger.LevelDebug, "error killing interactive auth program: %v", err)
|
|
|
|
}
|
2020-01-21 09:54:05 +00:00
|
|
|
}
|
|
|
|
|
2021-08-08 15:09:48 +00:00
|
|
|
func sendKeyboardAuthHTTPReq(url string, request *plugin.KeyboardAuthRequest) (*plugin.KeyboardAuthResponse, error) {
|
2020-04-01 21:25:23 +00:00
|
|
|
reqAsJSON, err := json.Marshal(request)
|
|
|
|
if err != nil {
|
2021-12-16 18:53:00 +00:00
|
|
|
providerLog(logger.LevelError, "error serializing keyboard interactive auth request: %v", err)
|
2021-08-08 15:09:48 +00:00
|
|
|
return nil, err
|
2020-04-01 21:25:23 +00:00
|
|
|
}
|
2021-05-25 06:36:01 +00:00
|
|
|
resp, err := httpclient.Post(url, "application/json", bytes.NewBuffer(reqAsJSON))
|
2020-04-01 21:25:23 +00:00
|
|
|
if err != nil {
|
2021-12-16 18:53:00 +00:00
|
|
|
providerLog(logger.LevelError, "error getting keyboard interactive auth hook HTTP response: %v", err)
|
2021-08-08 15:09:48 +00:00
|
|
|
return nil, err
|
2020-04-01 21:25:23 +00:00
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
2021-08-08 15:09:48 +00:00
|
|
|
return nil, fmt.Errorf("wrong keyboard interactive auth http status code: %v, expected 200", resp.StatusCode)
|
2020-04-01 21:25:23 +00:00
|
|
|
}
|
2021-08-08 15:09:48 +00:00
|
|
|
var response plugin.KeyboardAuthResponse
|
2020-04-01 21:25:23 +00:00
|
|
|
err = render.DecodeJSON(resp.Body, &response)
|
2021-08-08 15:09:48 +00:00
|
|
|
return &response, err
|
|
|
|
}
|
|
|
|
|
2024-02-05 18:02:01 +00:00
|
|
|
func doBuiltinKeyboardInteractiveAuth(user *User, client ssh.KeyboardInteractiveChallenge,
|
|
|
|
ip, protocol string, isPartialAuth bool,
|
|
|
|
) (int, error) {
|
|
|
|
if err := user.LoadAndApplyGroupSettings(); err != nil {
|
2022-04-25 13:49:11 +00:00
|
|
|
return 0, err
|
|
|
|
}
|
2024-07-24 16:27:13 +00:00
|
|
|
hasSecondFactor := user.Filters.TOTPConfig.Enabled && slices.Contains(user.Filters.TOTPConfig.Protocols, protocolSSH)
|
2024-02-05 18:02:01 +00:00
|
|
|
if !isPartialAuth || !hasSecondFactor {
|
|
|
|
answers, err := client("", "", []string{"Password: "}, []bool{false})
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
if len(answers) != 1 {
|
|
|
|
return 0, fmt.Errorf("unexpected number of answers: %d", len(answers))
|
|
|
|
}
|
|
|
|
_, err = checkUserAndPass(user, answers[0], ip, protocol)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
2021-09-04 10:11:04 +00:00
|
|
|
}
|
2023-06-25 05:16:26 +00:00
|
|
|
return checkKeyboardInteractiveSecondFactor(user, client, protocol)
|
|
|
|
}
|
|
|
|
|
|
|
|
func checkKeyboardInteractiveSecondFactor(user *User, client ssh.KeyboardInteractiveChallenge, protocol string) (int, error) {
|
2024-07-24 16:27:13 +00:00
|
|
|
if !user.Filters.TOTPConfig.Enabled || !slices.Contains(user.Filters.TOTPConfig.Protocols, protocolSSH) {
|
2021-09-04 10:11:04 +00:00
|
|
|
return 1, nil
|
|
|
|
}
|
2023-06-25 05:16:26 +00:00
|
|
|
err := user.Filters.TOTPConfig.Secret.TryDecrypt()
|
2021-09-04 10:11:04 +00:00
|
|
|
if err != nil {
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelError, "unable to decrypt TOTP secret for user %q, protocol %v, err: %v",
|
2021-09-04 10:11:04 +00:00
|
|
|
user.Username, protocol, err)
|
|
|
|
return 0, err
|
|
|
|
}
|
2023-06-25 05:16:26 +00:00
|
|
|
answers, err := client("", "", []string{"Authentication code: "}, []bool{false})
|
2021-09-04 10:11:04 +00:00
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
if len(answers) != 1 {
|
|
|
|
return 0, fmt.Errorf("unexpected number of answers: %v", len(answers))
|
|
|
|
}
|
|
|
|
match, err := mfa.ValidateTOTPPasscode(user.Filters.TOTPConfig.ConfigName, answers[0],
|
|
|
|
user.Filters.TOTPConfig.Secret.GetPayload())
|
|
|
|
if !match || err != nil {
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelWarn, "invalid passcode for user %q, protocol %v, err: %v",
|
2021-09-04 10:11:04 +00:00
|
|
|
user.Username, protocol, err)
|
|
|
|
return 0, util.NewValidationError("invalid passcode")
|
|
|
|
}
|
|
|
|
return 1, nil
|
|
|
|
}
|
|
|
|
|
2021-08-08 15:09:48 +00:00
|
|
|
func executeKeyboardInteractivePlugin(user *User, client ssh.KeyboardInteractiveChallenge, ip, protocol string) (int, error) {
|
|
|
|
authResult := 0
|
|
|
|
requestID := xid.New().String()
|
|
|
|
authStep := 1
|
|
|
|
req := &plugin.KeyboardAuthRequest{
|
|
|
|
Username: user.Username,
|
|
|
|
IP: ip,
|
|
|
|
Password: user.Password,
|
|
|
|
RequestID: requestID,
|
|
|
|
Step: authStep,
|
|
|
|
}
|
|
|
|
var response *plugin.KeyboardAuthResponse
|
|
|
|
var err error
|
|
|
|
for {
|
|
|
|
response, err = plugin.Handler.ExecuteKeyboardInteractiveStep(req)
|
|
|
|
if err != nil {
|
|
|
|
return authResult, err
|
|
|
|
}
|
|
|
|
if response.AuthResult != 0 {
|
|
|
|
return response.AuthResult, err
|
|
|
|
}
|
|
|
|
if err = response.Validate(); err != nil {
|
|
|
|
providerLog(logger.LevelInfo, "invalid response from keyboard interactive plugin: %v", err)
|
|
|
|
return authResult, err
|
|
|
|
}
|
|
|
|
answers, err := getKeyboardInteractiveAnswers(client, response, user, ip, protocol)
|
|
|
|
if err != nil {
|
|
|
|
return authResult, err
|
|
|
|
}
|
|
|
|
authStep++
|
|
|
|
req = &plugin.KeyboardAuthRequest{
|
|
|
|
RequestID: requestID,
|
|
|
|
Step: authStep,
|
|
|
|
Username: user.Username,
|
|
|
|
Password: user.Password,
|
|
|
|
Answers: answers,
|
|
|
|
Questions: response.Questions,
|
|
|
|
}
|
|
|
|
}
|
2020-04-01 21:25:23 +00:00
|
|
|
}
|
|
|
|
|
2021-02-16 18:11:36 +00:00
|
|
|
func executeKeyboardInteractiveHTTPHook(user *User, authHook string, client ssh.KeyboardInteractiveChallenge, ip, protocol string) (int, error) {
|
2020-04-01 21:25:23 +00:00
|
|
|
authResult := 0
|
|
|
|
requestID := xid.New().String()
|
2021-08-08 15:09:48 +00:00
|
|
|
authStep := 1
|
|
|
|
req := &plugin.KeyboardAuthRequest{
|
2020-04-01 21:25:23 +00:00
|
|
|
Username: user.Username,
|
2020-08-04 16:03:28 +00:00
|
|
|
IP: ip,
|
2020-04-01 21:25:23 +00:00
|
|
|
Password: user.Password,
|
|
|
|
RequestID: requestID,
|
2021-08-08 15:09:48 +00:00
|
|
|
Step: authStep,
|
2020-04-01 21:25:23 +00:00
|
|
|
}
|
2021-08-08 15:09:48 +00:00
|
|
|
var response *plugin.KeyboardAuthResponse
|
2021-05-25 06:36:01 +00:00
|
|
|
var err error
|
2020-04-01 21:25:23 +00:00
|
|
|
for {
|
2021-05-25 06:36:01 +00:00
|
|
|
response, err = sendKeyboardAuthHTTPReq(authHook, req)
|
2020-04-01 21:25:23 +00:00
|
|
|
if err != nil {
|
|
|
|
return authResult, err
|
|
|
|
}
|
|
|
|
if response.AuthResult != 0 {
|
|
|
|
return response.AuthResult, err
|
|
|
|
}
|
2021-08-08 15:09:48 +00:00
|
|
|
if err = response.Validate(); err != nil {
|
|
|
|
providerLog(logger.LevelInfo, "invalid response from keyboard interactive http hook: %v", err)
|
2020-04-01 21:25:23 +00:00
|
|
|
return authResult, err
|
|
|
|
}
|
2020-08-19 17:36:12 +00:00
|
|
|
answers, err := getKeyboardInteractiveAnswers(client, response, user, ip, protocol)
|
2020-04-01 21:25:23 +00:00
|
|
|
if err != nil {
|
|
|
|
return authResult, err
|
|
|
|
}
|
2021-08-08 15:09:48 +00:00
|
|
|
authStep++
|
|
|
|
req = &plugin.KeyboardAuthRequest{
|
2020-04-01 21:25:23 +00:00
|
|
|
RequestID: requestID,
|
2021-08-08 15:09:48 +00:00
|
|
|
Step: authStep,
|
2020-04-01 21:25:23 +00:00
|
|
|
Username: user.Username,
|
|
|
|
Password: user.Password,
|
|
|
|
Answers: answers,
|
|
|
|
Questions: response.Questions,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-08 15:09:48 +00:00
|
|
|
func getKeyboardInteractiveAnswers(client ssh.KeyboardInteractiveChallenge, response *plugin.KeyboardAuthResponse,
|
2021-09-04 10:11:04 +00:00
|
|
|
user *User, ip, protocol string,
|
|
|
|
) ([]string, error) {
|
2020-02-16 10:43:52 +00:00
|
|
|
questions := response.Questions
|
2022-03-19 20:44:27 +00:00
|
|
|
answers, err := client("", response.Instruction, questions, response.Echos)
|
2020-02-16 10:43:52 +00:00
|
|
|
if err != nil {
|
|
|
|
providerLog(logger.LevelInfo, "error getting interactive auth client response: %v", err)
|
2020-04-01 21:25:23 +00:00
|
|
|
return answers, err
|
2020-02-16 10:43:52 +00:00
|
|
|
}
|
|
|
|
if len(answers) != len(questions) {
|
|
|
|
err = fmt.Errorf("client answers does not match questions, expected: %v actual: %v", questions, answers)
|
|
|
|
providerLog(logger.LevelInfo, "keyboard interactive auth error: %v", err)
|
2020-04-01 21:25:23 +00:00
|
|
|
return answers, err
|
2020-02-16 10:43:52 +00:00
|
|
|
}
|
|
|
|
if len(answers) == 1 && response.CheckPwd > 0 {
|
2021-12-04 14:14:44 +00:00
|
|
|
if response.CheckPwd == 2 {
|
2024-07-24 16:27:13 +00:00
|
|
|
if !user.Filters.TOTPConfig.Enabled || !slices.Contains(user.Filters.TOTPConfig.Protocols, protocolSSH) {
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelInfo, "keyboard interactive auth error: unable to check TOTP passcode, TOTP is not enabled for user %q",
|
2021-12-04 14:14:44 +00:00
|
|
|
user.Username)
|
|
|
|
return answers, errors.New("TOTP not enabled for SSH protocol")
|
|
|
|
}
|
|
|
|
err := user.Filters.TOTPConfig.Secret.TryDecrypt()
|
|
|
|
if err != nil {
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelError, "unable to decrypt TOTP secret for user %q, protocol %v, err: %v",
|
2021-12-04 14:14:44 +00:00
|
|
|
user.Username, protocol, err)
|
|
|
|
return answers, fmt.Errorf("unable to decrypt TOTP secret: %w", err)
|
|
|
|
}
|
|
|
|
match, err := mfa.ValidateTOTPPasscode(user.Filters.TOTPConfig.ConfigName, answers[0],
|
|
|
|
user.Filters.TOTPConfig.Secret.GetPayload())
|
|
|
|
if !match || err != nil {
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelInfo, "keyboard interactive auth error: unable to validate passcode for user %q, match? %v, err: %v",
|
2021-12-04 14:14:44 +00:00
|
|
|
user.Username, match, err)
|
|
|
|
return answers, errors.New("unable to validate TOTP passcode")
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
_, err = checkUserAndPass(user, answers[0], ip, protocol)
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelInfo, "interactive auth hook requested password validation for user %q, validation error: %v",
|
2021-12-04 14:14:44 +00:00
|
|
|
user.Username, err)
|
|
|
|
if err != nil {
|
|
|
|
return answers, err
|
|
|
|
}
|
2020-02-16 10:43:52 +00:00
|
|
|
}
|
|
|
|
answers[0] = "OK"
|
|
|
|
}
|
2020-04-01 21:25:23 +00:00
|
|
|
return answers, err
|
|
|
|
}
|
|
|
|
|
2021-08-08 15:09:48 +00:00
|
|
|
func handleProgramInteractiveQuestions(client ssh.KeyboardInteractiveChallenge, response *plugin.KeyboardAuthResponse,
|
2021-09-04 10:11:04 +00:00
|
|
|
user *User, stdin io.WriteCloser, ip, protocol string,
|
|
|
|
) error {
|
2020-08-19 17:36:12 +00:00
|
|
|
answers, err := getKeyboardInteractiveAnswers(client, response, user, ip, protocol)
|
2020-04-01 21:25:23 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-02-16 10:43:52 +00:00
|
|
|
for _, answer := range answers {
|
|
|
|
if runtime.GOOS == "windows" {
|
|
|
|
answer += "\r"
|
|
|
|
}
|
|
|
|
answer += "\n"
|
|
|
|
_, err = stdin.Write([]byte(answer))
|
|
|
|
if err != nil {
|
|
|
|
providerLog(logger.LevelError, "unable to write client answer to keyboard interactive program: %v", err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-02-16 18:11:36 +00:00
|
|
|
func executeKeyboardInteractiveProgram(user *User, authHook string, client ssh.KeyboardInteractiveChallenge, ip, protocol string) (int, error) {
|
2020-04-01 21:25:23 +00:00
|
|
|
authResult := 0
|
2022-09-20 11:58:44 +00:00
|
|
|
timeout, env, args := command.GetConfig(authHook, command.HookKeyboardInteractive)
|
2022-05-20 17:30:54 +00:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
2020-01-21 09:54:05 +00:00
|
|
|
defer cancel()
|
2022-05-20 17:30:54 +00:00
|
|
|
|
2022-09-20 11:58:44 +00:00
|
|
|
cmd := exec.CommandContext(ctx, authHook, args...)
|
2022-05-20 17:30:54 +00:00
|
|
|
cmd.Env = append(env,
|
2023-02-26 14:15:34 +00:00
|
|
|
fmt.Sprintf("SFTPGO_AUTHD_USERNAME=%s", user.Username),
|
|
|
|
fmt.Sprintf("SFTPGO_AUTHD_IP=%s", ip),
|
|
|
|
fmt.Sprintf("SFTPGO_AUTHD_PASSWORD=%s", user.Password))
|
2020-01-21 09:54:05 +00:00
|
|
|
stdout, err := cmd.StdoutPipe()
|
|
|
|
if err != nil {
|
2020-04-01 21:25:23 +00:00
|
|
|
return authResult, err
|
2020-01-21 09:54:05 +00:00
|
|
|
}
|
|
|
|
stdin, err := cmd.StdinPipe()
|
|
|
|
if err != nil {
|
2020-04-01 21:25:23 +00:00
|
|
|
return authResult, err
|
2020-01-21 09:54:05 +00:00
|
|
|
}
|
|
|
|
err = cmd.Start()
|
|
|
|
if err != nil {
|
2020-04-01 21:25:23 +00:00
|
|
|
return authResult, err
|
2020-01-21 09:54:05 +00:00
|
|
|
}
|
|
|
|
var once sync.Once
|
|
|
|
scanner := bufio.NewScanner(stdout)
|
|
|
|
for scanner.Scan() {
|
2021-08-08 15:09:48 +00:00
|
|
|
var response plugin.KeyboardAuthResponse
|
2020-04-01 21:25:23 +00:00
|
|
|
err = json.Unmarshal(scanner.Bytes(), &response)
|
2020-01-21 09:54:05 +00:00
|
|
|
if err != nil {
|
|
|
|
providerLog(logger.LevelInfo, "interactive auth error parsing response: %v", err)
|
|
|
|
once.Do(func() { terminateInteractiveAuthProgram(cmd, false) })
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if response.AuthResult != 0 {
|
|
|
|
authResult = response.AuthResult
|
|
|
|
break
|
|
|
|
}
|
2021-08-08 15:09:48 +00:00
|
|
|
if err = response.Validate(); err != nil {
|
|
|
|
providerLog(logger.LevelInfo, "invalid response from keyboard interactive program: %v", err)
|
2020-01-21 09:54:05 +00:00
|
|
|
once.Do(func() { terminateInteractiveAuthProgram(cmd, false) })
|
|
|
|
break
|
|
|
|
}
|
|
|
|
go func() {
|
2021-08-08 15:09:48 +00:00
|
|
|
err := handleProgramInteractiveQuestions(client, &response, user, stdin, ip, protocol)
|
2020-01-21 09:54:05 +00:00
|
|
|
if err != nil {
|
|
|
|
once.Do(func() { terminateInteractiveAuthProgram(cmd, false) })
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
stdin.Close()
|
|
|
|
once.Do(func() { terminateInteractiveAuthProgram(cmd, true) })
|
2020-04-30 12:23:55 +00:00
|
|
|
go func() {
|
|
|
|
_, err := cmd.Process.Wait()
|
|
|
|
if err != nil {
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelWarn, "error waiting for %q process to exit: %v", authHook, err)
|
2020-04-30 12:23:55 +00:00
|
|
|
}
|
|
|
|
}()
|
2020-04-01 21:25:23 +00:00
|
|
|
|
|
|
|
return authResult, err
|
|
|
|
}
|
|
|
|
|
2024-02-05 18:02:01 +00:00
|
|
|
func doKeyboardInteractiveAuth(user *User, authHook string, client ssh.KeyboardInteractiveChallenge,
|
|
|
|
ip, protocol string, isPartialAuth bool,
|
|
|
|
) (User, error) {
|
2023-11-18 10:26:37 +00:00
|
|
|
if err := user.LoadAndApplyGroupSettings(); err != nil {
|
|
|
|
return *user, err
|
|
|
|
}
|
2020-04-01 21:25:23 +00:00
|
|
|
var authResult int
|
|
|
|
var err error
|
2023-11-18 10:26:37 +00:00
|
|
|
if !user.Filters.Hooks.ExternalAuthDisabled {
|
|
|
|
if plugin.Handler.HasAuthScope(plugin.AuthScopeKeyboardInteractive) {
|
|
|
|
authResult, err = executeKeyboardInteractivePlugin(user, client, ip, protocol)
|
|
|
|
if authResult == 1 && err == nil {
|
|
|
|
authResult, err = checkKeyboardInteractiveSecondFactor(user, client, protocol)
|
|
|
|
}
|
|
|
|
} else if authHook != "" {
|
|
|
|
if strings.HasPrefix(authHook, "http") {
|
|
|
|
authResult, err = executeKeyboardInteractiveHTTPHook(user, authHook, client, ip, protocol)
|
|
|
|
} else {
|
|
|
|
authResult, err = executeKeyboardInteractiveProgram(user, authHook, client, ip, protocol)
|
|
|
|
}
|
2021-09-04 10:11:04 +00:00
|
|
|
} else {
|
2024-02-05 18:02:01 +00:00
|
|
|
authResult, err = doBuiltinKeyboardInteractiveAuth(user, client, ip, protocol, isPartialAuth)
|
2021-09-04 10:11:04 +00:00
|
|
|
}
|
2020-04-01 21:25:23 +00:00
|
|
|
} else {
|
2024-02-05 18:02:01 +00:00
|
|
|
authResult, err = doBuiltinKeyboardInteractiveAuth(user, client, ip, protocol, isPartialAuth)
|
2020-04-01 21:25:23 +00:00
|
|
|
}
|
2020-04-03 20:30:30 +00:00
|
|
|
if err != nil {
|
2021-02-16 18:11:36 +00:00
|
|
|
return *user, err
|
2020-04-03 20:30:30 +00:00
|
|
|
}
|
2020-01-21 09:54:05 +00:00
|
|
|
if authResult != 1 {
|
2021-02-16 18:11:36 +00:00
|
|
|
return *user, fmt.Errorf("keyboard interactive auth failed, result: %v", authResult)
|
2020-01-21 09:54:05 +00:00
|
|
|
}
|
2021-08-17 16:08:32 +00:00
|
|
|
err = user.CheckLoginConditions()
|
2020-02-23 17:50:59 +00:00
|
|
|
if err != nil {
|
2021-02-16 18:11:36 +00:00
|
|
|
return *user, err
|
2020-02-23 17:50:59 +00:00
|
|
|
}
|
2021-02-16 18:11:36 +00:00
|
|
|
return *user, nil
|
2020-01-21 09:54:05 +00:00
|
|
|
}
|
|
|
|
|
2020-08-19 17:36:12 +00:00
|
|
|
func isCheckPasswordHookDefined(protocol string) bool {
|
2021-01-05 08:50:22 +00:00
|
|
|
if config.CheckPasswordHook == "" {
|
2020-08-19 17:36:12 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
if config.CheckPasswordScope == 0 {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
switch protocol {
|
2021-09-04 10:11:04 +00:00
|
|
|
case protocolSSH:
|
2020-08-19 17:36:12 +00:00
|
|
|
return config.CheckPasswordScope&1 != 0
|
2021-09-04 10:11:04 +00:00
|
|
|
case protocolFTP:
|
2020-08-19 17:36:12 +00:00
|
|
|
return config.CheckPasswordScope&2 != 0
|
2021-09-04 10:11:04 +00:00
|
|
|
case protocolWebDAV:
|
2020-08-19 17:36:12 +00:00
|
|
|
return config.CheckPasswordScope&4 != 0
|
|
|
|
default:
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func getPasswordHookResponse(username, password, ip, protocol string) ([]byte, error) {
|
|
|
|
if strings.HasPrefix(config.CheckPasswordHook, "http") {
|
|
|
|
var result []byte
|
|
|
|
req := checkPasswordRequest{
|
|
|
|
Username: username,
|
|
|
|
Password: password,
|
|
|
|
IP: ip,
|
|
|
|
Protocol: protocol,
|
|
|
|
}
|
|
|
|
reqAsJSON, err := json.Marshal(req)
|
|
|
|
if err != nil {
|
|
|
|
return result, err
|
|
|
|
}
|
2021-05-25 06:36:01 +00:00
|
|
|
resp, err := httpclient.Post(config.CheckPasswordHook, "application/json", bytes.NewBuffer(reqAsJSON))
|
2020-08-19 17:36:12 +00:00
|
|
|
if err != nil {
|
2021-12-16 18:53:00 +00:00
|
|
|
providerLog(logger.LevelError, "error getting check password hook response: %v", err)
|
2020-08-19 17:36:12 +00:00
|
|
|
return result, err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
|
|
return result, fmt.Errorf("wrong http status code from chek password hook: %v, expected 200", resp.StatusCode)
|
|
|
|
}
|
2021-05-12 20:44:17 +00:00
|
|
|
return io.ReadAll(io.LimitReader(resp.Body, maxHookResponseSize))
|
2020-08-19 17:36:12 +00:00
|
|
|
}
|
2022-09-20 11:58:44 +00:00
|
|
|
timeout, env, args := command.GetConfig(config.CheckPasswordHook, command.HookCheckPassword)
|
2022-05-20 17:30:54 +00:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
2020-08-19 17:36:12 +00:00
|
|
|
defer cancel()
|
2022-05-20 17:30:54 +00:00
|
|
|
|
2022-09-20 11:58:44 +00:00
|
|
|
cmd := exec.CommandContext(ctx, config.CheckPasswordHook, args...)
|
2022-05-20 17:30:54 +00:00
|
|
|
cmd.Env = append(env,
|
2023-02-26 14:15:34 +00:00
|
|
|
fmt.Sprintf("SFTPGO_AUTHD_USERNAME=%s", username),
|
|
|
|
fmt.Sprintf("SFTPGO_AUTHD_PASSWORD=%s", password),
|
|
|
|
fmt.Sprintf("SFTPGO_AUTHD_IP=%s", ip),
|
|
|
|
fmt.Sprintf("SFTPGO_AUTHD_PROTOCOL=%s", protocol),
|
2020-08-19 17:36:12 +00:00
|
|
|
)
|
2024-04-26 09:13:16 +00:00
|
|
|
return cmd.Output()
|
2020-08-19 17:36:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func executeCheckPasswordHook(username, password, ip, protocol string) (checkPasswordResponse, error) {
|
|
|
|
var response checkPasswordResponse
|
|
|
|
|
|
|
|
if !isCheckPasswordHookDefined(protocol) {
|
|
|
|
response.Status = -1
|
|
|
|
return response, nil
|
|
|
|
}
|
|
|
|
|
2021-03-21 18:15:47 +00:00
|
|
|
startTime := time.Now()
|
2020-08-19 17:36:12 +00:00
|
|
|
out, err := getPasswordHookResponse(username, password, ip, protocol)
|
2021-03-21 18:15:47 +00:00
|
|
|
providerLog(logger.LevelDebug, "check password hook executed, error: %v, elapsed: %v", err, time.Since(startTime))
|
2020-08-19 17:36:12 +00:00
|
|
|
if err != nil {
|
|
|
|
return response, err
|
|
|
|
}
|
|
|
|
err = json.Unmarshal(out, &response)
|
|
|
|
return response, err
|
|
|
|
}
|
|
|
|
|
2020-08-12 14:15:12 +00:00
|
|
|
func getPreLoginHookResponse(loginMethod, ip, protocol string, userAsJSON []byte) ([]byte, error) {
|
2020-04-01 21:25:23 +00:00
|
|
|
if strings.HasPrefix(config.PreLoginHook, "http") {
|
|
|
|
var url *url.URL
|
|
|
|
var result []byte
|
|
|
|
url, err := url.Parse(config.PreLoginHook)
|
|
|
|
if err != nil {
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelError, "invalid url for pre-login hook %q, error: %v", config.PreLoginHook, err)
|
2020-04-01 21:25:23 +00:00
|
|
|
return result, err
|
|
|
|
}
|
|
|
|
q := url.Query()
|
|
|
|
q.Add("login_method", loginMethod)
|
2020-08-04 16:03:28 +00:00
|
|
|
q.Add("ip", ip)
|
2020-08-12 14:15:12 +00:00
|
|
|
q.Add("protocol", protocol)
|
2020-04-01 21:25:23 +00:00
|
|
|
url.RawQuery = q.Encode()
|
2021-05-25 06:36:01 +00:00
|
|
|
|
|
|
|
resp, err := httpclient.Post(url.String(), "application/json", bytes.NewBuffer(userAsJSON))
|
2020-04-01 21:25:23 +00:00
|
|
|
if err != nil {
|
|
|
|
providerLog(logger.LevelWarn, "error getting pre-login hook response: %v", err)
|
|
|
|
return result, err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode == http.StatusNoContent {
|
|
|
|
return result, nil
|
|
|
|
}
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
|
|
return result, fmt.Errorf("wrong pre-login hook http status code: %v, expected 200", resp.StatusCode)
|
|
|
|
}
|
2021-05-12 20:44:17 +00:00
|
|
|
return io.ReadAll(io.LimitReader(resp.Body, maxHookResponseSize))
|
2020-04-01 21:25:23 +00:00
|
|
|
}
|
2022-09-20 11:58:44 +00:00
|
|
|
timeout, env, args := command.GetConfig(config.PreLoginHook, command.HookPreLogin)
|
2022-05-20 17:30:54 +00:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
2020-04-01 21:25:23 +00:00
|
|
|
defer cancel()
|
2022-05-20 17:30:54 +00:00
|
|
|
|
2022-09-20 11:58:44 +00:00
|
|
|
cmd := exec.CommandContext(ctx, config.PreLoginHook, args...)
|
2022-05-20 17:30:54 +00:00
|
|
|
cmd.Env = append(env,
|
2024-05-08 17:01:58 +00:00
|
|
|
fmt.Sprintf("SFTPGO_LOGIND_USER=%s", util.BytesToString(userAsJSON)),
|
2023-02-26 14:15:34 +00:00
|
|
|
fmt.Sprintf("SFTPGO_LOGIND_METHOD=%s", loginMethod),
|
|
|
|
fmt.Sprintf("SFTPGO_LOGIND_IP=%s", ip),
|
|
|
|
fmt.Sprintf("SFTPGO_LOGIND_PROTOCOL=%s", protocol),
|
2020-04-01 21:25:23 +00:00
|
|
|
)
|
2024-04-26 09:13:16 +00:00
|
|
|
return cmd.Output()
|
2020-04-01 21:25:23 +00:00
|
|
|
}
|
|
|
|
|
2022-05-19 17:49:51 +00:00
|
|
|
func executePreLoginHook(username, loginMethod, ip, protocol string, oidcTokenFields *map[string]any) (User, error) {
|
2022-04-25 13:49:11 +00:00
|
|
|
u, mergedUser, userAsJSON, err := getUserAndJSONForHook(username, oidcTokenFields)
|
2020-02-23 17:50:59 +00:00
|
|
|
if err != nil {
|
|
|
|
return u, err
|
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
if mergedUser.Filters.Hooks.PreLoginDisabled {
|
2021-04-04 20:32:25 +00:00
|
|
|
return u, nil
|
|
|
|
}
|
2021-03-21 18:15:47 +00:00
|
|
|
startTime := time.Now()
|
2020-08-12 14:15:12 +00:00
|
|
|
out, err := getPreLoginHookResponse(loginMethod, ip, protocol, userAsJSON)
|
2020-02-23 17:50:59 +00:00
|
|
|
if err != nil {
|
2023-02-26 14:15:34 +00:00
|
|
|
return u, fmt.Errorf("pre-login hook error: %v, username %q, ip %v, protocol %v elapsed %v",
|
2021-07-24 18:11:17 +00:00
|
|
|
err, username, ip, protocol, time.Since(startTime))
|
2020-02-23 17:50:59 +00:00
|
|
|
}
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelDebug, "pre-login hook completed, elapsed: %s", time.Since(startTime))
|
2021-07-11 13:26:51 +00:00
|
|
|
if util.IsByteArrayEmpty(out) {
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelDebug, "empty response from pre-login hook, no modification requested for user %q id: %d",
|
2020-03-27 22:26:22 +00:00
|
|
|
username, u.ID)
|
|
|
|
if u.ID == 0 {
|
2023-02-26 14:15:34 +00:00
|
|
|
return u, util.NewRecordNotFoundError(fmt.Sprintf("username %q does not exist", username))
|
2020-03-27 22:26:22 +00:00
|
|
|
}
|
2020-02-23 17:50:59 +00:00
|
|
|
return u, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
userID := u.ID
|
|
|
|
userUsedQuotaSize := u.UsedQuotaSize
|
|
|
|
userUsedQuotaFiles := u.UsedQuotaFiles
|
2022-01-30 10:42:36 +00:00
|
|
|
userUsedDownloadTransfer := u.UsedDownloadDataTransfer
|
|
|
|
userUsedUploadTransfer := u.UsedUploadDataTransfer
|
2020-02-23 17:50:59 +00:00
|
|
|
userLastQuotaUpdate := u.LastQuotaUpdate
|
|
|
|
userLastLogin := u.LastLogin
|
2022-08-21 17:01:08 +00:00
|
|
|
userFirstDownload := u.FirstDownload
|
|
|
|
userFirstUpload := u.FirstUpload
|
2022-12-11 16:15:34 +00:00
|
|
|
userLastPwdChange := u.LastPasswordChange
|
2021-08-19 13:51:43 +00:00
|
|
|
userCreatedAt := u.CreatedAt
|
2021-12-11 10:08:20 +00:00
|
|
|
totpConfig := u.Filters.TOTPConfig
|
|
|
|
recoveryCodes := u.Filters.RecoveryCodes
|
2020-02-23 17:50:59 +00:00
|
|
|
err = json.Unmarshal(out, &u)
|
|
|
|
if err != nil {
|
2024-05-08 17:01:58 +00:00
|
|
|
return u, fmt.Errorf("invalid pre-login hook response %q, error: %v", util.BytesToString(out), err)
|
2020-02-23 17:50:59 +00:00
|
|
|
}
|
|
|
|
u.ID = userID
|
|
|
|
u.UsedQuotaSize = userUsedQuotaSize
|
|
|
|
u.UsedQuotaFiles = userUsedQuotaFiles
|
2022-01-30 10:42:36 +00:00
|
|
|
u.UsedUploadDataTransfer = userUsedUploadTransfer
|
|
|
|
u.UsedDownloadDataTransfer = userUsedDownloadTransfer
|
2020-02-23 17:50:59 +00:00
|
|
|
u.LastQuotaUpdate = userLastQuotaUpdate
|
|
|
|
u.LastLogin = userLastLogin
|
2022-12-11 16:15:34 +00:00
|
|
|
u.LastPasswordChange = userLastPwdChange
|
2022-08-21 17:01:08 +00:00
|
|
|
u.FirstDownload = userFirstDownload
|
|
|
|
u.FirstUpload = userFirstUpload
|
2021-08-19 13:51:43 +00:00
|
|
|
u.CreatedAt = userCreatedAt
|
2020-03-27 22:26:22 +00:00
|
|
|
if userID == 0 {
|
2021-01-05 08:50:22 +00:00
|
|
|
err = provider.addUser(&u)
|
2020-03-27 22:26:22 +00:00
|
|
|
} else {
|
2021-08-19 13:51:43 +00:00
|
|
|
u.UpdatedAt = util.GetTimeAsMsSinceEpoch(time.Now())
|
2021-12-11 10:08:20 +00:00
|
|
|
// preserve TOTP config and recovery codes
|
|
|
|
u.Filters.TOTPConfig = totpConfig
|
|
|
|
u.Filters.RecoveryCodes = recoveryCodes
|
2021-01-05 08:50:22 +00:00
|
|
|
err = provider.updateUser(&u)
|
2021-03-27 18:10:27 +00:00
|
|
|
if err == nil {
|
2023-05-20 10:39:07 +00:00
|
|
|
webDAVUsersCache.swap(&u, "")
|
2021-03-27 18:10:27 +00:00
|
|
|
}
|
2020-03-27 22:26:22 +00:00
|
|
|
}
|
2020-02-23 17:50:59 +00:00
|
|
|
if err != nil {
|
|
|
|
return u, err
|
|
|
|
}
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelDebug, "user %q added/updated from pre-login hook response, id: %d", username, userID)
|
2021-01-05 08:50:22 +00:00
|
|
|
if userID == 0 {
|
2022-11-16 18:04:50 +00:00
|
|
|
return provider.userExists(username, "")
|
2021-01-05 08:50:22 +00:00
|
|
|
}
|
|
|
|
return u, nil
|
2020-02-23 17:50:59 +00:00
|
|
|
}
|
|
|
|
|
2020-08-12 14:15:12 +00:00
|
|
|
// ExecutePostLoginHook executes the post login hook if defined
|
2021-01-26 17:05:44 +00:00
|
|
|
func ExecutePostLoginHook(user *User, loginMethod, ip, protocol string, err error) {
|
2021-01-05 08:50:22 +00:00
|
|
|
if config.PostLoginHook == "" {
|
2020-08-12 14:15:12 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
if config.PostLoginScope == 1 && err == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if config.PostLoginScope == 2 && err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-01-26 17:05:44 +00:00
|
|
|
go func() {
|
2022-08-10 16:41:59 +00:00
|
|
|
actionsConcurrencyGuard <- struct{}{}
|
|
|
|
defer func() {
|
|
|
|
<-actionsConcurrencyGuard
|
|
|
|
}()
|
|
|
|
|
2021-01-26 17:05:44 +00:00
|
|
|
status := "0"
|
2020-08-12 14:15:12 +00:00
|
|
|
if err == nil {
|
2021-01-26 17:05:44 +00:00
|
|
|
status = "1"
|
|
|
|
}
|
|
|
|
|
2021-03-22 18:03:25 +00:00
|
|
|
user.PrepareForRendering()
|
2021-01-26 17:05:44 +00:00
|
|
|
userAsJSON, err := json.Marshal(user)
|
|
|
|
if err != nil {
|
2021-12-16 18:53:00 +00:00
|
|
|
providerLog(logger.LevelError, "error serializing user in post login hook: %v", err)
|
2021-01-26 17:05:44 +00:00
|
|
|
return
|
2020-08-12 14:15:12 +00:00
|
|
|
}
|
|
|
|
if strings.HasPrefix(config.PostLoginHook, "http") {
|
|
|
|
var url *url.URL
|
|
|
|
url, err := url.Parse(config.PostLoginHook)
|
|
|
|
if err != nil {
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelDebug, "Invalid post-login hook %q", config.PostLoginHook)
|
2020-08-12 14:15:12 +00:00
|
|
|
return
|
|
|
|
}
|
2021-01-26 17:05:44 +00:00
|
|
|
q := url.Query()
|
|
|
|
q.Add("login_method", loginMethod)
|
|
|
|
q.Add("ip", ip)
|
|
|
|
q.Add("protocol", protocol)
|
|
|
|
q.Add("status", status)
|
|
|
|
url.RawQuery = q.Encode()
|
|
|
|
|
2020-08-12 14:15:12 +00:00
|
|
|
startTime := time.Now()
|
|
|
|
respCode := 0
|
2021-05-25 06:36:01 +00:00
|
|
|
resp, err := httpclient.RetryablePost(url.String(), "application/json", bytes.NewBuffer(userAsJSON))
|
2020-08-12 14:15:12 +00:00
|
|
|
if err == nil {
|
|
|
|
respCode = resp.StatusCode
|
|
|
|
resp.Body.Close()
|
|
|
|
}
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelDebug, "post login hook executed for user %q, ip %v, protocol %v, response code: %v, elapsed: %v err: %v",
|
2021-07-24 18:11:17 +00:00
|
|
|
user.Username, ip, protocol, respCode, time.Since(startTime), err)
|
2020-08-12 14:15:12 +00:00
|
|
|
return
|
|
|
|
}
|
2022-09-20 11:58:44 +00:00
|
|
|
timeout, env, args := command.GetConfig(config.PostLoginHook, command.HookPostLogin)
|
2022-05-20 17:30:54 +00:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
2020-08-12 14:15:12 +00:00
|
|
|
defer cancel()
|
2022-05-20 17:30:54 +00:00
|
|
|
|
2022-09-20 11:58:44 +00:00
|
|
|
cmd := exec.CommandContext(ctx, config.PostLoginHook, args...)
|
2022-05-20 17:30:54 +00:00
|
|
|
cmd.Env = append(env,
|
2024-05-08 17:01:58 +00:00
|
|
|
fmt.Sprintf("SFTPGO_LOGIND_USER=%s", util.BytesToString(userAsJSON)),
|
2023-02-26 14:15:34 +00:00
|
|
|
fmt.Sprintf("SFTPGO_LOGIND_IP=%s", ip),
|
|
|
|
fmt.Sprintf("SFTPGO_LOGIND_METHOD=%s", loginMethod),
|
|
|
|
fmt.Sprintf("SFTPGO_LOGIND_STATUS=%s", status),
|
|
|
|
fmt.Sprintf("SFTPGO_LOGIND_PROTOCOL=%s", protocol))
|
2020-08-12 14:15:12 +00:00
|
|
|
startTime := time.Now()
|
|
|
|
err = cmd.Run()
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelDebug, "post login hook executed for user %q, ip %v, protocol %v, elapsed %v err: %v",
|
2021-07-24 18:11:17 +00:00
|
|
|
user.Username, ip, protocol, time.Since(startTime), err)
|
2021-01-26 17:05:44 +00:00
|
|
|
}()
|
2020-08-12 14:15:12 +00:00
|
|
|
}
|
|
|
|
|
2022-05-15 16:26:07 +00:00
|
|
|
func getExternalAuthResponse(username, password, pkey, keyboardInteractive, ip, protocol string, cert *x509.Certificate,
|
|
|
|
user User,
|
|
|
|
) ([]byte, error) {
|
2021-03-26 14:19:01 +00:00
|
|
|
var tlsCert string
|
|
|
|
if cert != nil {
|
|
|
|
var err error
|
2022-01-05 10:37:45 +00:00
|
|
|
tlsCert, err = util.EncodeTLSCertToPem(cert)
|
2021-03-26 14:19:01 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
2020-04-01 21:25:23 +00:00
|
|
|
if strings.HasPrefix(config.ExternalAuthHook, "http") {
|
|
|
|
var result []byte
|
2022-05-19 17:49:51 +00:00
|
|
|
authRequest := make(map[string]any)
|
2020-04-01 21:25:23 +00:00
|
|
|
authRequest["username"] = username
|
2020-08-04 16:03:28 +00:00
|
|
|
authRequest["ip"] = ip
|
2020-04-01 21:25:23 +00:00
|
|
|
authRequest["password"] = password
|
|
|
|
authRequest["public_key"] = pkey
|
2020-08-12 14:15:12 +00:00
|
|
|
authRequest["protocol"] = protocol
|
2020-04-01 21:25:23 +00:00
|
|
|
authRequest["keyboard_interactive"] = keyboardInteractive
|
2021-02-28 11:10:40 +00:00
|
|
|
authRequest["tls_cert"] = tlsCert
|
2022-05-15 16:26:07 +00:00
|
|
|
if user.ID > 0 {
|
|
|
|
authRequest["user"] = user
|
2021-03-26 14:19:01 +00:00
|
|
|
}
|
2020-04-01 21:25:23 +00:00
|
|
|
authRequestAsJSON, err := json.Marshal(authRequest)
|
|
|
|
if err != nil {
|
2021-12-16 18:53:00 +00:00
|
|
|
providerLog(logger.LevelError, "error serializing external auth request: %v", err)
|
2020-04-01 21:25:23 +00:00
|
|
|
return result, err
|
|
|
|
}
|
2021-05-25 06:36:01 +00:00
|
|
|
resp, err := httpclient.Post(config.ExternalAuthHook, "application/json", bytes.NewBuffer(authRequestAsJSON))
|
2020-04-01 21:25:23 +00:00
|
|
|
if err != nil {
|
|
|
|
providerLog(logger.LevelWarn, "error getting external auth hook HTTP response: %v", err)
|
|
|
|
return result, err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
2021-03-21 18:15:47 +00:00
|
|
|
providerLog(logger.LevelDebug, "external auth hook executed, response code: %v", resp.StatusCode)
|
2020-04-01 21:25:23 +00:00
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
|
|
return result, fmt.Errorf("wrong external auth http status code: %v, expected 200", resp.StatusCode)
|
|
|
|
}
|
2021-03-21 18:15:47 +00:00
|
|
|
|
2021-05-12 20:44:17 +00:00
|
|
|
return io.ReadAll(io.LimitReader(resp.Body, maxHookResponseSize))
|
2020-04-01 21:25:23 +00:00
|
|
|
}
|
2022-05-15 16:26:07 +00:00
|
|
|
var userAsJSON []byte
|
|
|
|
var err error
|
|
|
|
if user.ID > 0 {
|
|
|
|
userAsJSON, err = json.Marshal(user)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("unable to serialize user as JSON: %w", err)
|
|
|
|
}
|
|
|
|
}
|
2022-09-20 11:58:44 +00:00
|
|
|
timeout, env, args := command.GetConfig(config.ExternalAuthHook, command.HookExternalAuth)
|
2022-05-20 17:30:54 +00:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
2020-04-01 21:25:23 +00:00
|
|
|
defer cancel()
|
2022-05-15 16:26:07 +00:00
|
|
|
|
2022-09-20 11:58:44 +00:00
|
|
|
cmd := exec.CommandContext(ctx, config.ExternalAuthHook, args...)
|
2022-05-20 17:30:54 +00:00
|
|
|
cmd.Env = append(env,
|
2023-02-26 14:15:34 +00:00
|
|
|
fmt.Sprintf("SFTPGO_AUTHD_USERNAME=%s", username),
|
2024-05-08 17:01:58 +00:00
|
|
|
fmt.Sprintf("SFTPGO_AUTHD_USER=%s", util.BytesToString(userAsJSON)),
|
2023-02-26 14:15:34 +00:00
|
|
|
fmt.Sprintf("SFTPGO_AUTHD_IP=%s", ip),
|
|
|
|
fmt.Sprintf("SFTPGO_AUTHD_PASSWORD=%s", password),
|
|
|
|
fmt.Sprintf("SFTPGO_AUTHD_PUBLIC_KEY=%s", pkey),
|
|
|
|
fmt.Sprintf("SFTPGO_AUTHD_PROTOCOL=%s", protocol),
|
|
|
|
fmt.Sprintf("SFTPGO_AUTHD_TLS_CERT=%s", strings.ReplaceAll(tlsCert, "\n", "\\n")),
|
2020-04-01 21:25:23 +00:00
|
|
|
fmt.Sprintf("SFTPGO_AUTHD_KEYBOARD_INTERACTIVE=%v", keyboardInteractive))
|
2023-02-25 19:04:04 +00:00
|
|
|
|
2024-04-26 09:13:16 +00:00
|
|
|
return cmd.Output()
|
2020-04-01 21:25:23 +00:00
|
|
|
}
|
|
|
|
|
2021-03-27 18:10:27 +00:00
|
|
|
func updateUserFromExtAuthResponse(user *User, password, pkey string) {
|
|
|
|
if password != "" {
|
|
|
|
user.Password = password
|
|
|
|
}
|
2021-07-11 13:26:51 +00:00
|
|
|
if pkey != "" && !util.IsStringPrefixInSlice(pkey, user.PublicKeys) {
|
2021-03-27 18:10:27 +00:00
|
|
|
user.PublicKeys = append(user.PublicKeys, pkey)
|
|
|
|
}
|
2022-12-11 16:15:34 +00:00
|
|
|
user.LastPasswordChange = 0
|
2021-03-27 18:10:27 +00:00
|
|
|
}
|
|
|
|
|
2023-08-26 10:04:41 +00:00
|
|
|
func checkPasswordAfterEmptyExtAuthResponse(user *User, plainPwd, protocol string) error {
|
|
|
|
if plainPwd == "" {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
match, err := isPasswordOK(user, plainPwd)
|
|
|
|
if match && err == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
hashedPwd, err := hashPlainPassword(plainPwd)
|
|
|
|
if err != nil {
|
|
|
|
providerLog(logger.LevelError, "unable to hash password for user %q after empty external response: %v",
|
|
|
|
user.Username, err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
err = provider.updateUserPassword(user.Username, hashedPwd)
|
|
|
|
if err != nil {
|
|
|
|
providerLog(logger.LevelError, "unable to update password for user %q after empty external response: %v",
|
|
|
|
user.Username, err)
|
|
|
|
}
|
|
|
|
user.Password = hashedPwd
|
|
|
|
cachedUserPasswords.Add(user.Username, plainPwd, user.Password)
|
|
|
|
if protocol != protocolWebDAV {
|
|
|
|
webDAVUsersCache.swap(user, plainPwd)
|
|
|
|
}
|
|
|
|
providerLog(logger.LevelDebug, "updated password for user %q after empty external auth response", user.Username)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-02-25 10:51:10 +00:00
|
|
|
func doExternalAuth(username, password string, pubKey []byte, keyboardInteractive, ip, protocol string,
|
|
|
|
tlsCert *x509.Certificate,
|
|
|
|
) (User, error) {
|
2020-01-06 20:42:41 +00:00
|
|
|
var user User
|
2021-03-26 14:19:01 +00:00
|
|
|
|
2022-05-15 16:26:07 +00:00
|
|
|
u, mergedUser, err := getUserForHook(username, nil)
|
2021-03-26 14:19:01 +00:00
|
|
|
if err != nil {
|
|
|
|
return user, err
|
2020-01-06 20:42:41 +00:00
|
|
|
}
|
2021-04-04 20:32:25 +00:00
|
|
|
|
2023-05-20 10:39:07 +00:00
|
|
|
if mergedUser.skipExternalAuth() {
|
2022-02-25 10:51:10 +00:00
|
|
|
return u, nil
|
|
|
|
}
|
|
|
|
|
2021-07-11 13:26:51 +00:00
|
|
|
pkey, err := util.GetSSHPublicKeyAsString(pubKey)
|
2021-03-26 14:19:01 +00:00
|
|
|
if err != nil {
|
|
|
|
return user, err
|
2021-02-28 11:10:40 +00:00
|
|
|
}
|
2021-03-26 14:19:01 +00:00
|
|
|
|
2021-03-21 18:15:47 +00:00
|
|
|
startTime := time.Now()
|
2022-05-15 16:26:07 +00:00
|
|
|
out, err := getExternalAuthResponse(username, password, pkey, keyboardInteractive, ip, protocol, tlsCert, u)
|
2020-01-06 20:42:41 +00:00
|
|
|
if err != nil {
|
2023-02-26 14:15:34 +00:00
|
|
|
return user, fmt.Errorf("external auth error for user %q, elapsed: %s: %w", username, time.Since(startTime), err)
|
2020-01-06 20:42:41 +00:00
|
|
|
}
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelDebug, "external auth completed for user %q, elapsed: %s", username, time.Since(startTime))
|
2021-07-11 13:26:51 +00:00
|
|
|
if util.IsByteArrayEmpty(out) {
|
2023-02-26 14:15:34 +00:00
|
|
|
providerLog(logger.LevelDebug, "empty response from external hook, no modification requested for user %q, id: %d",
|
2021-03-26 14:19:01 +00:00
|
|
|
username, u.ID)
|
|
|
|
if u.ID == 0 {
|
2023-02-26 14:15:34 +00:00
|
|
|
return u, util.NewRecordNotFoundError(fmt.Sprintf("username %q does not exist", username))
|
2021-03-26 14:19:01 +00:00
|
|
|
}
|
2023-08-26 10:04:41 +00:00
|
|
|
err = checkPasswordAfterEmptyExtAuthResponse(&u, password, protocol)
|
|
|
|
return u, err
|
2021-03-26 14:19:01 +00:00
|
|
|
}
|
2020-01-06 20:42:41 +00:00
|
|
|
err = json.Unmarshal(out, &user)
|
|
|
|
if err != nil {
|
2021-03-21 18:15:47 +00:00
|
|
|
return user, fmt.Errorf("invalid external auth response: %v", err)
|
2020-01-06 20:42:41 +00:00
|
|
|
}
|
2021-03-27 18:10:27 +00:00
|
|
|
// an empty username means authentication failure
|
2021-02-11 18:45:52 +00:00
|
|
|
if user.Username == "" {
|
2020-08-31 17:25:17 +00:00
|
|
|
return user, ErrInvalidCredentials
|
2020-01-06 20:42:41 +00:00
|
|
|
}
|
2021-03-27 18:10:27 +00:00
|
|
|
updateUserFromExtAuthResponse(&user, password, pkey)
|
2021-01-05 08:50:22 +00:00
|
|
|
// some users want to map multiple login usernames with a single SFTPGo account
|
2020-06-08 11:06:02 +00:00
|
|
|
// for example an SFTP user logins using "user1" or "user2" and the external auth
|
|
|
|
// returns "user" in both cases, so we use the username returned from
|
|
|
|
// external auth and not the one used to login
|
2021-03-26 14:19:01 +00:00
|
|
|
if user.Username != username {
|
2022-11-16 18:04:50 +00:00
|
|
|
u, err = provider.userExists(user.Username, "")
|
2021-03-26 14:19:01 +00:00
|
|
|
}
|
|
|
|
if u.ID > 0 && err == nil {
|
2020-01-06 20:42:41 +00:00
|
|
|
user.ID = u.ID
|
|
|
|
user.UsedQuotaSize = u.UsedQuotaSize
|
|
|
|
user.UsedQuotaFiles = u.UsedQuotaFiles
|
2022-01-30 10:42:36 +00:00
|
|
|
user.UsedUploadDataTransfer = u.UsedUploadDataTransfer
|
|
|
|
user.UsedDownloadDataTransfer = u.UsedDownloadDataTransfer
|
2020-01-06 20:42:41 +00:00
|
|
|
user.LastQuotaUpdate = u.LastQuotaUpdate
|
|
|
|
user.LastLogin = u.LastLogin
|
2022-12-11 16:15:34 +00:00
|
|
|
user.LastPasswordChange = u.LastPasswordChange
|
2022-08-21 17:01:08 +00:00
|
|
|
user.FirstDownload = u.FirstDownload
|
|
|
|
user.FirstUpload = u.FirstUpload
|
2021-08-19 13:51:43 +00:00
|
|
|
user.CreatedAt = u.CreatedAt
|
|
|
|
user.UpdatedAt = util.GetTimeAsMsSinceEpoch(time.Now())
|
2021-12-11 10:08:20 +00:00
|
|
|
// preserve TOTP config and recovery codes
|
|
|
|
user.Filters.TOTPConfig = u.Filters.TOTPConfig
|
|
|
|
user.Filters.RecoveryCodes = u.Filters.RecoveryCodes
|
2024-06-04 16:14:09 +00:00
|
|
|
user, err = updateUserAfterExternalAuth(&user)
|
2021-03-27 18:10:27 +00:00
|
|
|
if err == nil {
|
2023-05-20 10:39:07 +00:00
|
|
|
if protocol != protocolWebDAV {
|
|
|
|
webDAVUsersCache.swap(&user, password)
|
|
|
|
}
|
2023-04-13 16:23:42 +00:00
|
|
|
cachedUserPasswords.Add(user.Username, password, user.Password)
|
2024-09-06 17:17:31 +00:00
|
|
|
executeAction(operationUpdate, ActionExecutorSelf, "", actionObjectUser, user.Username, "", &user)
|
2021-08-08 15:09:48 +00:00
|
|
|
}
|
|
|
|
return user, err
|
|
|
|
}
|
|
|
|
err = provider.addUser(&user)
|
|
|
|
if err != nil {
|
|
|
|
return user, err
|
|
|
|
}
|
2024-09-06 17:17:31 +00:00
|
|
|
executeAction(operationAdd, ActionExecutorSelf, "", actionObjectUser, user.Username, "", &user)
|
2022-11-16 18:04:50 +00:00
|
|
|
return provider.userExists(user.Username, "")
|
2021-08-08 15:09:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func doPluginAuth(username, password string, pubKey []byte, ip, protocol string,
|
|
|
|
tlsCert *x509.Certificate, authScope int,
|
|
|
|
) (User, error) {
|
|
|
|
var user User
|
|
|
|
|
2022-04-25 13:49:11 +00:00
|
|
|
u, mergedUser, userAsJSON, err := getUserAndJSONForHook(username, nil)
|
2021-08-08 15:09:48 +00:00
|
|
|
if err != nil {
|
|
|
|
return user, err
|
|
|
|
}
|
|
|
|
|
2023-05-20 10:39:07 +00:00
|
|
|
if mergedUser.skipExternalAuth() {
|
2022-02-25 10:51:10 +00:00
|
|
|
return u, nil
|
|
|
|
}
|
|
|
|
|
2021-08-08 15:09:48 +00:00
|
|
|
pkey, err := util.GetSSHPublicKeyAsString(pubKey)
|
|
|
|
if err != nil {
|
|
|
|
return user, err
|
|
|
|
}
|
|
|
|
|
|
|
|
startTime := time.Now()
|
|
|
|
|
|
|
|
out, err := plugin.Handler.Authenticate(username, password, ip, protocol, pkey, tlsCert, authScope, userAsJSON)
|
|
|
|
if err != nil {
|
2023-08-26 10:04:41 +00:00
|
|
|
return user, fmt.Errorf("plugin auth error for user %q: %v, elapsed: %v, auth scope: %d",
|
2021-08-08 15:09:48 +00:00
|
|
|
username, err, time.Since(startTime), authScope)
|
|
|
|
}
|
2023-08-26 10:04:41 +00:00
|
|
|
providerLog(logger.LevelDebug, "plugin auth completed for user %q, elapsed: %v, auth scope: %d",
|
2021-08-08 15:09:48 +00:00
|
|
|
username, time.Since(startTime), authScope)
|
|
|
|
if util.IsByteArrayEmpty(out) {
|
2023-08-26 10:04:41 +00:00
|
|
|
providerLog(logger.LevelDebug, "empty response from plugin auth, no modification requested for user %q id: %d, auth scope: %d",
|
|
|
|
username, u.ID, authScope)
|
2021-08-08 15:09:48 +00:00
|
|
|
if u.ID == 0 {
|
2023-02-26 14:15:34 +00:00
|
|
|
return u, util.NewRecordNotFoundError(fmt.Sprintf("username %q does not exist", username))
|
2021-08-08 15:09:48 +00:00
|
|
|
}
|
2023-08-26 10:04:41 +00:00
|
|
|
err = checkPasswordAfterEmptyExtAuthResponse(&u, password, protocol)
|
|
|
|
return u, err
|
2021-08-08 15:09:48 +00:00
|
|
|
}
|
|
|
|
err = json.Unmarshal(out, &user)
|
|
|
|
if err != nil {
|
|
|
|
return user, fmt.Errorf("invalid plugin auth response: %v", err)
|
|
|
|
}
|
|
|
|
updateUserFromExtAuthResponse(&user, password, pkey)
|
|
|
|
if u.ID > 0 {
|
|
|
|
user.ID = u.ID
|
|
|
|
user.UsedQuotaSize = u.UsedQuotaSize
|
|
|
|
user.UsedQuotaFiles = u.UsedQuotaFiles
|
2022-01-30 10:42:36 +00:00
|
|
|
user.UsedUploadDataTransfer = u.UsedUploadDataTransfer
|
|
|
|
user.UsedDownloadDataTransfer = u.UsedDownloadDataTransfer
|
2021-08-08 15:09:48 +00:00
|
|
|
user.LastQuotaUpdate = u.LastQuotaUpdate
|
|
|
|
user.LastLogin = u.LastLogin
|
2022-12-11 16:15:34 +00:00
|
|
|
user.LastPasswordChange = u.LastPasswordChange
|
2022-08-21 17:01:08 +00:00
|
|
|
user.FirstDownload = u.FirstDownload
|
|
|
|
user.FirstUpload = u.FirstUpload
|
2021-12-11 10:08:20 +00:00
|
|
|
// preserve TOTP config and recovery codes
|
|
|
|
user.Filters.TOTPConfig = u.Filters.TOTPConfig
|
|
|
|
user.Filters.RecoveryCodes = u.Filters.RecoveryCodes
|
2024-06-04 16:14:09 +00:00
|
|
|
user, err = updateUserAfterExternalAuth(&user)
|
2021-08-08 15:09:48 +00:00
|
|
|
if err == nil {
|
2023-05-20 10:39:07 +00:00
|
|
|
if protocol != protocolWebDAV {
|
|
|
|
webDAVUsersCache.swap(&user, password)
|
|
|
|
}
|
2023-04-13 16:23:42 +00:00
|
|
|
cachedUserPasswords.Add(user.Username, password, user.Password)
|
2024-09-06 17:17:31 +00:00
|
|
|
executeAction(operationUpdate, ActionExecutorSelf, "", actionObjectUser, user.Username, "", &user)
|
2021-03-27 18:10:27 +00:00
|
|
|
}
|
2021-01-05 08:50:22 +00:00
|
|
|
return user, err
|
2020-01-06 20:42:41 +00:00
|
|
|
}
|
2021-01-05 08:50:22 +00:00
|
|
|
err = provider.addUser(&user)
|
2020-01-06 20:42:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return user, err
|
|
|
|
}
|
2024-09-06 17:17:31 +00:00
|
|
|
executeAction(operationAdd, ActionExecutorSelf, "", actionObjectUser, user.Username, "", &user)
|
2022-11-16 18:04:50 +00:00
|
|
|
return provider.userExists(user.Username, "")
|
2020-01-06 20:42:41 +00:00
|
|
|
}
|
|
|
|
|
2024-06-04 16:14:09 +00:00
|
|
|
func updateUserAfterExternalAuth(user *User) (User, error) {
|
|
|
|
if err := provider.updateUser(user); err != nil {
|
|
|
|
return *user, err
|
|
|
|
}
|
|
|
|
return provider.userExists(user.Username, "")
|
|
|
|
}
|
|
|
|
|
2022-05-19 17:49:51 +00:00
|
|
|
func getUserForHook(username string, oidcTokenFields *map[string]any) (User, User, error) {
|
2022-11-16 18:04:50 +00:00
|
|
|
u, err := provider.userExists(username, "")
|
2021-03-26 14:19:01 +00:00
|
|
|
if err != nil {
|
2023-01-25 17:49:03 +00:00
|
|
|
if !errors.Is(err, util.ErrNotFound) {
|
2022-05-15 16:26:07 +00:00
|
|
|
return u, u, err
|
2021-03-26 14:19:01 +00:00
|
|
|
}
|
|
|
|
u = User{
|
2021-07-11 13:26:51 +00:00
|
|
|
BaseUser: sdk.BaseUser{
|
|
|
|
ID: 0,
|
|
|
|
Username: username,
|
|
|
|
},
|
2021-03-26 14:19:01 +00:00
|
|
|
}
|
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
mergedUser := u.getACopy()
|
|
|
|
err = mergedUser.LoadAndApplyGroupSettings()
|
|
|
|
if err != nil {
|
2022-05-15 16:26:07 +00:00
|
|
|
return u, mergedUser, err
|
2022-04-25 13:49:11 +00:00
|
|
|
}
|
|
|
|
|
2022-04-12 17:31:25 +00:00
|
|
|
u.OIDCCustomFields = oidcTokenFields
|
2022-05-15 16:26:07 +00:00
|
|
|
return u, mergedUser, err
|
|
|
|
}
|
|
|
|
|
2022-05-19 17:49:51 +00:00
|
|
|
func getUserAndJSONForHook(username string, oidcTokenFields *map[string]any) (User, User, []byte, error) {
|
2022-05-15 16:26:07 +00:00
|
|
|
u, mergedUser, err := getUserForHook(username, oidcTokenFields)
|
|
|
|
if err != nil {
|
|
|
|
return u, mergedUser, nil, err
|
|
|
|
}
|
|
|
|
userAsJSON, err := json.Marshal(u)
|
2021-03-26 14:19:01 +00:00
|
|
|
if err != nil {
|
2022-04-25 13:49:11 +00:00
|
|
|
return u, mergedUser, userAsJSON, err
|
2021-03-26 14:19:01 +00:00
|
|
|
}
|
2022-04-25 13:49:11 +00:00
|
|
|
return u, mergedUser, userAsJSON, err
|
2021-03-26 14:19:01 +00:00
|
|
|
}
|
|
|
|
|
2022-02-25 10:51:10 +00:00
|
|
|
func isLastActivityRecent(lastActivity int64, minDelay time.Duration) bool {
|
2022-02-24 15:11:35 +00:00
|
|
|
lastActivityTime := util.GetTimeFromMsecSinceEpoch(lastActivity)
|
|
|
|
diff := -time.Until(lastActivityTime)
|
|
|
|
if diff < -10*time.Second {
|
|
|
|
return false
|
|
|
|
}
|
2022-02-25 10:51:10 +00:00
|
|
|
return diff < minDelay
|
|
|
|
}
|
|
|
|
|
2023-05-20 10:39:07 +00:00
|
|
|
func isExternalAuthConfigured(loginMethod string) bool {
|
|
|
|
if config.ExternalAuthHook != "" {
|
|
|
|
if config.ExternalAuthScope == 0 {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
switch loginMethod {
|
|
|
|
case LoginMethodPassword:
|
|
|
|
return config.ExternalAuthScope&1 != 0
|
|
|
|
case LoginMethodTLSCertificate:
|
|
|
|
return config.ExternalAuthScope&8 != 0
|
|
|
|
case LoginMethodTLSCertificateAndPwd:
|
|
|
|
return config.ExternalAuthScope&1 != 0 || config.ExternalAuthScope&8 != 0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
switch loginMethod {
|
|
|
|
case LoginMethodPassword:
|
|
|
|
return plugin.Handler.HasAuthScope(plugin.AuthScopePassword)
|
|
|
|
case LoginMethodTLSCertificate:
|
|
|
|
return plugin.Handler.HasAuthScope(plugin.AuthScopeTLSCertificate)
|
|
|
|
case LoginMethodTLSCertificateAndPwd:
|
|
|
|
return plugin.Handler.HasAuthScope(plugin.AuthScopePassword) ||
|
|
|
|
plugin.Handler.HasAuthScope(plugin.AuthScopeTLSCertificate)
|
|
|
|
default:
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-13 12:45:07 +00:00
|
|
|
func getConfigPath(name, configDir string) string {
|
|
|
|
if !util.IsFileInputValid(name) {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
if name != "" && !filepath.IsAbs(name) {
|
|
|
|
return filepath.Join(configDir, name)
|
|
|
|
}
|
|
|
|
return name
|
|
|
|
}
|
|
|
|
|
2022-09-13 16:04:27 +00:00
|
|
|
func checkReservedUsernames(username string) error {
|
2024-07-24 16:27:13 +00:00
|
|
|
if slices.Contains(reservedUsers, username) {
|
2022-09-13 16:04:27 +00:00
|
|
|
return util.NewValidationError("this username is reserved")
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-05-19 17:49:51 +00:00
|
|
|
func providerLog(level logger.LogLevel, format string, v ...any) {
|
2022-02-25 10:51:10 +00:00
|
|
|
logger.Log(level, logSender, "", format, v...)
|
2022-02-24 15:11:35 +00:00
|
|
|
}
|