utils.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. "net"
  28. "os"
  29. "runtime"
  30. "strings"
  31. "syscall"
  32. "time"
  33. )
  34. // Contains is a helper function that returns true
  35. // if the target string is in the list.
  36. func Contains(list []string, target string) bool {
  37. for _, listItem := range list {
  38. if listItem == target {
  39. return true
  40. }
  41. }
  42. return false
  43. }
  44. // MakeSecureRandomInt is a helper function that wraps
  45. // MakeSecureRandomInt64.
  46. func MakeSecureRandomInt(max int) (int, error) {
  47. randomInt, err := MakeSecureRandomInt64(int64(max))
  48. return int(randomInt), err
  49. }
  50. // MakeSecureRandomInt64 is a helper function that wraps
  51. // crypto/rand.Int, which returns a uniform random value in [0, max).
  52. func MakeSecureRandomInt64(max int64) (int64, error) {
  53. randomInt, err := rand.Int(rand.Reader, big.NewInt(max))
  54. if err != nil {
  55. return 0, ContextError(err)
  56. }
  57. return randomInt.Int64(), nil
  58. }
  59. // MakeSecureRandomBytes is a helper function that wraps
  60. // crypto/rand.Read.
  61. func MakeSecureRandomBytes(length int) ([]byte, error) {
  62. randomBytes := make([]byte, length)
  63. n, err := rand.Read(randomBytes)
  64. if err != nil {
  65. return nil, ContextError(err)
  66. }
  67. if n != length {
  68. return nil, ContextError(errors.New("insufficient random bytes"))
  69. }
  70. return randomBytes, nil
  71. }
  72. // MakeSecureRandomPadding selects a random padding length in the indicated
  73. // range and returns a random byte array of the selected length.
  74. // In the unlikely case where an underlying MakeRandom functions fails,
  75. // the padding is length 0.
  76. func MakeSecureRandomPadding(minLength, maxLength int) []byte {
  77. var padding []byte
  78. paddingSize, err := MakeSecureRandomInt(maxLength - minLength)
  79. if err != nil {
  80. NoticeAlert("MakeSecureRandomPadding: MakeSecureRandomInt failed")
  81. return make([]byte, 0)
  82. }
  83. paddingSize += minLength
  84. padding, err = MakeSecureRandomBytes(paddingSize)
  85. if err != nil {
  86. NoticeAlert("MakeSecureRandomPadding: MakeSecureRandomBytes failed")
  87. return make([]byte, 0)
  88. }
  89. return padding
  90. }
  91. // MakeRandomPeriod returns a random duration, within a given range.
  92. // In the unlikely case where an underlying MakeRandom functions fails,
  93. // the period is the minimum.
  94. func MakeRandomPeriod(min, max time.Duration) (duration time.Duration) {
  95. period, err := MakeSecureRandomInt64(max.Nanoseconds() - min.Nanoseconds())
  96. if err != nil {
  97. NoticeAlert("NextRandomRangePeriod: MakeSecureRandomInt64 failed")
  98. }
  99. duration = min + time.Duration(period)
  100. return
  101. }
  102. func DecodeCertificate(encodedCertificate string) (certificate *x509.Certificate, err error) {
  103. derEncodedCertificate, err := base64.StdEncoding.DecodeString(encodedCertificate)
  104. if err != nil {
  105. return nil, ContextError(err)
  106. }
  107. certificate, err = x509.ParseCertificate(derEncodedCertificate)
  108. if err != nil {
  109. return nil, ContextError(err)
  110. }
  111. return certificate, nil
  112. }
  113. // TrimError removes the middle of over-long error message strings
  114. func TrimError(err error) error {
  115. const MAX_LEN = 100
  116. message := fmt.Sprintf("%s", err)
  117. if len(message) > MAX_LEN {
  118. return errors.New(message[:MAX_LEN/2] + "..." + message[len(message)-MAX_LEN/2:])
  119. }
  120. return err
  121. }
  122. // ContextError prefixes an error message with the current function name
  123. func ContextError(err error) error {
  124. if err == nil {
  125. return nil
  126. }
  127. pc, _, line, _ := runtime.Caller(1)
  128. funcName := runtime.FuncForPC(pc).Name()
  129. index := strings.LastIndex(funcName, "/")
  130. if index != -1 {
  131. funcName = funcName[index+1:]
  132. }
  133. return fmt.Errorf("%s#%d: %s", funcName, line, err)
  134. }
  135. // IsAddressInUseError returns true when the err is due to EADDRINUSE/WSAEADDRINUSE.
  136. func IsAddressInUseError(err error) bool {
  137. if err, ok := err.(*net.OpError); ok {
  138. if err, ok := err.Err.(*os.SyscallError); ok {
  139. if err.Err == syscall.EADDRINUSE {
  140. return true
  141. }
  142. // Special case for Windows (WSAEADDRINUSE = 10048)
  143. if errno, ok := err.Err.(syscall.Errno); ok {
  144. if 10048 == int(errno) {
  145. return true
  146. }
  147. }
  148. }
  149. }
  150. return false
  151. }