utils.go 9.0 KB

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