utils.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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. "bytes"
  22. "crypto/rand"
  23. "crypto/x509"
  24. "encoding/base64"
  25. "encoding/json"
  26. "errors"
  27. "fmt"
  28. "io"
  29. "math/big"
  30. "os"
  31. "runtime"
  32. "strings"
  33. "sync"
  34. "time"
  35. )
  36. // Contains is a helper function that returns true
  37. // if the target string is in the list.
  38. func Contains(list []string, target string) bool {
  39. for _, listItem := range list {
  40. if listItem == target {
  41. return true
  42. }
  43. }
  44. return false
  45. }
  46. // MakeSecureRandomInt is a helper function that wraps
  47. // MakeSecureRandomInt64.
  48. func MakeSecureRandomInt(max int) (int, error) {
  49. randomInt, err := MakeSecureRandomInt64(int64(max))
  50. return int(randomInt), err
  51. }
  52. // MakeSecureRandomInt64 is a helper function that wraps
  53. // crypto/rand.Int, which returns a uniform random value in [0, max).
  54. func MakeSecureRandomInt64(max int64) (int64, error) {
  55. randomInt, err := rand.Int(rand.Reader, big.NewInt(max))
  56. if err != nil {
  57. return 0, ContextError(err)
  58. }
  59. return randomInt.Int64(), nil
  60. }
  61. // MakeSecureRandomBytes is a helper function that wraps
  62. // crypto/rand.Read.
  63. func MakeSecureRandomBytes(length int) ([]byte, error) {
  64. randomBytes := make([]byte, length)
  65. n, err := rand.Read(randomBytes)
  66. if err != nil {
  67. return nil, ContextError(err)
  68. }
  69. if n != length {
  70. return nil, ContextError(errors.New("insufficient random bytes"))
  71. }
  72. return randomBytes, nil
  73. }
  74. // MakeSecureRandomPadding selects a random padding length in the indicated
  75. // range and returns a random byte array of the selected length.
  76. // In the unlikely case where an underlying MakeRandom functions fails,
  77. // the padding is length 0.
  78. func MakeSecureRandomPadding(minLength, maxLength int) []byte {
  79. var padding []byte
  80. paddingSize, err := MakeSecureRandomInt(maxLength - minLength)
  81. if err != nil {
  82. NoticeAlert("MakeSecureRandomPadding: MakeSecureRandomInt failed")
  83. return make([]byte, 0)
  84. }
  85. paddingSize += minLength
  86. padding, err = MakeSecureRandomBytes(paddingSize)
  87. if err != nil {
  88. NoticeAlert("MakeSecureRandomPadding: MakeSecureRandomBytes failed")
  89. return make([]byte, 0)
  90. }
  91. return padding
  92. }
  93. // MakeRandomPeriod returns a random duration, within a given range.
  94. // In the unlikely case where an underlying MakeRandom functions fails,
  95. // the period is the minimum.
  96. func MakeRandomPeriod(min, max time.Duration) (duration time.Duration) {
  97. period, err := MakeSecureRandomInt64(max.Nanoseconds() - min.Nanoseconds())
  98. if err != nil {
  99. NoticeAlert("NextRandomRangePeriod: MakeSecureRandomInt64 failed")
  100. }
  101. duration = min + time.Duration(period)
  102. return
  103. }
  104. func DecodeCertificate(encodedCertificate string) (certificate *x509.Certificate, err error) {
  105. derEncodedCertificate, err := base64.StdEncoding.DecodeString(encodedCertificate)
  106. if err != nil {
  107. return nil, ContextError(err)
  108. }
  109. certificate, err = x509.ParseCertificate(derEncodedCertificate)
  110. if err != nil {
  111. return nil, ContextError(err)
  112. }
  113. return certificate, nil
  114. }
  115. // TrimError removes the middle of over-long error message strings
  116. func TrimError(err error) error {
  117. const MAX_LEN = 100
  118. message := fmt.Sprintf("%s", err)
  119. if len(message) > MAX_LEN {
  120. return errors.New(message[:MAX_LEN/2] + "..." + message[len(message)-MAX_LEN/2:])
  121. }
  122. return err
  123. }
  124. // ContextError prefixes an error message with the current function name
  125. func ContextError(err error) error {
  126. if err == nil {
  127. return nil
  128. }
  129. pc, _, line, _ := runtime.Caller(1)
  130. funcName := runtime.FuncForPC(pc).Name()
  131. index := strings.LastIndex(funcName, "/")
  132. if index != -1 {
  133. funcName = funcName[index+1:]
  134. }
  135. return fmt.Errorf("%s#%d: %s", funcName, line, err)
  136. }
  137. // IsNetworkBindError returns true when the err is due to EADDRINUSE.
  138. func IsNetworkBindError(err error) bool {
  139. return strings.Contains(err.Error(), "bind: address already in use")
  140. }
  141. // NoticeConsoleRewriter consumes JOSN-format notice input and parses each
  142. // notice and rewrites in a more human-readable format more suitable for
  143. // console output. The data payload field is left as JSON.
  144. type NoticeConsoleRewriter struct {
  145. mutex sync.Mutex
  146. writer io.Writer
  147. buffer []byte
  148. }
  149. // NewNoticeConsoleRewriter initializes a new NoticeConsoleRewriter
  150. func NewNoticeConsoleRewriter(writer io.Writer) *NoticeConsoleRewriter {
  151. return &NoticeConsoleRewriter{writer: writer}
  152. }
  153. // Write implements io.Writer.
  154. func (rewriter *NoticeConsoleRewriter) Write(p []byte) (n int, err error) {
  155. rewriter.mutex.Lock()
  156. defer rewriter.mutex.Unlock()
  157. rewriter.buffer = append(rewriter.buffer, p...)
  158. index := bytes.Index(rewriter.buffer, []byte("\n"))
  159. if index == -1 {
  160. return len(p), nil
  161. }
  162. line := rewriter.buffer[:index]
  163. rewriter.buffer = rewriter.buffer[index+1:]
  164. type NoticeObject struct {
  165. NoticeType string `json:"noticeType"`
  166. Data json.RawMessage `json:"data"`
  167. Timestamp string `json:"timestamp"`
  168. }
  169. var noticeObject NoticeObject
  170. _ = json.Unmarshal(line, &noticeObject)
  171. fmt.Fprintf(os.Stderr,
  172. "%s %s %s\n",
  173. noticeObject.Timestamp,
  174. noticeObject.NoticeType,
  175. string(noticeObject.Data))
  176. return len(p), nil
  177. }