utils.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. if len(encrypted) < nonceSize {
  179. return result, errors.New("malformed ciphertext")
  180. }
  181. nonce, ciphertext := encrypted[:nonceSize], encrypted[nonceSize:]
  182. plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
  183. if err != nil {
  184. return result, err
  185. }
  186. return string(plaintext), nil
  187. }
  188. // GenerateRSAKeys generate rsa private and public keys and write the
  189. // private key to specified file and the public key to the specified
  190. // file adding the .pub suffix
  191. func GenerateRSAKeys(file string) error {
  192. if err := createDirPathIfMissing(file, 0700); err != nil {
  193. return err
  194. }
  195. key, err := rsa.GenerateKey(rand.Reader, 4096)
  196. if err != nil {
  197. return err
  198. }
  199. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  200. if err != nil {
  201. return err
  202. }
  203. defer o.Close()
  204. priv := &pem.Block{
  205. Type: "RSA PRIVATE KEY",
  206. Bytes: x509.MarshalPKCS1PrivateKey(key),
  207. }
  208. if err := pem.Encode(o, priv); err != nil {
  209. return err
  210. }
  211. pub, err := ssh.NewPublicKey(&key.PublicKey)
  212. if err != nil {
  213. return err
  214. }
  215. return ioutil.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  216. }
  217. // GenerateECDSAKeys generate ecdsa private and public keys and write the
  218. // private key to specified file and the public key to the specified
  219. // file adding the .pub suffix
  220. func GenerateECDSAKeys(file string) error {
  221. if err := createDirPathIfMissing(file, 0700); err != nil {
  222. return err
  223. }
  224. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  225. if err != nil {
  226. return err
  227. }
  228. keyBytes, err := x509.MarshalECPrivateKey(key)
  229. if err != nil {
  230. return err
  231. }
  232. priv := &pem.Block{
  233. Type: "EC PRIVATE KEY",
  234. Bytes: keyBytes,
  235. }
  236. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  237. if err != nil {
  238. return err
  239. }
  240. defer o.Close()
  241. if err := pem.Encode(o, priv); err != nil {
  242. return err
  243. }
  244. pub, err := ssh.NewPublicKey(&key.PublicKey)
  245. if err != nil {
  246. return err
  247. }
  248. return ioutil.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  249. }
  250. // GenerateEd25519Keys generate ed25519 private and public keys and write the
  251. // private key to specified file and the public key to the specified
  252. // file adding the .pub suffix
  253. func GenerateEd25519Keys(file string) error {
  254. pubKey, privKey, err := ed25519.GenerateKey(rand.Reader)
  255. if err != nil {
  256. return err
  257. }
  258. keyBytes, err := x509.MarshalPKCS8PrivateKey(privKey)
  259. if err != nil {
  260. return err
  261. }
  262. priv := &pem.Block{
  263. Type: "PRIVATE KEY",
  264. Bytes: keyBytes,
  265. }
  266. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  267. if err != nil {
  268. return err
  269. }
  270. defer o.Close()
  271. if err := pem.Encode(o, priv); err != nil {
  272. return err
  273. }
  274. pub, err := ssh.NewPublicKey(pubKey)
  275. if err != nil {
  276. return err
  277. }
  278. return ioutil.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  279. }
  280. // GetDirsForSFTPPath returns all the directory for the given path in reverse order
  281. // for example if the path is: /1/2/3/4 it returns:
  282. // [ "/1/2/3/4", "/1/2/3", "/1/2", "/1", "/" ]
  283. func GetDirsForSFTPPath(p string) []string {
  284. sftpPath := CleanPath(p)
  285. dirsForPath := []string{sftpPath}
  286. for {
  287. if sftpPath == "/" {
  288. break
  289. }
  290. sftpPath = path.Dir(sftpPath)
  291. dirsForPath = append(dirsForPath, sftpPath)
  292. }
  293. return dirsForPath
  294. }
  295. // CleanPath returns a clean POSIX (/) absolute path to work with
  296. func CleanPath(p string) string {
  297. p = filepath.ToSlash(p)
  298. if !path.IsAbs(p) {
  299. p = "/" + p
  300. }
  301. return path.Clean(p)
  302. }
  303. // LoadTemplate wraps a call to a function returning (*Template, error)
  304. // it is just like template.Must but it writes a log before exiting
  305. func LoadTemplate(t *template.Template, err error) *template.Template {
  306. if err != nil {
  307. logger.ErrorToConsole("error loading required template: %v", err)
  308. logger.Error(logSender, "", "error loading required template: %v", err)
  309. panic(err)
  310. }
  311. return t
  312. }
  313. // IsFileInputValid returns true this is a valid file name.
  314. // This method must be used before joining a file name, generally provided as
  315. // user input, with a directory
  316. func IsFileInputValid(fileInput string) bool {
  317. cleanInput := filepath.Clean(fileInput)
  318. if cleanInput == "." || cleanInput == ".." {
  319. return false
  320. }
  321. return true
  322. }
  323. // CleanDirInput sanitizes user input for directories.
  324. // On Windows it removes any trailing `"`.
  325. // We try to help windows users that set an invalid path such as "C:\ProgramData\SFTPGO\".
  326. // This will only help if the invalid path is the last argument, for example in this command:
  327. // sftpgo.exe serve -c "C:\ProgramData\SFTPGO\" -l "sftpgo.log"
  328. // the -l flag will be ignored and the -c flag will get the value `C:\ProgramData\SFTPGO" -l sftpgo.log`
  329. // since the backslash after SFTPGO escape the double quote. This is definitely a bad user input
  330. func CleanDirInput(dirInput string) string {
  331. if runtime.GOOS == "windows" {
  332. for strings.HasSuffix(dirInput, "\"") {
  333. dirInput = strings.TrimSuffix(dirInput, "\"")
  334. }
  335. }
  336. return filepath.Clean(dirInput)
  337. }
  338. func createDirPathIfMissing(file string, perm os.FileMode) error {
  339. dirPath := filepath.Dir(file)
  340. if _, err := os.Stat(dirPath); os.IsNotExist(err) {
  341. err = os.MkdirAll(dirPath, perm)
  342. if err != nil {
  343. return err
  344. }
  345. }
  346. return nil
  347. }