1
0

utils.go 14 KB

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