portable.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. // Copyright (C) 2019-2023 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. //go:build !noportable
  15. // +build !noportable
  16. package cmd
  17. import (
  18. "fmt"
  19. "os"
  20. "path"
  21. "path/filepath"
  22. "strings"
  23. "github.com/sftpgo/sdk"
  24. "github.com/spf13/cobra"
  25. "github.com/drakkan/sftpgo/v2/internal/common"
  26. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  27. "github.com/drakkan/sftpgo/v2/internal/kms"
  28. "github.com/drakkan/sftpgo/v2/internal/service"
  29. "github.com/drakkan/sftpgo/v2/internal/sftpd"
  30. "github.com/drakkan/sftpgo/v2/internal/version"
  31. "github.com/drakkan/sftpgo/v2/internal/vfs"
  32. )
  33. var (
  34. directoryToServe string
  35. portableSFTPDPort int
  36. portableUsername string
  37. portablePassword string
  38. portableStartDir string
  39. portableLogFile string
  40. portableLogLevel string
  41. portableLogUTCTime bool
  42. portablePublicKeys []string
  43. portablePermissions []string
  44. portableSSHCommands []string
  45. portableAllowedPatterns []string
  46. portableDeniedPatterns []string
  47. portableFsProvider string
  48. portableS3Bucket string
  49. portableS3Region string
  50. portableS3AccessKey string
  51. portableS3AccessSecret string
  52. portableS3RoleARN string
  53. portableS3Endpoint string
  54. portableS3StorageClass string
  55. portableS3ACL string
  56. portableS3KeyPrefix string
  57. portableS3ULPartSize int
  58. portableS3ULConcurrency int
  59. portableS3ForcePathStyle bool
  60. portableGCSBucket string
  61. portableGCSCredentialsFile string
  62. portableGCSAutoCredentials int
  63. portableGCSStorageClass string
  64. portableGCSKeyPrefix string
  65. portableFTPDPort int
  66. portableFTPSCert string
  67. portableFTPSKey string
  68. portableWebDAVPort int
  69. portableWebDAVCert string
  70. portableWebDAVKey string
  71. portableAzContainer string
  72. portableAzAccountName string
  73. portableAzAccountKey string
  74. portableAzEndpoint string
  75. portableAzAccessTier string
  76. portableAzSASURL string
  77. portableAzKeyPrefix string
  78. portableAzULPartSize int
  79. portableAzULConcurrency int
  80. portableAzDLPartSize int
  81. portableAzDLConcurrency int
  82. portableAzUseEmulator bool
  83. portableCryptPassphrase string
  84. portableSFTPEndpoint string
  85. portableSFTPUsername string
  86. portableSFTPPassword string
  87. portableSFTPPrivateKeyPath string
  88. portableSFTPFingerprints []string
  89. portableSFTPPrefix string
  90. portableSFTPDisableConcurrentReads bool
  91. portableSFTPDBufferSize int64
  92. portableCmd = &cobra.Command{
  93. Use: "portable",
  94. Short: "Serve a single directory/account",
  95. Long: `To serve the current working directory with auto generated credentials simply
  96. use:
  97. $ sftpgo portable
  98. Please take a look at the usage below to customize the serving parameters`,
  99. Run: func(_ *cobra.Command, _ []string) {
  100. portableDir := directoryToServe
  101. fsProvider := sdk.GetProviderByName(portableFsProvider)
  102. if !filepath.IsAbs(portableDir) {
  103. if fsProvider == sdk.LocalFilesystemProvider {
  104. portableDir, _ = filepath.Abs(portableDir)
  105. } else {
  106. portableDir = os.TempDir()
  107. }
  108. }
  109. permissions := make(map[string][]string)
  110. permissions["/"] = portablePermissions
  111. portableGCSCredentials := ""
  112. if fsProvider == sdk.GCSFilesystemProvider && portableGCSCredentialsFile != "" {
  113. contents, err := getFileContents(portableGCSCredentialsFile)
  114. if err != nil {
  115. fmt.Printf("Unable to get GCS credentials: %v\n", err)
  116. os.Exit(1)
  117. }
  118. portableGCSCredentials = contents
  119. portableGCSAutoCredentials = 0
  120. }
  121. portableSFTPPrivateKey := ""
  122. if fsProvider == sdk.SFTPFilesystemProvider && portableSFTPPrivateKeyPath != "" {
  123. contents, err := getFileContents(portableSFTPPrivateKeyPath)
  124. if err != nil {
  125. fmt.Printf("Unable to get SFTP private key: %v\n", err)
  126. os.Exit(1)
  127. }
  128. portableSFTPPrivateKey = contents
  129. }
  130. if portableFTPDPort >= 0 && portableFTPSCert != "" && portableFTPSKey != "" {
  131. keyPairs := []common.TLSKeyPair{
  132. {
  133. Cert: portableFTPSCert,
  134. Key: portableFTPSKey,
  135. ID: common.DefaultTLSKeyPaidID,
  136. },
  137. }
  138. _, err := common.NewCertManager(keyPairs, filepath.Clean(defaultConfigDir),
  139. "FTP portable")
  140. if err != nil {
  141. fmt.Printf("Unable to load FTPS key pair, cert file %#v key file %#v error: %v\n",
  142. portableFTPSCert, portableFTPSKey, err)
  143. os.Exit(1)
  144. }
  145. }
  146. if portableWebDAVPort > 0 && portableWebDAVCert != "" && portableWebDAVKey != "" {
  147. keyPairs := []common.TLSKeyPair{
  148. {
  149. Cert: portableWebDAVCert,
  150. Key: portableWebDAVKey,
  151. ID: common.DefaultTLSKeyPaidID,
  152. },
  153. }
  154. _, err := common.NewCertManager(keyPairs, filepath.Clean(defaultConfigDir),
  155. "WebDAV portable")
  156. if err != nil {
  157. fmt.Printf("Unable to load WebDAV key pair, cert file %#v key file %#v error: %v\n",
  158. portableWebDAVCert, portableWebDAVKey, err)
  159. os.Exit(1)
  160. }
  161. }
  162. service.SetGraceTime(graceTime)
  163. service := service.Service{
  164. ConfigDir: filepath.Clean(defaultConfigDir),
  165. ConfigFile: defaultConfigFile,
  166. LogFilePath: portableLogFile,
  167. LogMaxSize: defaultLogMaxSize,
  168. LogMaxBackups: defaultLogMaxBackup,
  169. LogMaxAge: defaultLogMaxAge,
  170. LogCompress: defaultLogCompress,
  171. LogLevel: portableLogLevel,
  172. LogUTCTime: portableLogUTCTime,
  173. Shutdown: make(chan bool),
  174. PortableMode: 1,
  175. PortableUser: dataprovider.User{
  176. BaseUser: sdk.BaseUser{
  177. Username: portableUsername,
  178. Password: portablePassword,
  179. PublicKeys: portablePublicKeys,
  180. Permissions: permissions,
  181. HomeDir: portableDir,
  182. Status: 1,
  183. },
  184. Filters: dataprovider.UserFilters{
  185. BaseUserFilters: sdk.BaseUserFilters{
  186. FilePatterns: parsePatternsFilesFilters(),
  187. StartDirectory: portableStartDir,
  188. },
  189. },
  190. FsConfig: vfs.Filesystem{
  191. Provider: sdk.GetProviderByName(portableFsProvider),
  192. S3Config: vfs.S3FsConfig{
  193. BaseS3FsConfig: sdk.BaseS3FsConfig{
  194. Bucket: portableS3Bucket,
  195. Region: portableS3Region,
  196. AccessKey: portableS3AccessKey,
  197. RoleARN: portableS3RoleARN,
  198. Endpoint: portableS3Endpoint,
  199. StorageClass: portableS3StorageClass,
  200. ACL: portableS3ACL,
  201. KeyPrefix: portableS3KeyPrefix,
  202. UploadPartSize: int64(portableS3ULPartSize),
  203. UploadConcurrency: portableS3ULConcurrency,
  204. ForcePathStyle: portableS3ForcePathStyle,
  205. },
  206. AccessSecret: kms.NewPlainSecret(portableS3AccessSecret),
  207. },
  208. GCSConfig: vfs.GCSFsConfig{
  209. BaseGCSFsConfig: sdk.BaseGCSFsConfig{
  210. Bucket: portableGCSBucket,
  211. AutomaticCredentials: portableGCSAutoCredentials,
  212. StorageClass: portableGCSStorageClass,
  213. KeyPrefix: portableGCSKeyPrefix,
  214. },
  215. Credentials: kms.NewPlainSecret(portableGCSCredentials),
  216. },
  217. AzBlobConfig: vfs.AzBlobFsConfig{
  218. BaseAzBlobFsConfig: sdk.BaseAzBlobFsConfig{
  219. Container: portableAzContainer,
  220. AccountName: portableAzAccountName,
  221. Endpoint: portableAzEndpoint,
  222. AccessTier: portableAzAccessTier,
  223. KeyPrefix: portableAzKeyPrefix,
  224. UseEmulator: portableAzUseEmulator,
  225. UploadPartSize: int64(portableAzULPartSize),
  226. UploadConcurrency: portableAzULConcurrency,
  227. DownloadPartSize: int64(portableAzDLPartSize),
  228. DownloadConcurrency: portableAzDLConcurrency,
  229. },
  230. AccountKey: kms.NewPlainSecret(portableAzAccountKey),
  231. SASURL: kms.NewPlainSecret(portableAzSASURL),
  232. },
  233. CryptConfig: vfs.CryptFsConfig{
  234. Passphrase: kms.NewPlainSecret(portableCryptPassphrase),
  235. },
  236. SFTPConfig: vfs.SFTPFsConfig{
  237. BaseSFTPFsConfig: sdk.BaseSFTPFsConfig{
  238. Endpoint: portableSFTPEndpoint,
  239. Username: portableSFTPUsername,
  240. Fingerprints: portableSFTPFingerprints,
  241. Prefix: portableSFTPPrefix,
  242. DisableCouncurrentReads: portableSFTPDisableConcurrentReads,
  243. BufferSize: portableSFTPDBufferSize,
  244. },
  245. Password: kms.NewPlainSecret(portableSFTPPassword),
  246. PrivateKey: kms.NewPlainSecret(portableSFTPPrivateKey),
  247. },
  248. },
  249. },
  250. }
  251. err := service.StartPortableMode(portableSFTPDPort, portableFTPDPort, portableWebDAVPort, portableSSHCommands,
  252. portableFTPSCert, portableFTPSKey, portableWebDAVCert,
  253. portableWebDAVKey)
  254. if err == nil {
  255. service.Wait()
  256. if service.Error == nil {
  257. os.Exit(0)
  258. }
  259. }
  260. os.Exit(1)
  261. },
  262. }
  263. )
  264. func init() {
  265. version.AddFeature("+portable")
  266. portableCmd.Flags().StringVarP(&directoryToServe, "directory", "d", ".", `Path to the directory to serve.
  267. This can be an absolute path or a path
  268. relative to the current directory
  269. `)
  270. portableCmd.Flags().StringVar(&portableStartDir, "start-directory", "/", `Alternate start directory.
  271. This is a virtual path not a filesystem
  272. path`)
  273. portableCmd.Flags().IntVarP(&portableSFTPDPort, "sftpd-port", "s", 0, `0 means a random unprivileged port,
  274. < 0 disabled`)
  275. portableCmd.Flags().IntVar(&portableFTPDPort, "ftpd-port", -1, `0 means a random unprivileged port,
  276. < 0 disabled`)
  277. portableCmd.Flags().IntVar(&portableWebDAVPort, "webdav-port", -1, `0 means a random unprivileged port,
  278. < 0 disabled`)
  279. portableCmd.Flags().StringSliceVarP(&portableSSHCommands, "ssh-commands", "c", sftpd.GetDefaultSSHCommands(),
  280. `SSH commands to enable.
  281. "*" means any supported SSH command
  282. including scp
  283. `)
  284. portableCmd.Flags().StringVarP(&portableUsername, "username", "u", "", `Leave empty to use an auto generated
  285. value`)
  286. portableCmd.Flags().StringVarP(&portablePassword, "password", "p", "", `Leave empty to use an auto generated
  287. value`)
  288. portableCmd.Flags().StringVarP(&portableLogFile, logFilePathFlag, "l", "", "Leave empty to disable logging")
  289. portableCmd.Flags().StringVar(&portableLogLevel, logLevelFlag, defaultLogLevel, `Set the log level.
  290. Supported values:
  291. debug, info, warn, error.
  292. `)
  293. portableCmd.Flags().BoolVar(&portableLogUTCTime, logUTCTimeFlag, false, "Use UTC time for logging")
  294. portableCmd.Flags().StringSliceVarP(&portablePublicKeys, "public-key", "k", []string{}, "")
  295. portableCmd.Flags().StringSliceVarP(&portablePermissions, "permissions", "g", []string{"list", "download"},
  296. `User's permissions. "*" means any
  297. permission`)
  298. portableCmd.Flags().StringArrayVar(&portableAllowedPatterns, "allowed-patterns", []string{},
  299. `Allowed file patterns case insensitive.
  300. The format is:
  301. /dir::pattern1,pattern2.
  302. For example: "/somedir::*.jpg,a*b?.png"`)
  303. portableCmd.Flags().StringArrayVar(&portableDeniedPatterns, "denied-patterns", []string{},
  304. `Denied file patterns case insensitive.
  305. The format is:
  306. /dir::pattern1,pattern2.
  307. For example: "/somedir::*.jpg,a*b?.png"`)
  308. portableCmd.Flags().StringVarP(&portableFsProvider, "fs-provider", "f", "osfs", `osfs => local filesystem (legacy value: 0)
  309. s3fs => AWS S3 compatible (legacy: 1)
  310. gcsfs => Google Cloud Storage (legacy: 2)
  311. azblobfs => Azure Blob Storage (legacy: 3)
  312. cryptfs => Encrypted local filesystem (legacy: 4)
  313. sftpfs => SFTP (legacy: 5)`)
  314. portableCmd.Flags().StringVar(&portableS3Bucket, "s3-bucket", "", "")
  315. portableCmd.Flags().StringVar(&portableS3Region, "s3-region", "", "")
  316. portableCmd.Flags().StringVar(&portableS3AccessKey, "s3-access-key", "", "")
  317. portableCmd.Flags().StringVar(&portableS3AccessSecret, "s3-access-secret", "", "")
  318. portableCmd.Flags().StringVar(&portableS3RoleARN, "s3-role-arn", "", "")
  319. portableCmd.Flags().StringVar(&portableS3Endpoint, "s3-endpoint", "", "")
  320. portableCmd.Flags().StringVar(&portableS3StorageClass, "s3-storage-class", "", "")
  321. portableCmd.Flags().StringVar(&portableS3ACL, "s3-acl", "", "")
  322. portableCmd.Flags().StringVar(&portableS3KeyPrefix, "s3-key-prefix", "", `Allows to restrict access to the
  323. virtual folder identified by this
  324. prefix and its contents`)
  325. portableCmd.Flags().IntVar(&portableS3ULPartSize, "s3-upload-part-size", 5, `The buffer size for multipart uploads
  326. (MB)`)
  327. portableCmd.Flags().IntVar(&portableS3ULConcurrency, "s3-upload-concurrency", 2, `How many parts are uploaded in
  328. parallel`)
  329. portableCmd.Flags().BoolVar(&portableS3ForcePathStyle, "s3-force-path-style", false, `Force path style bucket URL`)
  330. portableCmd.Flags().StringVar(&portableGCSBucket, "gcs-bucket", "", "")
  331. portableCmd.Flags().StringVar(&portableGCSStorageClass, "gcs-storage-class", "", "")
  332. portableCmd.Flags().StringVar(&portableGCSKeyPrefix, "gcs-key-prefix", "", `Allows to restrict access to the
  333. virtual folder identified by this
  334. prefix and its contents`)
  335. portableCmd.Flags().StringVar(&portableGCSCredentialsFile, "gcs-credentials-file", "", `Google Cloud Storage JSON credentials
  336. file`)
  337. portableCmd.Flags().IntVar(&portableGCSAutoCredentials, "gcs-automatic-credentials", 1, `0 means explicit credentials using
  338. a JSON credentials file, 1 automatic
  339. `)
  340. portableCmd.Flags().StringVar(&portableFTPSCert, "ftpd-cert", "", "Path to the certificate file for FTPS")
  341. portableCmd.Flags().StringVar(&portableFTPSKey, "ftpd-key", "", "Path to the key file for FTPS")
  342. portableCmd.Flags().StringVar(&portableWebDAVCert, "webdav-cert", "", `Path to the certificate file for WebDAV
  343. over HTTPS`)
  344. portableCmd.Flags().StringVar(&portableWebDAVKey, "webdav-key", "", `Path to the key file for WebDAV over
  345. HTTPS`)
  346. portableCmd.Flags().StringVar(&portableAzContainer, "az-container", "", "")
  347. portableCmd.Flags().StringVar(&portableAzAccountName, "az-account-name", "", "")
  348. portableCmd.Flags().StringVar(&portableAzAccountKey, "az-account-key", "", "")
  349. portableCmd.Flags().StringVar(&portableAzSASURL, "az-sas-url", "", `Shared access signature URL`)
  350. portableCmd.Flags().StringVar(&portableAzEndpoint, "az-endpoint", "", `Leave empty to use the default:
  351. "blob.core.windows.net"`)
  352. portableCmd.Flags().StringVar(&portableAzAccessTier, "az-access-tier", "", `Leave empty to use the default
  353. container setting`)
  354. portableCmd.Flags().StringVar(&portableAzKeyPrefix, "az-key-prefix", "", `Allows to restrict access to the
  355. virtual folder identified by this
  356. prefix and its contents`)
  357. portableCmd.Flags().IntVar(&portableAzULPartSize, "az-upload-part-size", 5, `The buffer size for multipart uploads
  358. (MB)`)
  359. portableCmd.Flags().IntVar(&portableAzULConcurrency, "az-upload-concurrency", 5, `How many parts are uploaded in
  360. parallel`)
  361. portableCmd.Flags().IntVar(&portableAzDLPartSize, "az-download-part-size", 5, `The buffer size for multipart downloads
  362. (MB)`)
  363. portableCmd.Flags().IntVar(&portableAzDLConcurrency, "az-download-concurrency", 5, `How many parts are downloaded in
  364. parallel`)
  365. portableCmd.Flags().BoolVar(&portableAzUseEmulator, "az-use-emulator", false, "")
  366. portableCmd.Flags().StringVar(&portableCryptPassphrase, "crypto-passphrase", "", `Passphrase for encryption/decryption`)
  367. portableCmd.Flags().StringVar(&portableSFTPEndpoint, "sftp-endpoint", "", `SFTP endpoint as host:port for SFTP
  368. provider`)
  369. portableCmd.Flags().StringVar(&portableSFTPUsername, "sftp-username", "", `SFTP user for SFTP provider`)
  370. portableCmd.Flags().StringVar(&portableSFTPPassword, "sftp-password", "", `SFTP password for SFTP provider`)
  371. portableCmd.Flags().StringVar(&portableSFTPPrivateKeyPath, "sftp-key-path", "", `SFTP private key path for SFTP provider`)
  372. portableCmd.Flags().StringSliceVar(&portableSFTPFingerprints, "sftp-fingerprints", []string{}, `SFTP fingerprints to verify remote host
  373. key for SFTP provider`)
  374. portableCmd.Flags().StringVar(&portableSFTPPrefix, "sftp-prefix", "", `SFTP prefix allows restrict all
  375. operations to a given path within the
  376. remote SFTP server`)
  377. portableCmd.Flags().BoolVar(&portableSFTPDisableConcurrentReads, "sftp-disable-concurrent-reads", false, `Concurrent reads are safe to use and
  378. disabling them will degrade performance.
  379. Disable for read once servers`)
  380. portableCmd.Flags().Int64Var(&portableSFTPDBufferSize, "sftp-buffer-size", 0, `The size of the buffer (in MB) to use
  381. for transfers. By enabling buffering,
  382. the reads and writes, from/to the
  383. remote SFTP server, are split in
  384. multiple concurrent requests and this
  385. allows data to be transferred at a
  386. faster rate, over high latency networks,
  387. by overlapping round-trip times`)
  388. portableCmd.Flags().IntVar(&graceTime, graceTimeFlag, 0,
  389. `This grace time defines the number of
  390. seconds allowed for existing transfers
  391. to get completed before shutting down.
  392. A graceful shutdown is triggered by an
  393. interrupt signal.
  394. `)
  395. rootCmd.AddCommand(portableCmd)
  396. }
  397. func parsePatternsFilesFilters() []sdk.PatternsFilter {
  398. var patterns []sdk.PatternsFilter
  399. for _, val := range portableAllowedPatterns {
  400. p, exts := getPatternsFilterValues(strings.TrimSpace(val))
  401. if p != "" {
  402. patterns = append(patterns, sdk.PatternsFilter{
  403. Path: path.Clean(p),
  404. AllowedPatterns: exts,
  405. DeniedPatterns: []string{},
  406. })
  407. }
  408. }
  409. for _, val := range portableDeniedPatterns {
  410. p, exts := getPatternsFilterValues(strings.TrimSpace(val))
  411. if p != "" {
  412. found := false
  413. for index, e := range patterns {
  414. if path.Clean(e.Path) == path.Clean(p) {
  415. patterns[index].DeniedPatterns = append(patterns[index].DeniedPatterns, exts...)
  416. found = true
  417. break
  418. }
  419. }
  420. if !found {
  421. patterns = append(patterns, sdk.PatternsFilter{
  422. Path: path.Clean(p),
  423. AllowedPatterns: []string{},
  424. DeniedPatterns: exts,
  425. })
  426. }
  427. }
  428. }
  429. return patterns
  430. }
  431. func getPatternsFilterValues(value string) (string, []string) {
  432. if strings.Contains(value, "::") {
  433. dirExts := strings.Split(value, "::")
  434. if len(dirExts) > 1 {
  435. dir := strings.TrimSpace(dirExts[0])
  436. exts := []string{}
  437. for _, e := range strings.Split(dirExts[1], ",") {
  438. cleanedExt := strings.TrimSpace(e)
  439. if cleanedExt != "" {
  440. exts = append(exts, cleanedExt)
  441. }
  442. }
  443. if dir != "" && len(exts) > 0 {
  444. return dir, exts
  445. }
  446. }
  447. }
  448. return "", nil
  449. }
  450. func getFileContents(name string) (string, error) {
  451. fi, err := os.Stat(name)
  452. if err != nil {
  453. return "", err
  454. }
  455. if fi.Size() > 1048576 {
  456. return "", fmt.Errorf("%#v is too big %v/1048576 bytes", name, fi.Size())
  457. }
  458. contents, err := os.ReadFile(name)
  459. if err != nil {
  460. return "", err
  461. }
  462. return string(contents), nil
  463. }