utils.go 12 KB

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