utils.go 15 KB

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