feedback.go 7.3 KB

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