util.go 16 KB

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