utils.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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/x509"
  12. "encoding/hex"
  13. "encoding/pem"
  14. "errors"
  15. "fmt"
  16. "html/template"
  17. "io"
  18. "io/ioutil"
  19. "net"
  20. "os"
  21. "path"
  22. "path/filepath"
  23. "runtime"
  24. "strings"
  25. "time"
  26. "golang.org/x/crypto/ssh"
  27. "github.com/drakkan/sftpgo/logger"
  28. )
  29. const logSender = "utils"
  30. // IsStringInSlice searches a string in a slice and returns true if the string is found
  31. func IsStringInSlice(obj string, list []string) bool {
  32. for _, v := range list {
  33. if v == obj {
  34. return true
  35. }
  36. }
  37. return false
  38. }
  39. // IsStringPrefixInSlice searches a string prefix in a slice and returns true
  40. // if a matching prefix is found
  41. func IsStringPrefixInSlice(obj string, list []string) bool {
  42. for _, v := range list {
  43. if strings.HasPrefix(obj, v) {
  44. return true
  45. }
  46. }
  47. return false
  48. }
  49. // RemoveDuplicates returns a new slice removing any duplicate element from the initial one
  50. func RemoveDuplicates(obj []string) []string {
  51. if len(obj) == 0 {
  52. return obj
  53. }
  54. result := make([]string, 0, len(obj))
  55. seen := make(map[string]bool)
  56. for _, item := range obj {
  57. if _, ok := seen[item]; !ok {
  58. result = append(result, item)
  59. }
  60. seen[item] = true
  61. }
  62. return result
  63. }
  64. // GetTimeAsMsSinceEpoch returns unix timestamp as milliseconds from a time struct
  65. func GetTimeAsMsSinceEpoch(t time.Time) int64 {
  66. return t.UnixNano() / 1000000
  67. }
  68. // GetTimeFromMsecSinceEpoch return a time struct from a unix timestamp with millisecond precision
  69. func GetTimeFromMsecSinceEpoch(msec int64) time.Time {
  70. return time.Unix(0, msec*1000000)
  71. }
  72. // GetDurationAsString returns a string representation for a time.Duration
  73. func GetDurationAsString(d time.Duration) string {
  74. d = d.Round(time.Second)
  75. h := d / time.Hour
  76. d -= h * time.Hour
  77. m := d / time.Minute
  78. d -= m * time.Minute
  79. s := d / time.Second
  80. if h > 0 {
  81. return fmt.Sprintf("%02d:%02d:%02d", h, m, s)
  82. }
  83. return fmt.Sprintf("%02d:%02d", m, s)
  84. }
  85. // ByteCountSI returns humanized size in SI (decimal) format
  86. func ByteCountSI(b int64) string {
  87. return byteCount(b, 1000)
  88. }
  89. // ByteCountIEC returns humanized size in IEC (binary) format
  90. func ByteCountIEC(b int64) string {
  91. return byteCount(b, 1024)
  92. }
  93. func byteCount(b int64, unit int64) string {
  94. if b < unit {
  95. return fmt.Sprintf("%d B", b)
  96. }
  97. div, exp := unit, 0
  98. for n := b / unit; n >= unit; n /= unit {
  99. div *= unit
  100. exp++
  101. }
  102. if unit == 1000 {
  103. return fmt.Sprintf("%.1f %cB",
  104. float64(b)/float64(div), "KMGTPE"[exp])
  105. }
  106. return fmt.Sprintf("%.1f %ciB",
  107. float64(b)/float64(div), "KMGTPE"[exp])
  108. }
  109. // GetIPFromRemoteAddress returns the IP from the remote address.
  110. // If the given remote address cannot be parsed it will be returned unchanged
  111. func GetIPFromRemoteAddress(remoteAddress string) string {
  112. ip, _, err := net.SplitHostPort(remoteAddress)
  113. if err == nil {
  114. return ip
  115. }
  116. return remoteAddress
  117. }
  118. // NilIfEmpty returns nil if the input string is empty
  119. func NilIfEmpty(s string) *string {
  120. if len(s) == 0 {
  121. return nil
  122. }
  123. return &s
  124. }
  125. // EncryptData encrypts data using the given key
  126. func EncryptData(data string) (string, error) {
  127. var result string
  128. key := make([]byte, 16)
  129. if _, err := io.ReadFull(rand.Reader, key); err != nil {
  130. return result, err
  131. }
  132. keyHex := hex.EncodeToString(key)
  133. block, err := aes.NewCipher([]byte(keyHex))
  134. if err != nil {
  135. return result, err
  136. }
  137. gcm, err := cipher.NewGCM(block)
  138. if err != nil {
  139. return result, err
  140. }
  141. nonce := make([]byte, gcm.NonceSize())
  142. if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
  143. return result, err
  144. }
  145. ciphertext := gcm.Seal(nonce, nonce, []byte(data), nil)
  146. result = fmt.Sprintf("$aes$%s$%x", keyHex, ciphertext)
  147. return result, err
  148. }
  149. // RemoveDecryptionKey returns encrypted data without the decryption key
  150. func RemoveDecryptionKey(encryptData string) string {
  151. vals := strings.Split(encryptData, "$")
  152. if len(vals) == 4 {
  153. return fmt.Sprintf("$%v$%v", vals[1], vals[3])
  154. }
  155. return encryptData
  156. }
  157. // DecryptData decrypts data encrypted using EncryptData
  158. func DecryptData(data string) (string, error) {
  159. var result string
  160. vals := strings.Split(data, "$")
  161. if len(vals) != 4 {
  162. return "", errors.New("data to decrypt is not in the correct format")
  163. }
  164. key := vals[2]
  165. encrypted, err := hex.DecodeString(vals[3])
  166. if err != nil {
  167. return result, err
  168. }
  169. block, err := aes.NewCipher([]byte(key))
  170. if err != nil {
  171. return result, err
  172. }
  173. gcm, err := cipher.NewGCM(block)
  174. if err != nil {
  175. return result, err
  176. }
  177. nonceSize := gcm.NonceSize()
  178. nonce, ciphertext := encrypted[:nonceSize], encrypted[nonceSize:]
  179. plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
  180. if err != nil {
  181. return result, err
  182. }
  183. return string(plaintext), nil
  184. }
  185. // GenerateRSAKeys generate rsa private and public keys and write the
  186. // private key to specified file and the public key to the specified
  187. // file adding the .pub suffix
  188. func GenerateRSAKeys(file string) error {
  189. if err := createDirPathIfMissing(file, 0700); err != nil {
  190. return err
  191. }
  192. key, err := rsa.GenerateKey(rand.Reader, 4096)
  193. if err != nil {
  194. return err
  195. }
  196. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  197. if err != nil {
  198. return err
  199. }
  200. defer o.Close()
  201. priv := &pem.Block{
  202. Type: "RSA PRIVATE KEY",
  203. Bytes: x509.MarshalPKCS1PrivateKey(key),
  204. }
  205. if err := pem.Encode(o, priv); err != nil {
  206. return err
  207. }
  208. pub, err := ssh.NewPublicKey(&key.PublicKey)
  209. if err != nil {
  210. return err
  211. }
  212. return ioutil.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  213. }
  214. // GenerateECDSAKeys generate ecdsa private and public keys and write the
  215. // private key to specified file and the public key to the specified
  216. // file adding the .pub suffix
  217. func GenerateECDSAKeys(file string) error {
  218. if err := createDirPathIfMissing(file, 0700); err != nil {
  219. return err
  220. }
  221. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  222. if err != nil {
  223. return err
  224. }
  225. keyBytes, err := x509.MarshalECPrivateKey(key)
  226. if err != nil {
  227. return err
  228. }
  229. priv := &pem.Block{
  230. Type: "EC PRIVATE KEY",
  231. Bytes: keyBytes,
  232. }
  233. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  234. if err != nil {
  235. return err
  236. }
  237. defer o.Close()
  238. if err := pem.Encode(o, priv); err != nil {
  239. return err
  240. }
  241. pub, err := ssh.NewPublicKey(&key.PublicKey)
  242. if err != nil {
  243. return err
  244. }
  245. return ioutil.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  246. }
  247. // GenerateEd25519Keys generate ed25519 private and public keys and write the
  248. // private key to specified file and the public key to the specified
  249. // file adding the .pub suffix
  250. func GenerateEd25519Keys(file string) error {
  251. pubKey, privKey, err := ed25519.GenerateKey(rand.Reader)
  252. if err != nil {
  253. return err
  254. }
  255. keyBytes, err := x509.MarshalPKCS8PrivateKey(privKey)
  256. if err != nil {
  257. return err
  258. }
  259. priv := &pem.Block{
  260. Type: "PRIVATE KEY",
  261. Bytes: keyBytes,
  262. }
  263. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  264. if err != nil {
  265. return err
  266. }
  267. defer o.Close()
  268. if err := pem.Encode(o, priv); err != nil {
  269. return err
  270. }
  271. pub, err := ssh.NewPublicKey(pubKey)
  272. if err != nil {
  273. return err
  274. }
  275. return ioutil.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  276. }
  277. // GetDirsForSFTPPath returns all the directory for the given path in reverse order
  278. // for example if the path is: /1/2/3/4 it returns:
  279. // [ "/1/2/3/4", "/1/2/3", "/1/2", "/1", "/" ]
  280. func GetDirsForSFTPPath(p string) []string {
  281. sftpPath := CleanPath(p)
  282. dirsForPath := []string{sftpPath}
  283. for {
  284. if sftpPath == "/" {
  285. break
  286. }
  287. sftpPath = path.Dir(sftpPath)
  288. dirsForPath = append(dirsForPath, sftpPath)
  289. }
  290. return dirsForPath
  291. }
  292. // CleanPath returns a clean POSIX (/) absolute path to work with
  293. func CleanPath(p string) string {
  294. p = filepath.ToSlash(p)
  295. if !path.IsAbs(p) {
  296. p = "/" + p
  297. }
  298. return path.Clean(p)
  299. }
  300. // LoadTemplate wraps a call to a function returning (*Template, error)
  301. // it is just like template.Must but it writes a log before exiting
  302. func LoadTemplate(t *template.Template, err error) *template.Template {
  303. if err != nil {
  304. logger.ErrorToConsole("error loading required template: %v", err)
  305. logger.Error(logSender, "", "error loading required template: %v", err)
  306. panic(err)
  307. }
  308. return t
  309. }
  310. // IsFileInputValid returns true this is a valid file name.
  311. // This method must be used before joining a file name, generally provided as
  312. // user input, with a directory
  313. func IsFileInputValid(fileInput string) bool {
  314. cleanInput := filepath.Clean(fileInput)
  315. if cleanInput == "." || cleanInput == ".." {
  316. return false
  317. }
  318. return true
  319. }
  320. // CleanDirInput sanitizes user input for directories.
  321. // On Windows it removes any trailing `"`.
  322. // We try to help windows users that set an invalid path such as "C:\ProgramData\SFTPGO\".
  323. // This will only help if the invalid path is the last argument, for example in this command:
  324. // sftpgo.exe serve -c "C:\ProgramData\SFTPGO\" -l "sftpgo.log"
  325. // the -l flag will be ignored and the -c flag will get the value `C:\ProgramData\SFTPGO" -l sftpgo.log`
  326. // since the backslash after SFTPGO escape the double quote. This is definitely a bad user input
  327. func CleanDirInput(dirInput string) string {
  328. if runtime.GOOS == "windows" {
  329. for strings.HasSuffix(dirInput, "\"") {
  330. dirInput = strings.TrimSuffix(dirInput, "\"")
  331. }
  332. }
  333. return filepath.Clean(dirInput)
  334. }
  335. func createDirPathIfMissing(file string, perm os.FileMode) error {
  336. dirPath := filepath.Dir(file)
  337. if _, err := os.Stat(dirPath); os.IsNotExist(err) {
  338. err = os.MkdirAll(dirPath, perm)
  339. if err != nil {
  340. return err
  341. }
  342. }
  343. return nil
  344. }