util.go 21 KB

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