util.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. // Package util provides some common utility methods
  2. package util
  3. import (
  4. "bytes"
  5. "crypto/ecdsa"
  6. "crypto/ed25519"
  7. "crypto/elliptic"
  8. "crypto/rand"
  9. "crypto/rsa"
  10. "crypto/tls"
  11. "crypto/x509"
  12. "encoding/pem"
  13. "errors"
  14. "fmt"
  15. "html/template"
  16. "io"
  17. "net"
  18. "net/http"
  19. "net/url"
  20. "os"
  21. "path"
  22. "path/filepath"
  23. "runtime"
  24. "strings"
  25. "time"
  26. "github.com/google/uuid"
  27. "github.com/lithammer/shortuuid/v3"
  28. "github.com/rs/xid"
  29. "golang.org/x/crypto/ssh"
  30. "github.com/drakkan/sftpgo/v2/logger"
  31. )
  32. const (
  33. logSender = "util"
  34. osWindows = "windows"
  35. )
  36. var (
  37. xForwardedFor = http.CanonicalHeaderKey("X-Forwarded-For")
  38. xRealIP = http.CanonicalHeaderKey("X-Real-IP")
  39. cfConnectingIP = http.CanonicalHeaderKey("CF-Connecting-IP")
  40. trueClientIP = http.CanonicalHeaderKey("True-Client-IP")
  41. )
  42. // IsStringInSlice searches a string in a slice and returns true if the string is found
  43. func IsStringInSlice(obj string, list []string) bool {
  44. for i := 0; i < len(list); i++ {
  45. if list[i] == obj {
  46. return true
  47. }
  48. }
  49. return false
  50. }
  51. // IsStringPrefixInSlice searches a string prefix in a slice and returns true
  52. // if a matching prefix is found
  53. func IsStringPrefixInSlice(obj string, list []string) bool {
  54. for i := 0; i < len(list); i++ {
  55. if strings.HasPrefix(obj, list[i]) {
  56. return true
  57. }
  58. }
  59. return false
  60. }
  61. // RemoveDuplicates returns a new slice removing any duplicate element from the initial one
  62. func RemoveDuplicates(obj []string) []string {
  63. if len(obj) == 0 {
  64. return obj
  65. }
  66. result := make([]string, 0, len(obj))
  67. seen := make(map[string]bool)
  68. for _, item := range obj {
  69. if _, ok := seen[item]; !ok {
  70. result = append(result, item)
  71. }
  72. seen[item] = true
  73. }
  74. return result
  75. }
  76. // GetTimeAsMsSinceEpoch returns unix timestamp as milliseconds from a time struct
  77. func GetTimeAsMsSinceEpoch(t time.Time) int64 {
  78. return t.UnixNano() / 1000000
  79. }
  80. // GetTimeFromMsecSinceEpoch return a time struct from a unix timestamp with millisecond precision
  81. func GetTimeFromMsecSinceEpoch(msec int64) time.Time {
  82. return time.Unix(0, msec*1000000)
  83. }
  84. // GetDurationAsString returns a string representation for a time.Duration
  85. func GetDurationAsString(d time.Duration) string {
  86. d = d.Round(time.Second)
  87. h := d / time.Hour
  88. d -= h * time.Hour
  89. m := d / time.Minute
  90. d -= m * time.Minute
  91. s := d / time.Second
  92. if h > 0 {
  93. return fmt.Sprintf("%02d:%02d:%02d", h, m, s)
  94. }
  95. return fmt.Sprintf("%02d:%02d", m, s)
  96. }
  97. // ByteCountSI returns humanized size in SI (decimal) format
  98. func ByteCountSI(b int64) string {
  99. return byteCount(b, 1000)
  100. }
  101. // ByteCountIEC returns humanized size in IEC (binary) format
  102. func ByteCountIEC(b int64) string {
  103. return byteCount(b, 1024)
  104. }
  105. func byteCount(b int64, unit int64) string {
  106. if b < unit {
  107. return fmt.Sprintf("%d B", b)
  108. }
  109. div, exp := unit, 0
  110. for n := b / unit; n >= unit; n /= unit {
  111. div *= unit
  112. exp++
  113. }
  114. if unit == 1000 {
  115. return fmt.Sprintf("%.1f %cB",
  116. float64(b)/float64(div), "KMGTPE"[exp])
  117. }
  118. return fmt.Sprintf("%.1f %ciB",
  119. float64(b)/float64(div), "KMGTPE"[exp])
  120. }
  121. // GetIPFromRemoteAddress returns the IP from the remote address.
  122. // If the given remote address cannot be parsed it will be returned unchanged
  123. func GetIPFromRemoteAddress(remoteAddress string) string {
  124. ip, _, err := net.SplitHostPort(remoteAddress)
  125. if err == nil {
  126. return ip
  127. }
  128. return remoteAddress
  129. }
  130. // NilIfEmpty returns nil if the input string is empty
  131. func NilIfEmpty(s string) *string {
  132. if len(s) == 0 {
  133. return nil
  134. }
  135. return &s
  136. }
  137. // GenerateRSAKeys generate rsa private and public keys and write the
  138. // private key to specified file and the public key to the specified
  139. // file adding the .pub suffix
  140. func GenerateRSAKeys(file string) error {
  141. if err := createDirPathIfMissing(file, 0700); err != nil {
  142. return err
  143. }
  144. key, err := rsa.GenerateKey(rand.Reader, 4096)
  145. if err != nil {
  146. return err
  147. }
  148. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  149. if err != nil {
  150. return err
  151. }
  152. defer o.Close()
  153. priv := &pem.Block{
  154. Type: "RSA PRIVATE KEY",
  155. Bytes: x509.MarshalPKCS1PrivateKey(key),
  156. }
  157. if err := pem.Encode(o, priv); err != nil {
  158. return err
  159. }
  160. pub, err := ssh.NewPublicKey(&key.PublicKey)
  161. if err != nil {
  162. return err
  163. }
  164. return os.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  165. }
  166. // GenerateECDSAKeys generate ecdsa private and public keys and write the
  167. // private key to specified file and the public key to the specified
  168. // file adding the .pub suffix
  169. func GenerateECDSAKeys(file string) error {
  170. if err := createDirPathIfMissing(file, 0700); err != nil {
  171. return err
  172. }
  173. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  174. if err != nil {
  175. return err
  176. }
  177. keyBytes, err := x509.MarshalECPrivateKey(key)
  178. if err != nil {
  179. return err
  180. }
  181. priv := &pem.Block{
  182. Type: "EC PRIVATE KEY",
  183. Bytes: keyBytes,
  184. }
  185. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  186. if err != nil {
  187. return err
  188. }
  189. defer o.Close()
  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 os.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  198. }
  199. // GenerateEd25519Keys generate ed25519 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 GenerateEd25519Keys(file string) error {
  203. pubKey, privKey, err := ed25519.GenerateKey(rand.Reader)
  204. if err != nil {
  205. return err
  206. }
  207. keyBytes, err := x509.MarshalPKCS8PrivateKey(privKey)
  208. if err != nil {
  209. return err
  210. }
  211. priv := &pem.Block{
  212. Type: "PRIVATE KEY",
  213. Bytes: keyBytes,
  214. }
  215. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  216. if err != nil {
  217. return err
  218. }
  219. defer o.Close()
  220. if err := pem.Encode(o, priv); err != nil {
  221. return err
  222. }
  223. pub, err := ssh.NewPublicKey(pubKey)
  224. if err != nil {
  225. return err
  226. }
  227. return os.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  228. }
  229. // GetDirsForVirtualPath returns all the directory for the given path in reverse order
  230. // for example if the path is: /1/2/3/4 it returns:
  231. // [ "/1/2/3/4", "/1/2/3", "/1/2", "/1", "/" ]
  232. func GetDirsForVirtualPath(virtualPath string) []string {
  233. if virtualPath == "." {
  234. virtualPath = "/"
  235. } else {
  236. if !path.IsAbs(virtualPath) {
  237. virtualPath = CleanPath(virtualPath)
  238. }
  239. }
  240. dirsForPath := []string{virtualPath}
  241. for {
  242. if virtualPath == "/" {
  243. break
  244. }
  245. virtualPath = path.Dir(virtualPath)
  246. dirsForPath = append(dirsForPath, virtualPath)
  247. }
  248. return dirsForPath
  249. }
  250. // CleanPath returns a clean POSIX (/) absolute path to work with
  251. func CleanPath(p string) string {
  252. p = filepath.ToSlash(p)
  253. if !path.IsAbs(p) {
  254. p = "/" + p
  255. }
  256. return path.Clean(p)
  257. }
  258. // LoadTemplate parses the given template paths.
  259. // It behaves like template.Must but it writes a log before exiting.
  260. // You can optionally provide a base template (e.g. to define some custom functions)
  261. func LoadTemplate(base *template.Template, paths ...string) *template.Template {
  262. var t *template.Template
  263. var err error
  264. if base != nil {
  265. base, err = base.Clone()
  266. if err == nil {
  267. t, err = base.ParseFiles(paths...)
  268. }
  269. } else {
  270. t, err = template.ParseFiles(paths...)
  271. }
  272. if err != nil {
  273. logger.ErrorToConsole("error loading required template: %v", err)
  274. logger.Error(logSender, "", "error loading required template: %v", err)
  275. panic(err)
  276. }
  277. return t
  278. }
  279. // IsFileInputValid returns true this is a valid file name.
  280. // This method must be used before joining a file name, generally provided as
  281. // user input, with a directory
  282. func IsFileInputValid(fileInput string) bool {
  283. cleanInput := filepath.Clean(fileInput)
  284. if cleanInput == "." || cleanInput == ".." {
  285. return false
  286. }
  287. return true
  288. }
  289. // CleanDirInput sanitizes user input for directories.
  290. // On Windows it removes any trailing `"`.
  291. // We try to help windows users that set an invalid path such as "C:\ProgramData\SFTPGO\".
  292. // This will only help if the invalid path is the last argument, for example in this command:
  293. // sftpgo.exe serve -c "C:\ProgramData\SFTPGO\" -l "sftpgo.log"
  294. // the -l flag will be ignored and the -c flag will get the value `C:\ProgramData\SFTPGO" -l sftpgo.log`
  295. // since the backslash after SFTPGO escape the double quote. This is definitely a bad user input
  296. func CleanDirInput(dirInput string) string {
  297. if runtime.GOOS == osWindows {
  298. for strings.HasSuffix(dirInput, "\"") {
  299. dirInput = strings.TrimSuffix(dirInput, "\"")
  300. }
  301. }
  302. return filepath.Clean(dirInput)
  303. }
  304. func createDirPathIfMissing(file string, perm os.FileMode) error {
  305. dirPath := filepath.Dir(file)
  306. if _, err := os.Stat(dirPath); os.IsNotExist(err) {
  307. err = os.MkdirAll(dirPath, perm)
  308. if err != nil {
  309. return err
  310. }
  311. }
  312. return nil
  313. }
  314. // GenerateRandomBytes generates the secret to use for JWT auth
  315. func GenerateRandomBytes(length int) []byte {
  316. b := make([]byte, length)
  317. _, err := io.ReadFull(rand.Reader, b)
  318. if err == nil {
  319. return b
  320. }
  321. b = xid.New().Bytes()
  322. for len(b) < length {
  323. b = append(b, xid.New().Bytes()...)
  324. }
  325. return b[:length]
  326. }
  327. // GenerateUniqueID retuens an unique ID
  328. func GenerateUniqueID() string {
  329. u, err := uuid.NewRandom()
  330. if err != nil {
  331. return xid.New().String()
  332. }
  333. return shortuuid.DefaultEncoder.Encode(u)
  334. }
  335. // HTTPListenAndServe is a wrapper for ListenAndServe that support both tcp
  336. // and Unix-domain sockets
  337. func HTTPListenAndServe(srv *http.Server, address string, port int, isTLS bool, logSender string) error {
  338. var listener net.Listener
  339. var err error
  340. if filepath.IsAbs(address) && runtime.GOOS != osWindows {
  341. if !IsFileInputValid(address) {
  342. return fmt.Errorf("invalid socket address %#v", address)
  343. }
  344. err = createDirPathIfMissing(address, os.ModePerm)
  345. if err != nil {
  346. logger.ErrorToConsole("error creating Unix-domain socket parent dir: %v", err)
  347. logger.Error(logSender, "", "error creating Unix-domain socket parent dir: %v", err)
  348. }
  349. os.Remove(address)
  350. listener, err = newListener("unix", address, srv.ReadTimeout, srv.WriteTimeout)
  351. } else {
  352. CheckTCP4Port(port)
  353. listener, err = newListener("tcp", fmt.Sprintf("%s:%d", address, port), srv.ReadTimeout, srv.WriteTimeout)
  354. }
  355. if err != nil {
  356. return err
  357. }
  358. logger.Info(logSender, "", "server listener registered, address: %v TLS enabled: %v", listener.Addr().String(), isTLS)
  359. defer listener.Close()
  360. if isTLS {
  361. return srv.ServeTLS(listener, "", "")
  362. }
  363. return srv.Serve(listener)
  364. }
  365. // GetTLSCiphersFromNames returns the TLS ciphers from the specified names
  366. func GetTLSCiphersFromNames(cipherNames []string) []uint16 {
  367. var ciphers []uint16
  368. for _, name := range RemoveDuplicates(cipherNames) {
  369. for _, c := range tls.CipherSuites() {
  370. if c.Name == strings.TrimSpace(name) {
  371. ciphers = append(ciphers, c.ID)
  372. }
  373. }
  374. }
  375. return ciphers
  376. }
  377. // EncodeTLSCertToPem returns the specified certificate PEM encoded.
  378. // This can be verified using openssl x509 -in cert.crt -text -noout
  379. func EncodeTLSCertToPem(tlsCert *x509.Certificate) (string, error) {
  380. if len(tlsCert.Raw) == 0 {
  381. return "", errors.New("invalid x509 certificate, no der contents")
  382. }
  383. publicKeyBlock := pem.Block{
  384. Type: "CERTIFICATE",
  385. Bytes: tlsCert.Raw,
  386. }
  387. return string(pem.EncodeToMemory(&publicKeyBlock)), nil
  388. }
  389. // CheckTCP4Port quits the app if bind on the given IPv4 port fails.
  390. // This is a ugly hack to avoid to bind on an already used port.
  391. // It is required on Windows only. Upstream does not consider this
  392. // behaviour a bug:
  393. // https://github.com/golang/go/issues/45150
  394. func CheckTCP4Port(port int) {
  395. if runtime.GOOS != osWindows {
  396. return
  397. }
  398. listener, err := net.Listen("tcp4", fmt.Sprintf(":%d", port))
  399. if err != nil {
  400. logger.ErrorToConsole("unable to bind on tcp4 address: %v", err)
  401. logger.Error(logSender, "", "unable to bind on tcp4 address: %v", err)
  402. os.Exit(1)
  403. }
  404. listener.Close()
  405. }
  406. // IsByteArrayEmpty return true if the byte array is empty or a new line
  407. func IsByteArrayEmpty(b []byte) bool {
  408. if len(b) == 0 {
  409. return true
  410. }
  411. if bytes.Equal(b, []byte("\n")) {
  412. return true
  413. }
  414. if bytes.Equal(b, []byte("\r\n")) {
  415. return true
  416. }
  417. return false
  418. }
  419. // GetSSHPublicKeyAsString returns an SSH public key serialized as string
  420. func GetSSHPublicKeyAsString(pubKey []byte) (string, error) {
  421. if len(pubKey) == 0 {
  422. return "", nil
  423. }
  424. k, err := ssh.ParsePublicKey(pubKey)
  425. if err != nil {
  426. return "", err
  427. }
  428. return string(ssh.MarshalAuthorizedKey(k)), nil
  429. }
  430. // GetRealIP returns the ip address as result of parsing either the
  431. // X-Real-IP header or the X-Forwarded-For header
  432. func GetRealIP(r *http.Request) string {
  433. var ip string
  434. if clientIP := r.Header.Get(trueClientIP); clientIP != "" {
  435. ip = clientIP
  436. } else if xrip := r.Header.Get(xRealIP); xrip != "" {
  437. ip = xrip
  438. } else if clientIP := r.Header.Get(cfConnectingIP); clientIP != "" {
  439. ip = clientIP
  440. } else if xff := r.Header.Get(xForwardedFor); xff != "" {
  441. i := strings.Index(xff, ", ")
  442. if i == -1 {
  443. i = len(xff)
  444. }
  445. ip = strings.TrimSpace(xff[:i])
  446. }
  447. if net.ParseIP(ip) == nil {
  448. return ""
  449. }
  450. return ip
  451. }
  452. // GetHTTPLocalAddress returns the local address for an http.Request
  453. // or empty if it cannot be determined
  454. func GetHTTPLocalAddress(r *http.Request) string {
  455. if r == nil {
  456. return ""
  457. }
  458. localAddr, ok := r.Context().Value(http.LocalAddrContextKey).(net.Addr)
  459. if ok {
  460. return localAddr.String()
  461. }
  462. return ""
  463. }
  464. // ParseAllowedIPAndRanges returns a list of functions that allow to find if an
  465. // IP is equal or is contained within the allowed list
  466. func ParseAllowedIPAndRanges(allowed []string) ([]func(net.IP) bool, error) {
  467. res := make([]func(net.IP) bool, len(allowed))
  468. for i, allowFrom := range allowed {
  469. if strings.LastIndex(allowFrom, "/") > 0 {
  470. _, ipRange, err := net.ParseCIDR(allowFrom)
  471. if err != nil {
  472. return nil, fmt.Errorf("given string %q is not a valid IP range: %v", allowFrom, err)
  473. }
  474. res[i] = ipRange.Contains
  475. } else {
  476. allowed := net.ParseIP(allowFrom)
  477. if allowed == nil {
  478. return nil, fmt.Errorf("given string %q is not a valid IP address", allowFrom)
  479. }
  480. res[i] = allowed.Equal
  481. }
  482. }
  483. return res, nil
  484. }
  485. // GetRedactedURL returns the url redacting the password if any
  486. func GetRedactedURL(rawurl string) string {
  487. if !strings.HasPrefix(rawurl, "http") {
  488. return rawurl
  489. }
  490. u, err := url.Parse(rawurl)
  491. if err != nil {
  492. return rawurl
  493. }
  494. return u.Redacted()
  495. }
  496. // PrependFileInfo prepends a file info to a slice in an efficient way.
  497. // We, optimistically, assume that the slice has enough capacity
  498. func PrependFileInfo(files []os.FileInfo, info os.FileInfo) []os.FileInfo {
  499. files = append(files, nil)
  500. copy(files[1:], files)
  501. files[0] = info
  502. return files
  503. }