utils.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. // Package utils provides some common utility methods
  2. package utils
  3. import (
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "crypto/ecdsa"
  7. "crypto/elliptic"
  8. "crypto/rand"
  9. "crypto/rsa"
  10. "crypto/x509"
  11. "encoding/hex"
  12. "encoding/pem"
  13. "errors"
  14. "fmt"
  15. "html/template"
  16. "io"
  17. "io/ioutil"
  18. "net"
  19. "os"
  20. "path"
  21. "path/filepath"
  22. "strings"
  23. "time"
  24. "github.com/drakkan/sftpgo/logger"
  25. "golang.org/x/crypto/ssh"
  26. )
  27. const logSender = "utils"
  28. // IsStringInSlice searches a string in a slice and returns true if the string is found
  29. func IsStringInSlice(obj string, list []string) bool {
  30. for _, v := range list {
  31. if v == obj {
  32. return true
  33. }
  34. }
  35. return false
  36. }
  37. // IsStringPrefixInSlice searches a string prefix in a slice and returns true
  38. // if a matching prefix is found
  39. func IsStringPrefixInSlice(obj string, list []string) bool {
  40. for _, v := range list {
  41. if strings.HasPrefix(obj, v) {
  42. return true
  43. }
  44. }
  45. return false
  46. }
  47. // GetTimeAsMsSinceEpoch returns unix timestamp as milliseconds from a time struct
  48. func GetTimeAsMsSinceEpoch(t time.Time) int64 {
  49. return t.UnixNano() / 1000000
  50. }
  51. // GetTimeFromMsecSinceEpoch return a time struct from a unix timestamp with millisecond precision
  52. func GetTimeFromMsecSinceEpoch(msec int64) time.Time {
  53. return time.Unix(0, msec*1000000)
  54. }
  55. // GetAppVersion returns VersionInfo struct
  56. func GetAppVersion() VersionInfo {
  57. return versionInfo
  58. }
  59. // GetDurationAsString returns a string representation for a time.Duration
  60. func GetDurationAsString(d time.Duration) string {
  61. d = d.Round(time.Second)
  62. h := d / time.Hour
  63. d -= h * time.Hour
  64. m := d / time.Minute
  65. d -= m * time.Minute
  66. s := d / time.Second
  67. if h > 0 {
  68. return fmt.Sprintf("%02d:%02d:%02d", h, m, s)
  69. }
  70. return fmt.Sprintf("%02d:%02d", m, s)
  71. }
  72. // ByteCountSI returns humanized size in SI (decimal) format
  73. func ByteCountSI(b int64) string {
  74. return byteCount(b, 1000)
  75. }
  76. // ByteCountIEC returns humanized size in IEC (binary) format
  77. func ByteCountIEC(b int64) string {
  78. return byteCount(b, 1024)
  79. }
  80. func byteCount(b int64, unit int64) string {
  81. if b < unit {
  82. return fmt.Sprintf("%d B", b)
  83. }
  84. div, exp := unit, 0
  85. for n := b / unit; n >= unit; n /= unit {
  86. div *= unit
  87. exp++
  88. }
  89. if unit == 1000 {
  90. return fmt.Sprintf("%.1f %cB",
  91. float64(b)/float64(div), "KMGTPE"[exp])
  92. }
  93. return fmt.Sprintf("%.1f %ciB",
  94. float64(b)/float64(div), "KMGTPE"[exp])
  95. }
  96. // GetIPFromRemoteAddress returns the IP from the remote address.
  97. // If the given remote address cannot be parsed it will be returned unchanged
  98. func GetIPFromRemoteAddress(remoteAddress string) string {
  99. ip, _, err := net.SplitHostPort(remoteAddress)
  100. if err == nil {
  101. return ip
  102. }
  103. return remoteAddress
  104. }
  105. // NilIfEmpty returns nil if the input string is empty
  106. func NilIfEmpty(s string) *string {
  107. if len(s) == 0 {
  108. return nil
  109. }
  110. return &s
  111. }
  112. // EncryptData encrypts data using the given key
  113. func EncryptData(data string) (string, error) {
  114. var result string
  115. key := make([]byte, 16)
  116. if _, err := io.ReadFull(rand.Reader, key); err != nil {
  117. return result, err
  118. }
  119. keyHex := hex.EncodeToString(key)
  120. block, err := aes.NewCipher([]byte(keyHex))
  121. if err != nil {
  122. return result, err
  123. }
  124. gcm, err := cipher.NewGCM(block)
  125. if err != nil {
  126. return result, err
  127. }
  128. nonce := make([]byte, gcm.NonceSize())
  129. if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
  130. return result, err
  131. }
  132. ciphertext := gcm.Seal(nonce, nonce, []byte(data), nil)
  133. result = fmt.Sprintf("$aes$%s$%x", keyHex, ciphertext)
  134. return result, err
  135. }
  136. // RemoveDecryptionKey returns encrypted data without the decryption key
  137. func RemoveDecryptionKey(encryptData string) string {
  138. vals := strings.Split(encryptData, "$")
  139. if len(vals) == 4 {
  140. return fmt.Sprintf("$%v$%v", vals[1], vals[3])
  141. }
  142. return encryptData
  143. }
  144. // DecryptData decrypts data encrypted using EncryptData
  145. func DecryptData(data string) (string, error) {
  146. var result string
  147. vals := strings.Split(data, "$")
  148. if len(vals) != 4 {
  149. return "", errors.New("data to decrypt is not in the correct format")
  150. }
  151. key := vals[2]
  152. encrypted, err := hex.DecodeString(vals[3])
  153. if err != nil {
  154. return result, err
  155. }
  156. block, err := aes.NewCipher([]byte(key))
  157. if err != nil {
  158. return result, err
  159. }
  160. gcm, err := cipher.NewGCM(block)
  161. if err != nil {
  162. return result, err
  163. }
  164. nonceSize := gcm.NonceSize()
  165. nonce, ciphertext := encrypted[:nonceSize], encrypted[nonceSize:]
  166. plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
  167. if err != nil {
  168. return result, err
  169. }
  170. return string(plaintext), nil
  171. }
  172. // GenerateRSAKeys generate rsa private and public keys and write the
  173. // private key to specified file and the public key to the specified
  174. // file adding the .pub suffix
  175. func GenerateRSAKeys(file string) error {
  176. key, err := rsa.GenerateKey(rand.Reader, 4096)
  177. if err != nil {
  178. return err
  179. }
  180. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  181. if err != nil {
  182. return err
  183. }
  184. defer o.Close()
  185. priv := &pem.Block{
  186. Type: "RSA PRIVATE KEY",
  187. Bytes: x509.MarshalPKCS1PrivateKey(key),
  188. }
  189. if err := pem.Encode(o, priv); err != nil {
  190. return err
  191. }
  192. pub, err := ssh.NewPublicKey(&key.PublicKey)
  193. if err != nil {
  194. return err
  195. }
  196. return ioutil.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  197. }
  198. // GenerateECDSAKeys generate ecdsa private and public keys and write the
  199. // private key to specified file and the public key to the specified
  200. // file adding the .pub suffix
  201. func GenerateECDSAKeys(file string) error {
  202. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  203. if err != nil {
  204. return err
  205. }
  206. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  207. if err != nil {
  208. return err
  209. }
  210. defer o.Close()
  211. keyBytes, err := x509.MarshalECPrivateKey(key)
  212. if err != nil {
  213. return err
  214. }
  215. priv := &pem.Block{
  216. Type: "EC PRIVATE KEY",
  217. Bytes: keyBytes,
  218. }
  219. if err := pem.Encode(o, priv); err != nil {
  220. return err
  221. }
  222. pub, err := ssh.NewPublicKey(&key.PublicKey)
  223. if err != nil {
  224. return err
  225. }
  226. return ioutil.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  227. }
  228. // GetDirsForSFTPPath returns all the directory for the given path in reverse order
  229. // for example if the path is: /1/2/3/4 it returns:
  230. // [ "/1/2/3/4", "/1/2/3", "/1/2", "/1", "/" ]
  231. func GetDirsForSFTPPath(p string) []string {
  232. sftpPath := CleanSFTPPath(p)
  233. dirsForPath := []string{sftpPath}
  234. for {
  235. if sftpPath == "/" {
  236. break
  237. }
  238. sftpPath = path.Dir(sftpPath)
  239. dirsForPath = append(dirsForPath, sftpPath)
  240. }
  241. return dirsForPath
  242. }
  243. // CleanSFTPPath returns a clean sftp path
  244. func CleanSFTPPath(p string) string {
  245. sftpPath := filepath.ToSlash(p)
  246. if !path.IsAbs(p) {
  247. sftpPath = "/" + sftpPath
  248. }
  249. return path.Clean(sftpPath)
  250. }
  251. // LoadTemplate wraps a call to a function returning (*Template, error)
  252. // it is just like template.Must but it writes a log before exiting
  253. func LoadTemplate(t *template.Template, err error) *template.Template {
  254. if err != nil {
  255. logger.ErrorToConsole("error loading required template: %v", err)
  256. logger.Error(logSender, "", "error loading required template: %v", err)
  257. panic(err)
  258. }
  259. return t
  260. }