util.go 22 KB

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