feedback.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. /*
  2. * Copyright (c) 2016, 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. "context"
  23. "crypto/aes"
  24. "crypto/cipher"
  25. "crypto/hmac"
  26. "crypto/rand"
  27. "crypto/rsa"
  28. "crypto/sha1"
  29. "crypto/sha256"
  30. "crypto/x509"
  31. "encoding/base64"
  32. "encoding/hex"
  33. "encoding/json"
  34. "errors"
  35. "net/http"
  36. "strconv"
  37. "strings"
  38. "time"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  40. )
  41. const (
  42. FEEDBACK_UPLOAD_MAX_RETRIES = 5
  43. FEEDBACK_UPLOAD_RETRY_DELAY_SECONDS = 300
  44. FEEDBACK_UPLOAD_TIMEOUT_SECONDS = 30
  45. )
  46. // Conforms to the format expected by the feedback decryptor.
  47. // https://bitbucket.org/psiphon/psiphon-circumvention-system/src/default/EmailResponder/FeedbackDecryptor/decryptor.py
  48. type secureFeedback struct {
  49. IV string `json:"iv"`
  50. ContentCipherText string `json:"contentCiphertext"`
  51. WrappedEncryptionKey string `json:"wrappedEncryptionKey"`
  52. ContentMac string `json:"contentMac"`
  53. WrappedMacKey string `json:"wrappedMacKey"`
  54. }
  55. // Encrypt and marshal feedback into secure json structure utilizing the
  56. // Encrypt-then-MAC paradigm (https://tools.ietf.org/html/rfc7366#section-3).
  57. func encryptFeedback(diagnosticsJson, b64EncodedPublicKey string) ([]byte, error) {
  58. publicKey, err := base64.StdEncoding.DecodeString(b64EncodedPublicKey)
  59. if err != nil {
  60. return nil, common.ContextError(err)
  61. }
  62. iv, encryptionKey, diagnosticsCiphertext, err := encryptAESCBC([]byte(diagnosticsJson))
  63. if err != nil {
  64. return nil, err
  65. }
  66. digest, macKey, err := generateHMAC(iv, diagnosticsCiphertext)
  67. if err != nil {
  68. return nil, err
  69. }
  70. wrappedMacKey, err := encryptWithPublicKey(macKey, publicKey)
  71. if err != nil {
  72. return nil, err
  73. }
  74. wrappedEncryptionKey, err := encryptWithPublicKey(encryptionKey, publicKey)
  75. if err != nil {
  76. return nil, err
  77. }
  78. var securedFeedback = secureFeedback{
  79. IV: base64.StdEncoding.EncodeToString(iv),
  80. ContentCipherText: base64.StdEncoding.EncodeToString(diagnosticsCiphertext),
  81. WrappedEncryptionKey: base64.StdEncoding.EncodeToString(wrappedEncryptionKey),
  82. ContentMac: base64.StdEncoding.EncodeToString(digest),
  83. WrappedMacKey: base64.StdEncoding.EncodeToString(wrappedMacKey),
  84. }
  85. encryptedFeedback, err := json.Marshal(securedFeedback)
  86. if err != nil {
  87. return nil, common.ContextError(err)
  88. }
  89. return encryptedFeedback, nil
  90. }
  91. // Encrypt feedback and upload to server. If upload fails
  92. // the feedback thread will sleep and retry multiple times.
  93. func SendFeedback(configJson, diagnosticsJson, b64EncodedPublicKey, uploadServer, uploadPath, uploadServerHeaders string) error {
  94. config, err := LoadConfig([]byte(configJson))
  95. if err != nil {
  96. return common.ContextError(err)
  97. }
  98. err = config.Commit()
  99. if err != nil {
  100. return common.ContextError(err)
  101. }
  102. untunneledDialConfig := &DialConfig{
  103. UpstreamProxyURL: config.UpstreamProxyURL,
  104. CustomHeaders: config.CustomHeaders,
  105. DeviceBinder: nil,
  106. IPv6Synthesizer: nil,
  107. DnsServerGetter: nil,
  108. UseIndistinguishableTLS: config.UseIndistinguishableTLS,
  109. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  110. DeviceRegion: config.DeviceRegion,
  111. }
  112. secureFeedback, err := encryptFeedback(diagnosticsJson, b64EncodedPublicKey)
  113. if err != nil {
  114. return err
  115. }
  116. randBytes, err := common.MakeSecureRandomBytes(8)
  117. if err != nil {
  118. return err
  119. }
  120. uploadId := hex.EncodeToString(randBytes)
  121. url := "https://" + uploadServer + uploadPath + uploadId
  122. headerPieces := strings.Split(uploadServerHeaders, ": ")
  123. // Only a single header is expected.
  124. if len(headerPieces) != 2 {
  125. return common.ContextError(errors.New("expected 2 header pieces, got: " + strconv.Itoa(len(headerPieces))))
  126. }
  127. for i := 0; i < FEEDBACK_UPLOAD_MAX_RETRIES; i++ {
  128. err = uploadFeedback(
  129. config,
  130. untunneledDialConfig,
  131. secureFeedback,
  132. url,
  133. MakePsiphonUserAgent(config),
  134. headerPieces)
  135. if err != nil {
  136. time.Sleep(FEEDBACK_UPLOAD_RETRY_DELAY_SECONDS * time.Second)
  137. } else {
  138. break
  139. }
  140. }
  141. return err
  142. }
  143. // Attempt to upload feedback data to server.
  144. func uploadFeedback(
  145. config *Config, dialConfig *DialConfig, feedbackData []byte, url, userAgent string, headerPieces []string) error {
  146. ctx, cancelFunc := context.WithTimeout(
  147. context.Background(),
  148. time.Duration(FEEDBACK_UPLOAD_TIMEOUT_SECONDS*time.Second))
  149. defer cancelFunc()
  150. client, err := MakeUntunneledHTTPClient(
  151. ctx,
  152. config,
  153. dialConfig,
  154. nil,
  155. false)
  156. if err != nil {
  157. return err
  158. }
  159. req, err := http.NewRequest("PUT", url, bytes.NewBuffer(feedbackData))
  160. if err != nil {
  161. return common.ContextError(err)
  162. }
  163. req.Header.Set("User-Agent", userAgent)
  164. req.Header.Set(headerPieces[0], headerPieces[1])
  165. resp, err := client.Do(req)
  166. if err != nil {
  167. return common.ContextError(err)
  168. }
  169. defer resp.Body.Close()
  170. if resp.StatusCode != http.StatusOK {
  171. return common.ContextError(errors.New("received HTTP status: " + resp.Status))
  172. }
  173. return nil
  174. }
  175. // Pad src to the next block boundary with PKCS7 padding
  176. // (https://tools.ietf.org/html/rfc5652#section-6.3).
  177. func addPKCS7Padding(src []byte, blockSize int) []byte {
  178. paddingLen := blockSize - (len(src) % blockSize)
  179. padding := bytes.Repeat([]byte{byte(paddingLen)}, paddingLen)
  180. return append(src, padding...)
  181. }
  182. // Encrypt plaintext with AES in CBC mode.
  183. func encryptAESCBC(plaintext []byte) ([]byte, []byte, []byte, error) {
  184. // CBC mode works on blocks so plaintexts need to be padded to the
  185. // next whole block (https://tools.ietf.org/html/rfc5246#section-6.2.3.2).
  186. plaintext = addPKCS7Padding(plaintext, aes.BlockSize)
  187. ciphertext := make([]byte, len(plaintext))
  188. iv, err := common.MakeSecureRandomBytes(aes.BlockSize)
  189. if err != nil {
  190. return nil, nil, nil, err
  191. }
  192. key, err := common.MakeSecureRandomBytes(aes.BlockSize)
  193. if err != nil {
  194. return nil, nil, nil, common.ContextError(err)
  195. }
  196. block, err := aes.NewCipher(key)
  197. if err != nil {
  198. return nil, nil, nil, common.ContextError(err)
  199. }
  200. mode := cipher.NewCBCEncrypter(block, iv)
  201. mode.CryptBlocks(ciphertext, plaintext)
  202. return iv, key, ciphertext, nil
  203. }
  204. // Encrypt plaintext with RSA public key.
  205. func encryptWithPublicKey(plaintext, publicKey []byte) ([]byte, error) {
  206. parsedKey, err := x509.ParsePKIXPublicKey(publicKey)
  207. if err != nil {
  208. return nil, common.ContextError(err)
  209. }
  210. if rsaPubKey, ok := parsedKey.(*rsa.PublicKey); ok {
  211. rsaEncryptOutput, err := rsa.EncryptOAEP(sha1.New(), rand.Reader, rsaPubKey, plaintext, nil)
  212. if err != nil {
  213. return nil, common.ContextError(err)
  214. }
  215. return rsaEncryptOutput, nil
  216. }
  217. return nil, common.ContextError(errors.New("feedback key is not an RSA public key"))
  218. }
  219. // Generate HMAC for Encrypt-then-MAC paradigm.
  220. func generateHMAC(iv, plaintext []byte) ([]byte, []byte, error) {
  221. key, err := common.MakeSecureRandomBytes(16)
  222. if err != nil {
  223. return nil, nil, err
  224. }
  225. mac := hmac.New(sha256.New, key)
  226. mac.Write(iv)
  227. mac.Write(plaintext)
  228. digest := mac.Sum(nil)
  229. return digest, key, nil
  230. }