util.go 24 KB

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