utils.go 12 KB

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