utils.go 15 KB

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