utils.go 13 KB

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