utils.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package psiphon
  20. import (
  21. "crypto/rand"
  22. "crypto/x509"
  23. "encoding/base64"
  24. "errors"
  25. "fmt"
  26. "math/big"
  27. "runtime"
  28. "strings"
  29. "time"
  30. )
  31. // Contains is a helper function that returns true
  32. // if the target string is in the list.
  33. func Contains(list []string, target string) bool {
  34. for _, listItem := range list {
  35. if listItem == target {
  36. return true
  37. }
  38. }
  39. return false
  40. }
  41. // MakeSecureRandomInt is a helper function that wraps
  42. // MakeSecureRandomInt64.
  43. func MakeSecureRandomInt(max int) (int, error) {
  44. randomInt, err := MakeSecureRandomInt64(int64(max))
  45. return int(randomInt), err
  46. }
  47. // MakeSecureRandomInt64 is a helper function that wraps
  48. // crypto/rand.Int, which returns a uniform random value in [0, max).
  49. func MakeSecureRandomInt64(max int64) (int64, error) {
  50. randomInt, err := rand.Int(rand.Reader, big.NewInt(max))
  51. if err != nil {
  52. return 0, ContextError(err)
  53. }
  54. return randomInt.Int64(), nil
  55. }
  56. // MakeSecureRandomBytes is a helper function that wraps
  57. // crypto/rand.Read.
  58. func MakeSecureRandomBytes(length int) ([]byte, error) {
  59. randomBytes := make([]byte, length)
  60. n, err := rand.Read(randomBytes)
  61. if err != nil {
  62. return nil, ContextError(err)
  63. }
  64. if n != length {
  65. return nil, ContextError(errors.New("insufficient random bytes"))
  66. }
  67. return randomBytes, nil
  68. }
  69. // MakeSecureRandomPadding selects a random padding length in the indicated
  70. // range and returns a random byte array of the selected length.
  71. // In the unlikely case where an underlying MakeRandom functions fails,
  72. // the padding is length 0.
  73. func MakeSecureRandomPadding(minLength, maxLength int) []byte {
  74. var padding []byte
  75. paddingSize, err := MakeSecureRandomInt(maxLength - minLength)
  76. if err != nil {
  77. NoticeAlert("MakeSecureRandomPadding: MakeSecureRandomInt failed")
  78. return make([]byte, 0)
  79. }
  80. paddingSize += minLength
  81. padding, err = MakeSecureRandomBytes(paddingSize)
  82. if err != nil {
  83. NoticeAlert("MakeSecureRandomPadding: MakeSecureRandomBytes failed")
  84. return make([]byte, 0)
  85. }
  86. return padding
  87. }
  88. // MakeRandomPeriod returns a random duration, within a given range.
  89. // In the unlikely case where an underlying MakeRandom functions fails,
  90. // the period is the minimum.
  91. func MakeRandomPeriod(min, max time.Duration) (duration time.Duration) {
  92. period, err := MakeSecureRandomInt64(max.Nanoseconds() - min.Nanoseconds())
  93. if err != nil {
  94. NoticeAlert("NextRandomRangePeriod: MakeSecureRandomInt64 failed")
  95. }
  96. duration = min + time.Duration(period)
  97. return
  98. }
  99. func DecodeCertificate(encodedCertificate string) (certificate *x509.Certificate, err error) {
  100. derEncodedCertificate, err := base64.StdEncoding.DecodeString(encodedCertificate)
  101. if err != nil {
  102. return nil, ContextError(err)
  103. }
  104. certificate, err = x509.ParseCertificate(derEncodedCertificate)
  105. if err != nil {
  106. return nil, ContextError(err)
  107. }
  108. return certificate, nil
  109. }
  110. // TrimError removes the middle of over-long error message strings
  111. func TrimError(err error) error {
  112. const MAX_LEN = 100
  113. message := fmt.Sprintf("%s", err)
  114. if len(message) > MAX_LEN {
  115. return errors.New(message[:MAX_LEN/2] + "..." + message[len(message)-MAX_LEN/2:])
  116. }
  117. return err
  118. }
  119. // ContextError prefixes an error message with the current function name
  120. func ContextError(err error) error {
  121. if err == nil {
  122. return nil
  123. }
  124. pc, _, line, _ := runtime.Caller(1)
  125. funcName := runtime.FuncForPC(pc).Name()
  126. index := strings.LastIndex(funcName, "/")
  127. if index != -1 {
  128. funcName = funcName[index+1:]
  129. }
  130. return fmt.Errorf("%s#%d: %s", funcName, line, err)
  131. }
  132. // IsNetworkBindError returns true when the err is due to EADDRINUSE.
  133. func IsNetworkBindError(err error) bool {
  134. return strings.Contains(err.Error(), "bind: address already in use")
  135. }