utils.go 10 KB

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