util.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  1. // Copyright (C) 2019-2022 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. // Package util provides some common utility methods
  15. package util
  16. import (
  17. "bytes"
  18. "crypto/ecdsa"
  19. "crypto/ed25519"
  20. "crypto/elliptic"
  21. "crypto/rand"
  22. "crypto/rsa"
  23. "crypto/tls"
  24. "crypto/x509"
  25. "encoding/pem"
  26. "errors"
  27. "fmt"
  28. "io"
  29. "io/fs"
  30. "math"
  31. "net"
  32. "net/http"
  33. "net/url"
  34. "os"
  35. "path"
  36. "path/filepath"
  37. "regexp"
  38. "runtime"
  39. "strconv"
  40. "strings"
  41. "time"
  42. "unicode"
  43. "github.com/google/uuid"
  44. "github.com/lithammer/shortuuid/v3"
  45. "github.com/rs/xid"
  46. "golang.org/x/crypto/ssh"
  47. "github.com/drakkan/sftpgo/v2/internal/logger"
  48. )
  49. const (
  50. logSender = "util"
  51. osWindows = "windows"
  52. )
  53. var (
  54. emailRegex = regexp.MustCompile("^(?:(?:(?:(?:[a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(?:\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|(?:(?:\\x22)(?:(?:(?:(?:\\x20|\\x09)*(?:\\x0d\\x0a))?(?:\\x20|\\x09)+)?(?:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(?:(?:(?:\\x20|\\x09)*(?:\\x0d\\x0a))?(\\x20|\\x09)+)?(?:\\x22))))@(?:(?:(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])(?:[a-zA-Z]|\\d|-|\\.|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(?:(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])(?:[a-zA-Z]|\\d|-|\\.|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$")
  55. // this can be set at build time
  56. additionalSharedDataSearchPath = ""
  57. )
  58. // IEC Sizes.
  59. // kibis of bits
  60. const (
  61. oneByte = 1 << (iota * 10)
  62. kiByte
  63. miByte
  64. giByte
  65. tiByte
  66. piByte
  67. eiByte
  68. )
  69. // SI Sizes.
  70. const (
  71. iByte = 1
  72. kbByte = iByte * 1000
  73. mByte = kbByte * 1000
  74. gByte = mByte * 1000
  75. tByte = gByte * 1000
  76. pByte = tByte * 1000
  77. eByte = pByte * 1000
  78. )
  79. var bytesSizeTable = map[string]uint64{
  80. "b": oneByte,
  81. "kib": kiByte,
  82. "kb": kbByte,
  83. "mib": miByte,
  84. "mb": mByte,
  85. "gib": giByte,
  86. "gb": gByte,
  87. "tib": tiByte,
  88. "tb": tByte,
  89. "pib": piByte,
  90. "pb": pByte,
  91. "eib": eiByte,
  92. "eb": eByte,
  93. // Without suffix
  94. "": oneByte,
  95. "ki": kiByte,
  96. "k": kbByte,
  97. "mi": miByte,
  98. "m": mByte,
  99. "gi": giByte,
  100. "g": gByte,
  101. "ti": tiByte,
  102. "t": tByte,
  103. "pi": piByte,
  104. "p": pByte,
  105. "ei": eiByte,
  106. "e": eByte,
  107. }
  108. // Contains reports whether v is present in elems.
  109. func Contains[T comparable](elems []T, v T) bool {
  110. for _, s := range elems {
  111. if v == s {
  112. return true
  113. }
  114. }
  115. return false
  116. }
  117. // IsStringPrefixInSlice searches a string prefix in a slice and returns true
  118. // if a matching prefix is found
  119. func IsStringPrefixInSlice(obj string, list []string) bool {
  120. for i := 0; i < len(list); i++ {
  121. if strings.HasPrefix(obj, list[i]) {
  122. return true
  123. }
  124. }
  125. return false
  126. }
  127. // RemoveDuplicates returns a new slice removing any duplicate element from the initial one
  128. func RemoveDuplicates(obj []string, trim bool) []string {
  129. if len(obj) == 0 {
  130. return obj
  131. }
  132. seen := make(map[string]bool)
  133. validIdx := 0
  134. for _, item := range obj {
  135. if trim {
  136. item = strings.TrimSpace(item)
  137. }
  138. if !seen[item] {
  139. seen[item] = true
  140. obj[validIdx] = item
  141. validIdx++
  142. }
  143. }
  144. return obj[:validIdx]
  145. }
  146. // GetTimeAsMsSinceEpoch returns unix timestamp as milliseconds from a time struct
  147. func GetTimeAsMsSinceEpoch(t time.Time) int64 {
  148. return t.UnixMilli()
  149. }
  150. // GetTimeFromMsecSinceEpoch return a time struct from a unix timestamp with millisecond precision
  151. func GetTimeFromMsecSinceEpoch(msec int64) time.Time {
  152. return time.Unix(0, msec*1000000)
  153. }
  154. // GetDurationAsString returns a string representation for a time.Duration
  155. func GetDurationAsString(d time.Duration) string {
  156. d = d.Round(time.Second)
  157. h := d / time.Hour
  158. d -= h * time.Hour
  159. m := d / time.Minute
  160. d -= m * time.Minute
  161. s := d / time.Second
  162. if h > 0 {
  163. return fmt.Sprintf("%02d:%02d:%02d", h, m, s)
  164. }
  165. return fmt.Sprintf("%02d:%02d", m, s)
  166. }
  167. // ByteCountSI returns humanized size in SI (decimal) format
  168. func ByteCountSI(b int64) string {
  169. return byteCount(b, 1000, true)
  170. }
  171. // ByteCountIEC returns humanized size in IEC (binary) format
  172. func ByteCountIEC(b int64) string {
  173. return byteCount(b, 1024, false)
  174. }
  175. func byteCount(b int64, unit int64, maxPrecision bool) string {
  176. if b <= 0 && maxPrecision {
  177. return strconv.FormatInt(b, 10)
  178. }
  179. if b < unit {
  180. return fmt.Sprintf("%d B", b)
  181. }
  182. div, exp := unit, 0
  183. for n := b / unit; n >= unit; n /= unit {
  184. div *= unit
  185. exp++
  186. }
  187. var val string
  188. if maxPrecision {
  189. val = strconv.FormatFloat(float64(b)/float64(div), 'f', -1, 64)
  190. } else {
  191. val = fmt.Sprintf("%.1f", float64(b)/float64(div))
  192. }
  193. if unit == 1000 {
  194. return fmt.Sprintf("%s %cB", val, "KMGTPE"[exp])
  195. }
  196. return fmt.Sprintf("%s %ciB", val, "KMGTPE"[exp])
  197. }
  198. // ParseBytes parses a string representation of bytes into the number
  199. // of bytes it represents.
  200. //
  201. // ParseBytes("42 MB") -> 42000000, nil
  202. // ParseBytes("42 mib") -> 44040192, nil
  203. //
  204. // copied from here:
  205. //
  206. // https://github.com/dustin/go-humanize/blob/master/bytes.go
  207. //
  208. // with minor modifications
  209. func ParseBytes(s string) (int64, error) {
  210. s = strings.TrimSpace(s)
  211. lastDigit := 0
  212. hasComma := false
  213. for _, r := range s {
  214. if !(unicode.IsDigit(r) || r == '.' || r == ',') {
  215. break
  216. }
  217. if r == ',' {
  218. hasComma = true
  219. }
  220. lastDigit++
  221. }
  222. num := s[:lastDigit]
  223. if hasComma {
  224. num = strings.Replace(num, ",", "", -1)
  225. }
  226. f, err := strconv.ParseFloat(num, 64)
  227. if err != nil {
  228. return 0, err
  229. }
  230. extra := strings.ToLower(strings.TrimSpace(s[lastDigit:]))
  231. if m, ok := bytesSizeTable[extra]; ok {
  232. f *= float64(m)
  233. if f >= math.MaxInt64 {
  234. return 0, fmt.Errorf("value too large: %v", s)
  235. }
  236. if f < 0 {
  237. return 0, fmt.Errorf("negative value not allowed: %v", s)
  238. }
  239. return int64(f), nil
  240. }
  241. return 0, fmt.Errorf("unhandled size name: %v", extra)
  242. }
  243. // GetIPFromRemoteAddress returns the IP from the remote address.
  244. // If the given remote address cannot be parsed it will be returned unchanged
  245. func GetIPFromRemoteAddress(remoteAddress string) string {
  246. ip, _, err := net.SplitHostPort(remoteAddress)
  247. if err == nil {
  248. return ip
  249. }
  250. return remoteAddress
  251. }
  252. // NilIfEmpty returns nil if the input string is empty
  253. func NilIfEmpty(s string) *string {
  254. if s == "" {
  255. return nil
  256. }
  257. return &s
  258. }
  259. // GetStringFromPointer returns the string value or empty if nil
  260. func GetStringFromPointer(val *string) string {
  261. if val == nil {
  262. return ""
  263. }
  264. return *val
  265. }
  266. // GetIntFromPointer returns the int value or zero
  267. func GetIntFromPointer(val *int64) int64 {
  268. if val == nil {
  269. return 0
  270. }
  271. return *val
  272. }
  273. // GetTimeFromPointer returns the time value or now
  274. func GetTimeFromPointer(val *time.Time) time.Time {
  275. if val == nil {
  276. return time.Now()
  277. }
  278. return *val
  279. }
  280. // GenerateRSAKeys generate rsa private and public keys and write the
  281. // private key to specified file and the public key to the specified
  282. // file adding the .pub suffix
  283. func GenerateRSAKeys(file string) error {
  284. if err := createDirPathIfMissing(file, 0700); err != nil {
  285. return err
  286. }
  287. key, err := rsa.GenerateKey(rand.Reader, 4096)
  288. if err != nil {
  289. return err
  290. }
  291. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  292. if err != nil {
  293. return err
  294. }
  295. defer o.Close()
  296. priv := &pem.Block{
  297. Type: "RSA PRIVATE KEY",
  298. Bytes: x509.MarshalPKCS1PrivateKey(key),
  299. }
  300. if err := pem.Encode(o, priv); err != nil {
  301. return err
  302. }
  303. pub, err := ssh.NewPublicKey(&key.PublicKey)
  304. if err != nil {
  305. return err
  306. }
  307. return os.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  308. }
  309. // GenerateECDSAKeys generate ecdsa private and public keys and write the
  310. // private key to specified file and the public key to the specified
  311. // file adding the .pub suffix
  312. func GenerateECDSAKeys(file string) error {
  313. if err := createDirPathIfMissing(file, 0700); err != nil {
  314. return err
  315. }
  316. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  317. if err != nil {
  318. return err
  319. }
  320. keyBytes, err := x509.MarshalECPrivateKey(key)
  321. if err != nil {
  322. return err
  323. }
  324. priv := &pem.Block{
  325. Type: "EC PRIVATE KEY",
  326. Bytes: keyBytes,
  327. }
  328. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  329. if err != nil {
  330. return err
  331. }
  332. defer o.Close()
  333. if err := pem.Encode(o, priv); err != nil {
  334. return err
  335. }
  336. pub, err := ssh.NewPublicKey(&key.PublicKey)
  337. if err != nil {
  338. return err
  339. }
  340. return os.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  341. }
  342. // GenerateEd25519Keys generate ed25519 private and public keys and write the
  343. // private key to specified file and the public key to the specified
  344. // file adding the .pub suffix
  345. func GenerateEd25519Keys(file string) error {
  346. pubKey, privKey, err := ed25519.GenerateKey(rand.Reader)
  347. if err != nil {
  348. return err
  349. }
  350. keyBytes, err := x509.MarshalPKCS8PrivateKey(privKey)
  351. if err != nil {
  352. return err
  353. }
  354. priv := &pem.Block{
  355. Type: "PRIVATE KEY",
  356. Bytes: keyBytes,
  357. }
  358. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  359. if err != nil {
  360. return err
  361. }
  362. defer o.Close()
  363. if err := pem.Encode(o, priv); err != nil {
  364. return err
  365. }
  366. pub, err := ssh.NewPublicKey(pubKey)
  367. if err != nil {
  368. return err
  369. }
  370. return os.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  371. }
  372. // GetDirsForVirtualPath returns all the directory for the given path in reverse order
  373. // for example if the path is: /1/2/3/4 it returns:
  374. // [ "/1/2/3/4", "/1/2/3", "/1/2", "/1", "/" ]
  375. func GetDirsForVirtualPath(virtualPath string) []string {
  376. if virtualPath == "" || virtualPath == "." {
  377. virtualPath = "/"
  378. } else {
  379. if !path.IsAbs(virtualPath) {
  380. virtualPath = CleanPath(virtualPath)
  381. }
  382. }
  383. dirsForPath := []string{virtualPath}
  384. for {
  385. if virtualPath == "/" {
  386. break
  387. }
  388. virtualPath = path.Dir(virtualPath)
  389. dirsForPath = append(dirsForPath, virtualPath)
  390. }
  391. return dirsForPath
  392. }
  393. // CleanPath returns a clean POSIX (/) absolute path to work with
  394. func CleanPath(p string) string {
  395. return CleanPathWithBase("/", p)
  396. }
  397. // CleanPathWithBase returns a clean POSIX (/) absolute path to work with.
  398. // The specified base will be used if the provided path is not absolute
  399. func CleanPathWithBase(base, p string) string {
  400. p = filepath.ToSlash(p)
  401. if !path.IsAbs(p) {
  402. p = path.Join(base, p)
  403. }
  404. return path.Clean(p)
  405. }
  406. // IsFileInputValid returns true this is a valid file name.
  407. // This method must be used before joining a file name, generally provided as
  408. // user input, with a directory
  409. func IsFileInputValid(fileInput string) bool {
  410. cleanInput := filepath.Clean(fileInput)
  411. if cleanInput == "." || cleanInput == ".." {
  412. return false
  413. }
  414. return true
  415. }
  416. // CleanDirInput sanitizes user input for directories.
  417. // On Windows it removes any trailing `"`.
  418. // We try to help windows users that set an invalid path such as "C:\ProgramData\SFTPGO\".
  419. // This will only help if the invalid path is the last argument, for example in this command:
  420. // sftpgo.exe serve -c "C:\ProgramData\SFTPGO\" -l "sftpgo.log"
  421. // the -l flag will be ignored and the -c flag will get the value `C:\ProgramData\SFTPGO" -l sftpgo.log`
  422. // since the backslash after SFTPGO escape the double quote. This is definitely a bad user input
  423. func CleanDirInput(dirInput string) string {
  424. if runtime.GOOS == osWindows {
  425. for strings.HasSuffix(dirInput, "\"") {
  426. dirInput = strings.TrimSuffix(dirInput, "\"")
  427. }
  428. }
  429. return filepath.Clean(dirInput)
  430. }
  431. func createDirPathIfMissing(file string, perm os.FileMode) error {
  432. dirPath := filepath.Dir(file)
  433. if _, err := os.Stat(dirPath); errors.Is(err, fs.ErrNotExist) {
  434. err = os.MkdirAll(dirPath, perm)
  435. if err != nil {
  436. return err
  437. }
  438. }
  439. return nil
  440. }
  441. // GenerateRandomBytes generates the secret to use for JWT auth
  442. func GenerateRandomBytes(length int) []byte {
  443. b := make([]byte, length)
  444. _, err := io.ReadFull(rand.Reader, b)
  445. if err == nil {
  446. return b
  447. }
  448. b = xid.New().Bytes()
  449. for len(b) < length {
  450. b = append(b, xid.New().Bytes()...)
  451. }
  452. return b[:length]
  453. }
  454. // GenerateUniqueID retuens an unique ID
  455. func GenerateUniqueID() string {
  456. u, err := uuid.NewRandom()
  457. if err != nil {
  458. return xid.New().String()
  459. }
  460. return shortuuid.DefaultEncoder.Encode(u)
  461. }
  462. // HTTPListenAndServe is a wrapper for ListenAndServe that support both tcp
  463. // and Unix-domain sockets
  464. func HTTPListenAndServe(srv *http.Server, address string, port int, isTLS bool, logSender string) error {
  465. var listener net.Listener
  466. var err error
  467. if filepath.IsAbs(address) && runtime.GOOS != osWindows {
  468. if !IsFileInputValid(address) {
  469. return fmt.Errorf("invalid socket address %#v", address)
  470. }
  471. err = createDirPathIfMissing(address, os.ModePerm)
  472. if err != nil {
  473. logger.ErrorToConsole("error creating Unix-domain socket parent dir: %v", err)
  474. logger.Error(logSender, "", "error creating Unix-domain socket parent dir: %v", err)
  475. }
  476. os.Remove(address)
  477. listener, err = newListener("unix", address, srv.ReadTimeout, srv.WriteTimeout)
  478. } else {
  479. CheckTCP4Port(port)
  480. listener, err = newListener("tcp", fmt.Sprintf("%s:%d", address, port), srv.ReadTimeout, srv.WriteTimeout)
  481. }
  482. if err != nil {
  483. return err
  484. }
  485. logger.Info(logSender, "", "server listener registered, address: %v TLS enabled: %v", listener.Addr().String(), isTLS)
  486. defer listener.Close()
  487. if isTLS {
  488. return srv.ServeTLS(listener, "", "")
  489. }
  490. return srv.Serve(listener)
  491. }
  492. // GetTLSCiphersFromNames returns the TLS ciphers from the specified names
  493. func GetTLSCiphersFromNames(cipherNames []string) []uint16 {
  494. var ciphers []uint16
  495. for _, name := range RemoveDuplicates(cipherNames, false) {
  496. for _, c := range tls.CipherSuites() {
  497. if c.Name == strings.TrimSpace(name) {
  498. ciphers = append(ciphers, c.ID)
  499. }
  500. }
  501. }
  502. return ciphers
  503. }
  504. // EncodeTLSCertToPem returns the specified certificate PEM encoded.
  505. // This can be verified using openssl x509 -in cert.crt -text -noout
  506. func EncodeTLSCertToPem(tlsCert *x509.Certificate) (string, error) {
  507. if len(tlsCert.Raw) == 0 {
  508. return "", errors.New("invalid x509 certificate, no der contents")
  509. }
  510. publicKeyBlock := pem.Block{
  511. Type: "CERTIFICATE",
  512. Bytes: tlsCert.Raw,
  513. }
  514. return string(pem.EncodeToMemory(&publicKeyBlock)), nil
  515. }
  516. // CheckTCP4Port quits the app if bind on the given IPv4 port fails.
  517. // This is a ugly hack to avoid to bind on an already used port.
  518. // It is required on Windows only. Upstream does not consider this
  519. // behaviour a bug:
  520. // https://github.com/golang/go/issues/45150
  521. func CheckTCP4Port(port int) {
  522. if runtime.GOOS != osWindows {
  523. return
  524. }
  525. listener, err := net.Listen("tcp4", fmt.Sprintf(":%d", port))
  526. if err != nil {
  527. logger.ErrorToConsole("unable to bind on tcp4 address: %v", err)
  528. logger.Error(logSender, "", "unable to bind on tcp4 address: %v", err)
  529. os.Exit(1)
  530. }
  531. listener.Close()
  532. }
  533. // IsByteArrayEmpty return true if the byte array is empty or a new line
  534. func IsByteArrayEmpty(b []byte) bool {
  535. if len(b) == 0 {
  536. return true
  537. }
  538. if bytes.Equal(b, []byte("\n")) {
  539. return true
  540. }
  541. if bytes.Equal(b, []byte("\r\n")) {
  542. return true
  543. }
  544. return false
  545. }
  546. // GetSSHPublicKeyAsString returns an SSH public key serialized as string
  547. func GetSSHPublicKeyAsString(pubKey []byte) (string, error) {
  548. if len(pubKey) == 0 {
  549. return "", nil
  550. }
  551. k, err := ssh.ParsePublicKey(pubKey)
  552. if err != nil {
  553. return "", err
  554. }
  555. return string(ssh.MarshalAuthorizedKey(k)), nil
  556. }
  557. // GetRealIP returns the ip address as result of parsing either the
  558. // X-Real-IP header or the X-Forwarded-For header
  559. func GetRealIP(r *http.Request, header string, depth int) string {
  560. if header == "" {
  561. return ""
  562. }
  563. var ipAddresses []string
  564. for _, h := range r.Header.Values(header) {
  565. for _, ipStr := range strings.Split(h, ",") {
  566. ipStr = strings.TrimSpace(ipStr)
  567. ipAddresses = append(ipAddresses, ipStr)
  568. }
  569. }
  570. idx := len(ipAddresses) - 1 - depth
  571. if idx >= 0 {
  572. ip := strings.TrimSpace(ipAddresses[idx])
  573. if ip == "" || net.ParseIP(ip) == nil {
  574. return ""
  575. }
  576. return ip
  577. }
  578. return ""
  579. }
  580. // GetHTTPLocalAddress returns the local address for an http.Request
  581. // or empty if it cannot be determined
  582. func GetHTTPLocalAddress(r *http.Request) string {
  583. if r == nil {
  584. return ""
  585. }
  586. localAddr, ok := r.Context().Value(http.LocalAddrContextKey).(net.Addr)
  587. if ok {
  588. return localAddr.String()
  589. }
  590. return ""
  591. }
  592. // ParseAllowedIPAndRanges returns a list of functions that allow to find if an
  593. // IP is equal or is contained within the allowed list
  594. func ParseAllowedIPAndRanges(allowed []string) ([]func(net.IP) bool, error) {
  595. res := make([]func(net.IP) bool, len(allowed))
  596. for i, allowFrom := range allowed {
  597. if strings.LastIndex(allowFrom, "/") > 0 {
  598. _, ipRange, err := net.ParseCIDR(allowFrom)
  599. if err != nil {
  600. return nil, fmt.Errorf("given string %q is not a valid IP range: %v", allowFrom, err)
  601. }
  602. res[i] = ipRange.Contains
  603. } else {
  604. allowed := net.ParseIP(allowFrom)
  605. if allowed == nil {
  606. return nil, fmt.Errorf("given string %q is not a valid IP address", allowFrom)
  607. }
  608. res[i] = allowed.Equal
  609. }
  610. }
  611. return res, nil
  612. }
  613. // GetRedactedURL returns the url redacting the password if any
  614. func GetRedactedURL(rawurl string) string {
  615. if !strings.HasPrefix(rawurl, "http") {
  616. return rawurl
  617. }
  618. u, err := url.Parse(rawurl)
  619. if err != nil {
  620. return rawurl
  621. }
  622. return u.Redacted()
  623. }
  624. // PrependFileInfo prepends a file info to a slice in an efficient way.
  625. // We, optimistically, assume that the slice has enough capacity
  626. func PrependFileInfo(files []os.FileInfo, info os.FileInfo) []os.FileInfo {
  627. files = append(files, nil)
  628. copy(files[1:], files)
  629. files[0] = info
  630. return files
  631. }
  632. // GetTLSVersion returns the TLS version for integer:
  633. // - 12 means TLS 1.2
  634. // - 13 means TLS 1.3
  635. // default is TLS 1.2
  636. func GetTLSVersion(val int) uint16 {
  637. switch val {
  638. case 13:
  639. return tls.VersionTLS13
  640. default:
  641. return tls.VersionTLS12
  642. }
  643. }
  644. // IsEmailValid returns true if the specified email address is valid
  645. func IsEmailValid(email string) bool {
  646. return emailRegex.MatchString(email)
  647. }
  648. // PanicOnError calls panic if err is not nil
  649. func PanicOnError(err error) {
  650. if err != nil {
  651. panic(fmt.Errorf("unexpected error: %w", err))
  652. }
  653. }
  654. // GetAbsolutePath returns an absolute path using the current dir as base
  655. // if name defines a relative path
  656. func GetAbsolutePath(name string) (string, error) {
  657. if name == "" {
  658. return name, errors.New("input path cannot be empty")
  659. }
  660. if filepath.IsAbs(name) {
  661. return name, nil
  662. }
  663. curDir, err := os.Getwd()
  664. if err != nil {
  665. return name, err
  666. }
  667. return filepath.Join(curDir, name), nil
  668. }