util.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. // Package util provides some common utility methods
  2. package util
  3. import (
  4. "bytes"
  5. "crypto/ecdsa"
  6. "crypto/ed25519"
  7. "crypto/elliptic"
  8. "crypto/rand"
  9. "crypto/rsa"
  10. "crypto/tls"
  11. "crypto/x509"
  12. "encoding/pem"
  13. "errors"
  14. "fmt"
  15. "html/template"
  16. "io"
  17. "io/fs"
  18. "net"
  19. "net/http"
  20. "net/url"
  21. "os"
  22. "path"
  23. "path/filepath"
  24. "runtime"
  25. "strings"
  26. "time"
  27. "github.com/google/uuid"
  28. "github.com/lithammer/shortuuid/v3"
  29. "github.com/rs/xid"
  30. "golang.org/x/crypto/ssh"
  31. "github.com/drakkan/sftpgo/v2/logger"
  32. )
  33. const (
  34. logSender = "util"
  35. osWindows = "windows"
  36. )
  37. var (
  38. xForwardedFor = http.CanonicalHeaderKey("X-Forwarded-For")
  39. xRealIP = http.CanonicalHeaderKey("X-Real-IP")
  40. cfConnectingIP = http.CanonicalHeaderKey("CF-Connecting-IP")
  41. trueClientIP = http.CanonicalHeaderKey("True-Client-IP")
  42. )
  43. // Contains reports whether v is present in elems.
  44. func Contains[T comparable](elems []T, v T) bool {
  45. for _, s := range elems {
  46. if v == s {
  47. return true
  48. }
  49. }
  50. return false
  51. }
  52. // IsStringPrefixInSlice searches a string prefix in a slice and returns true
  53. // if a matching prefix is found
  54. func IsStringPrefixInSlice(obj string, list []string) bool {
  55. for i := 0; i < len(list); i++ {
  56. if strings.HasPrefix(obj, list[i]) {
  57. return true
  58. }
  59. }
  60. return false
  61. }
  62. // RemoveDuplicates returns a new slice removing any duplicate element from the initial one
  63. func RemoveDuplicates(obj []string) []string {
  64. if len(obj) == 0 {
  65. return obj
  66. }
  67. seen := make(map[string]bool)
  68. validIdx := 0
  69. for _, item := range obj {
  70. if !seen[item] {
  71. seen[item] = true
  72. obj[validIdx] = item
  73. validIdx++
  74. }
  75. }
  76. return obj[:validIdx]
  77. }
  78. // GetTimeAsMsSinceEpoch returns unix timestamp as milliseconds from a time struct
  79. func GetTimeAsMsSinceEpoch(t time.Time) int64 {
  80. return t.UnixMilli()
  81. }
  82. // GetTimeFromMsecSinceEpoch return a time struct from a unix timestamp with millisecond precision
  83. func GetTimeFromMsecSinceEpoch(msec int64) time.Time {
  84. return time.Unix(0, msec*1000000)
  85. }
  86. // GetDurationAsString returns a string representation for a time.Duration
  87. func GetDurationAsString(d time.Duration) string {
  88. d = d.Round(time.Second)
  89. h := d / time.Hour
  90. d -= h * time.Hour
  91. m := d / time.Minute
  92. d -= m * time.Minute
  93. s := d / time.Second
  94. if h > 0 {
  95. return fmt.Sprintf("%02d:%02d:%02d", h, m, s)
  96. }
  97. return fmt.Sprintf("%02d:%02d", m, s)
  98. }
  99. // ByteCountSI returns humanized size in SI (decimal) format
  100. func ByteCountSI(b int64) string {
  101. return byteCount(b, 1000)
  102. }
  103. // ByteCountIEC returns humanized size in IEC (binary) format
  104. func ByteCountIEC(b int64) string {
  105. return byteCount(b, 1024)
  106. }
  107. func byteCount(b int64, unit int64) string {
  108. if b < unit {
  109. return fmt.Sprintf("%d B", b)
  110. }
  111. div, exp := unit, 0
  112. for n := b / unit; n >= unit; n /= unit {
  113. div *= unit
  114. exp++
  115. }
  116. if unit == 1000 {
  117. return fmt.Sprintf("%.1f %cB",
  118. float64(b)/float64(div), "KMGTPE"[exp])
  119. }
  120. return fmt.Sprintf("%.1f %ciB",
  121. float64(b)/float64(div), "KMGTPE"[exp])
  122. }
  123. // GetIPFromRemoteAddress returns the IP from the remote address.
  124. // If the given remote address cannot be parsed it will be returned unchanged
  125. func GetIPFromRemoteAddress(remoteAddress string) string {
  126. ip, _, err := net.SplitHostPort(remoteAddress)
  127. if err == nil {
  128. return ip
  129. }
  130. return remoteAddress
  131. }
  132. // NilIfEmpty returns nil if the input string is empty
  133. func NilIfEmpty(s string) *string {
  134. if s == "" {
  135. return nil
  136. }
  137. return &s
  138. }
  139. // GetStringFromPointer returns the string value or empty if nil
  140. func GetStringFromPointer(val *string) string {
  141. if val == nil {
  142. return ""
  143. }
  144. return *val
  145. }
  146. // GetIntFromPointer returns the int value or zero
  147. func GetIntFromPointer(val *int64) int64 {
  148. if val == nil {
  149. return 0
  150. }
  151. return *val
  152. }
  153. // GetTimeFromPointer returns the time value or now
  154. func GetTimeFromPointer(val *time.Time) time.Time {
  155. if val == nil {
  156. return time.Now()
  157. }
  158. return *val
  159. }
  160. // GenerateRSAKeys generate rsa private and public keys and write the
  161. // private key to specified file and the public key to the specified
  162. // file adding the .pub suffix
  163. func GenerateRSAKeys(file string) error {
  164. if err := createDirPathIfMissing(file, 0700); err != nil {
  165. return err
  166. }
  167. key, err := rsa.GenerateKey(rand.Reader, 4096)
  168. if err != nil {
  169. return err
  170. }
  171. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  172. if err != nil {
  173. return err
  174. }
  175. defer o.Close()
  176. priv := &pem.Block{
  177. Type: "RSA PRIVATE KEY",
  178. Bytes: x509.MarshalPKCS1PrivateKey(key),
  179. }
  180. if err := pem.Encode(o, priv); err != nil {
  181. return err
  182. }
  183. pub, err := ssh.NewPublicKey(&key.PublicKey)
  184. if err != nil {
  185. return err
  186. }
  187. return os.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  188. }
  189. // GenerateECDSAKeys generate ecdsa private and public keys and write the
  190. // private key to specified file and the public key to the specified
  191. // file adding the .pub suffix
  192. func GenerateECDSAKeys(file string) error {
  193. if err := createDirPathIfMissing(file, 0700); err != nil {
  194. return err
  195. }
  196. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  197. if err != nil {
  198. return err
  199. }
  200. keyBytes, err := x509.MarshalECPrivateKey(key)
  201. if err != nil {
  202. return err
  203. }
  204. priv := &pem.Block{
  205. Type: "EC PRIVATE KEY",
  206. Bytes: keyBytes,
  207. }
  208. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  209. if err != nil {
  210. return err
  211. }
  212. defer o.Close()
  213. if err := pem.Encode(o, priv); err != nil {
  214. return err
  215. }
  216. pub, err := ssh.NewPublicKey(&key.PublicKey)
  217. if err != nil {
  218. return err
  219. }
  220. return os.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  221. }
  222. // GenerateEd25519Keys generate ed25519 private and public keys and write the
  223. // private key to specified file and the public key to the specified
  224. // file adding the .pub suffix
  225. func GenerateEd25519Keys(file string) error {
  226. pubKey, privKey, err := ed25519.GenerateKey(rand.Reader)
  227. if err != nil {
  228. return err
  229. }
  230. keyBytes, err := x509.MarshalPKCS8PrivateKey(privKey)
  231. if err != nil {
  232. return err
  233. }
  234. priv := &pem.Block{
  235. Type: "PRIVATE KEY",
  236. Bytes: keyBytes,
  237. }
  238. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  239. if err != nil {
  240. return err
  241. }
  242. defer o.Close()
  243. if err := pem.Encode(o, priv); err != nil {
  244. return err
  245. }
  246. pub, err := ssh.NewPublicKey(pubKey)
  247. if err != nil {
  248. return err
  249. }
  250. return os.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  251. }
  252. // GetDirsForVirtualPath returns all the directory for the given path in reverse order
  253. // for example if the path is: /1/2/3/4 it returns:
  254. // [ "/1/2/3/4", "/1/2/3", "/1/2", "/1", "/" ]
  255. func GetDirsForVirtualPath(virtualPath string) []string {
  256. if virtualPath == "" || virtualPath == "." {
  257. virtualPath = "/"
  258. } else {
  259. if !path.IsAbs(virtualPath) {
  260. virtualPath = CleanPath(virtualPath)
  261. }
  262. }
  263. dirsForPath := []string{virtualPath}
  264. for {
  265. if virtualPath == "/" {
  266. break
  267. }
  268. virtualPath = path.Dir(virtualPath)
  269. dirsForPath = append(dirsForPath, virtualPath)
  270. }
  271. return dirsForPath
  272. }
  273. // CleanPath returns a clean POSIX (/) absolute path to work with
  274. func CleanPath(p string) string {
  275. p = filepath.ToSlash(p)
  276. if !path.IsAbs(p) {
  277. p = "/" + p
  278. }
  279. return path.Clean(p)
  280. }
  281. // LoadTemplate parses the given template paths.
  282. // It behaves like template.Must but it writes a log before exiting.
  283. // You can optionally provide a base template (e.g. to define some custom functions)
  284. func LoadTemplate(base *template.Template, paths ...string) *template.Template {
  285. var t *template.Template
  286. var err error
  287. if base != nil {
  288. base, err = base.Clone()
  289. if err == nil {
  290. t, err = base.ParseFiles(paths...)
  291. }
  292. } else {
  293. t, err = template.ParseFiles(paths...)
  294. }
  295. if err != nil {
  296. logger.ErrorToConsole("error loading required template: %v", err)
  297. logger.Error(logSender, "", "error loading required template: %v", err)
  298. panic(err)
  299. }
  300. return t
  301. }
  302. // IsFileInputValid returns true this is a valid file name.
  303. // This method must be used before joining a file name, generally provided as
  304. // user input, with a directory
  305. func IsFileInputValid(fileInput string) bool {
  306. cleanInput := filepath.Clean(fileInput)
  307. if cleanInput == "." || cleanInput == ".." {
  308. return false
  309. }
  310. return true
  311. }
  312. // FindSharedDataPath searches for the specified directory name in searchDir
  313. // and in system-wide shared data directories.
  314. // If name is an absolute path it is returned unmodified.
  315. func FindSharedDataPath(name, searchDir string) string {
  316. if !IsFileInputValid(name) {
  317. return ""
  318. }
  319. if name != "" && !filepath.IsAbs(name) {
  320. searchList := []string{searchDir}
  321. if runtime.GOOS != osWindows {
  322. searchList = append(searchList, "/usr/share/sftpgo")
  323. searchList = append(searchList, "/usr/local/share/sftpgo")
  324. }
  325. for _, basePath := range searchList {
  326. res := filepath.Join(basePath, name)
  327. _, err := os.Stat(res)
  328. if err == nil {
  329. logger.Debug(logSender, "", "found share data path for name %#v: %#v", name, res)
  330. return res
  331. }
  332. }
  333. return filepath.Join(searchDir, name)
  334. }
  335. return name
  336. }
  337. // CleanDirInput sanitizes user input for directories.
  338. // On Windows it removes any trailing `"`.
  339. // We try to help windows users that set an invalid path such as "C:\ProgramData\SFTPGO\".
  340. // This will only help if the invalid path is the last argument, for example in this command:
  341. // sftpgo.exe serve -c "C:\ProgramData\SFTPGO\" -l "sftpgo.log"
  342. // the -l flag will be ignored and the -c flag will get the value `C:\ProgramData\SFTPGO" -l sftpgo.log`
  343. // since the backslash after SFTPGO escape the double quote. This is definitely a bad user input
  344. func CleanDirInput(dirInput string) string {
  345. if runtime.GOOS == osWindows {
  346. for strings.HasSuffix(dirInput, "\"") {
  347. dirInput = strings.TrimSuffix(dirInput, "\"")
  348. }
  349. }
  350. return filepath.Clean(dirInput)
  351. }
  352. func createDirPathIfMissing(file string, perm os.FileMode) error {
  353. dirPath := filepath.Dir(file)
  354. if _, err := os.Stat(dirPath); errors.Is(err, fs.ErrNotExist) {
  355. err = os.MkdirAll(dirPath, perm)
  356. if err != nil {
  357. return err
  358. }
  359. }
  360. return nil
  361. }
  362. // GenerateRandomBytes generates the secret to use for JWT auth
  363. func GenerateRandomBytes(length int) []byte {
  364. b := make([]byte, length)
  365. _, err := io.ReadFull(rand.Reader, b)
  366. if err == nil {
  367. return b
  368. }
  369. b = xid.New().Bytes()
  370. for len(b) < length {
  371. b = append(b, xid.New().Bytes()...)
  372. }
  373. return b[:length]
  374. }
  375. // GenerateUniqueID retuens an unique ID
  376. func GenerateUniqueID() string {
  377. u, err := uuid.NewRandom()
  378. if err != nil {
  379. return xid.New().String()
  380. }
  381. return shortuuid.DefaultEncoder.Encode(u)
  382. }
  383. // HTTPListenAndServe is a wrapper for ListenAndServe that support both tcp
  384. // and Unix-domain sockets
  385. func HTTPListenAndServe(srv *http.Server, address string, port int, isTLS bool, logSender string) error {
  386. var listener net.Listener
  387. var err error
  388. if filepath.IsAbs(address) && runtime.GOOS != osWindows {
  389. if !IsFileInputValid(address) {
  390. return fmt.Errorf("invalid socket address %#v", address)
  391. }
  392. err = createDirPathIfMissing(address, os.ModePerm)
  393. if err != nil {
  394. logger.ErrorToConsole("error creating Unix-domain socket parent dir: %v", err)
  395. logger.Error(logSender, "", "error creating Unix-domain socket parent dir: %v", err)
  396. }
  397. os.Remove(address)
  398. listener, err = newListener("unix", address, srv.ReadTimeout, srv.WriteTimeout)
  399. } else {
  400. CheckTCP4Port(port)
  401. listener, err = newListener("tcp", fmt.Sprintf("%s:%d", address, port), srv.ReadTimeout, srv.WriteTimeout)
  402. }
  403. if err != nil {
  404. return err
  405. }
  406. logger.Info(logSender, "", "server listener registered, address: %v TLS enabled: %v", listener.Addr().String(), isTLS)
  407. defer listener.Close()
  408. if isTLS {
  409. return srv.ServeTLS(listener, "", "")
  410. }
  411. return srv.Serve(listener)
  412. }
  413. // GetTLSCiphersFromNames returns the TLS ciphers from the specified names
  414. func GetTLSCiphersFromNames(cipherNames []string) []uint16 {
  415. var ciphers []uint16
  416. for _, name := range RemoveDuplicates(cipherNames) {
  417. for _, c := range tls.CipherSuites() {
  418. if c.Name == strings.TrimSpace(name) {
  419. ciphers = append(ciphers, c.ID)
  420. }
  421. }
  422. }
  423. return ciphers
  424. }
  425. // EncodeTLSCertToPem returns the specified certificate PEM encoded.
  426. // This can be verified using openssl x509 -in cert.crt -text -noout
  427. func EncodeTLSCertToPem(tlsCert *x509.Certificate) (string, error) {
  428. if len(tlsCert.Raw) == 0 {
  429. return "", errors.New("invalid x509 certificate, no der contents")
  430. }
  431. publicKeyBlock := pem.Block{
  432. Type: "CERTIFICATE",
  433. Bytes: tlsCert.Raw,
  434. }
  435. return string(pem.EncodeToMemory(&publicKeyBlock)), nil
  436. }
  437. // CheckTCP4Port quits the app if bind on the given IPv4 port fails.
  438. // This is a ugly hack to avoid to bind on an already used port.
  439. // It is required on Windows only. Upstream does not consider this
  440. // behaviour a bug:
  441. // https://github.com/golang/go/issues/45150
  442. func CheckTCP4Port(port int) {
  443. if runtime.GOOS != osWindows {
  444. return
  445. }
  446. listener, err := net.Listen("tcp4", fmt.Sprintf(":%d", port))
  447. if err != nil {
  448. logger.ErrorToConsole("unable to bind on tcp4 address: %v", err)
  449. logger.Error(logSender, "", "unable to bind on tcp4 address: %v", err)
  450. os.Exit(1)
  451. }
  452. listener.Close()
  453. }
  454. // IsByteArrayEmpty return true if the byte array is empty or a new line
  455. func IsByteArrayEmpty(b []byte) bool {
  456. if len(b) == 0 {
  457. return true
  458. }
  459. if bytes.Equal(b, []byte("\n")) {
  460. return true
  461. }
  462. if bytes.Equal(b, []byte("\r\n")) {
  463. return true
  464. }
  465. return false
  466. }
  467. // GetSSHPublicKeyAsString returns an SSH public key serialized as string
  468. func GetSSHPublicKeyAsString(pubKey []byte) (string, error) {
  469. if len(pubKey) == 0 {
  470. return "", nil
  471. }
  472. k, err := ssh.ParsePublicKey(pubKey)
  473. if err != nil {
  474. return "", err
  475. }
  476. return string(ssh.MarshalAuthorizedKey(k)), nil
  477. }
  478. // GetRealIP returns the ip address as result of parsing either the
  479. // X-Real-IP header or the X-Forwarded-For header
  480. func GetRealIP(r *http.Request) string {
  481. var ip string
  482. if clientIP := r.Header.Get(trueClientIP); clientIP != "" {
  483. ip = clientIP
  484. } else if xrip := r.Header.Get(xRealIP); xrip != "" {
  485. ip = xrip
  486. } else if clientIP := r.Header.Get(cfConnectingIP); clientIP != "" {
  487. ip = clientIP
  488. } else if xff := r.Header.Get(xForwardedFor); xff != "" {
  489. i := strings.Index(xff, ",")
  490. if i == -1 {
  491. i = len(xff)
  492. }
  493. ip = strings.TrimSpace(xff[:i])
  494. }
  495. if ip == "" || net.ParseIP(ip) == nil {
  496. return ""
  497. }
  498. return ip
  499. }
  500. // GetHTTPLocalAddress returns the local address for an http.Request
  501. // or empty if it cannot be determined
  502. func GetHTTPLocalAddress(r *http.Request) string {
  503. if r == nil {
  504. return ""
  505. }
  506. localAddr, ok := r.Context().Value(http.LocalAddrContextKey).(net.Addr)
  507. if ok {
  508. return localAddr.String()
  509. }
  510. return ""
  511. }
  512. // ParseAllowedIPAndRanges returns a list of functions that allow to find if an
  513. // IP is equal or is contained within the allowed list
  514. func ParseAllowedIPAndRanges(allowed []string) ([]func(net.IP) bool, error) {
  515. res := make([]func(net.IP) bool, len(allowed))
  516. for i, allowFrom := range allowed {
  517. if strings.LastIndex(allowFrom, "/") > 0 {
  518. _, ipRange, err := net.ParseCIDR(allowFrom)
  519. if err != nil {
  520. return nil, fmt.Errorf("given string %q is not a valid IP range: %v", allowFrom, err)
  521. }
  522. res[i] = ipRange.Contains
  523. } else {
  524. allowed := net.ParseIP(allowFrom)
  525. if allowed == nil {
  526. return nil, fmt.Errorf("given string %q is not a valid IP address", allowFrom)
  527. }
  528. res[i] = allowed.Equal
  529. }
  530. }
  531. return res, nil
  532. }
  533. // GetRedactedURL returns the url redacting the password if any
  534. func GetRedactedURL(rawurl string) string {
  535. if !strings.HasPrefix(rawurl, "http") {
  536. return rawurl
  537. }
  538. u, err := url.Parse(rawurl)
  539. if err != nil {
  540. return rawurl
  541. }
  542. return u.Redacted()
  543. }
  544. // PrependFileInfo prepends a file info to a slice in an efficient way.
  545. // We, optimistically, assume that the slice has enough capacity
  546. func PrependFileInfo(files []os.FileInfo, info os.FileInfo) []os.FileInfo {
  547. files = append(files, nil)
  548. copy(files[1:], files)
  549. files[0] = info
  550. return files
  551. }
  552. // GetTLSVersion returns the TLS version for integer:
  553. // - 12 means TLS 1.2
  554. // - 13 means TLS 1.3
  555. // default is TLS 1.2
  556. func GetTLSVersion(val int) uint16 {
  557. switch val {
  558. case 13:
  559. return tls.VersionTLS13
  560. default:
  561. return tls.VersionTLS12
  562. }
  563. }