feedback.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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/json"
  33. "fmt"
  34. "net/http"
  35. "net/url"
  36. "path"
  37. "time"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  42. )
  43. // Conforms to the format expected by the feedback decryptor.
  44. // https://bitbucket.org/psiphon/psiphon-circumvention-system/src/default/EmailResponder/FeedbackDecryptor/decryptor.py
  45. type secureFeedback struct {
  46. IV string `json:"iv"`
  47. ContentCipherText string `json:"contentCiphertext"`
  48. WrappedEncryptionKey string `json:"wrappedEncryptionKey"`
  49. ContentMac string `json:"contentMac"`
  50. WrappedMacKey string `json:"wrappedMacKey"`
  51. }
  52. // Encrypt and marshal feedback into secure json structure utilizing the
  53. // Encrypt-then-MAC paradigm (https://tools.ietf.org/html/rfc7366#section-3).
  54. func encryptFeedback(diagnosticsJson, b64EncodedPublicKey string) ([]byte, error) {
  55. publicKey, err := base64.StdEncoding.DecodeString(b64EncodedPublicKey)
  56. if err != nil {
  57. return nil, errors.Trace(err)
  58. }
  59. iv, encryptionKey, diagnosticsCiphertext, err := encryptAESCBC([]byte(diagnosticsJson))
  60. if err != nil {
  61. return nil, err
  62. }
  63. digest, macKey, err := generateHMAC(iv, diagnosticsCiphertext)
  64. if err != nil {
  65. return nil, err
  66. }
  67. wrappedMacKey, err := encryptWithPublicKey(macKey, publicKey)
  68. if err != nil {
  69. return nil, err
  70. }
  71. wrappedEncryptionKey, err := encryptWithPublicKey(encryptionKey, publicKey)
  72. if err != nil {
  73. return nil, err
  74. }
  75. var securedFeedback = secureFeedback{
  76. IV: base64.StdEncoding.EncodeToString(iv),
  77. ContentCipherText: base64.StdEncoding.EncodeToString(diagnosticsCiphertext),
  78. WrappedEncryptionKey: base64.StdEncoding.EncodeToString(wrappedEncryptionKey),
  79. ContentMac: base64.StdEncoding.EncodeToString(digest),
  80. WrappedMacKey: base64.StdEncoding.EncodeToString(wrappedMacKey),
  81. }
  82. encryptedFeedback, err := json.Marshal(securedFeedback)
  83. if err != nil {
  84. return nil, errors.Trace(err)
  85. }
  86. return encryptedFeedback, nil
  87. }
  88. // Encrypt feedback and upload to server. If upload fails
  89. // the routine will sleep and retry multiple times.
  90. func SendFeedback(ctx context.Context, config *Config, diagnosticsJson, uploadPath string) error {
  91. // Get tactics, may update client parameters
  92. p := config.GetParameters().Get()
  93. timeout := p.Duration(parameters.FeedbackTacticsWaitPeriod)
  94. p.Close()
  95. getTacticsCtx, cancelFunc := context.WithTimeout(ctx, timeout)
  96. defer cancelFunc()
  97. // Note: GetTactics will fail silently if the datastore used for retrieving
  98. // and storing tactics is opened by another process.
  99. GetTactics(getTacticsCtx, config)
  100. // Get the latest client parameters
  101. p = config.GetParameters().Get()
  102. feedbackUploadMinRetryDelay := p.Duration(parameters.FeedbackUploadRetryMinDelaySeconds)
  103. feedbackUploadMaxRetryDelay := p.Duration(parameters.FeedbackUploadRetryMaxDelaySeconds)
  104. feedbackUploadTimeout := p.Duration(parameters.FeedbackUploadTimeoutSeconds)
  105. feedbackUploadMaxAttempts := p.Int(parameters.FeedbackUploadMaxAttempts)
  106. transferURLs := p.TransferURLs(parameters.FeedbackUploadURLs)
  107. p.Close()
  108. untunneledDialConfig := &DialConfig{
  109. UpstreamProxyURL: config.UpstreamProxyURL,
  110. CustomHeaders: config.CustomHeaders,
  111. DeviceBinder: nil,
  112. IPv6Synthesizer: nil,
  113. DnsServerGetter: nil,
  114. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  115. }
  116. uploadId := prng.HexString(8)
  117. for i := 0; i < feedbackUploadMaxAttempts; i++ {
  118. uploadURL := transferURLs.Select(i)
  119. if uploadURL == nil {
  120. return errors.TraceNew("error no feedback upload URL selected")
  121. }
  122. b64PublicKey := uploadURL.B64EncodedPublicKey
  123. if b64PublicKey == "" {
  124. if config.FeedbackEncryptionPublicKey == "" {
  125. return errors.TraceNew("error no default encryption key")
  126. }
  127. b64PublicKey = config.FeedbackEncryptionPublicKey
  128. }
  129. secureFeedback, err := encryptFeedback(diagnosticsJson, b64PublicKey)
  130. if err != nil {
  131. return errors.Trace(err)
  132. }
  133. feedbackUploadCtx, cancelFunc := context.WithTimeout(
  134. ctx,
  135. feedbackUploadTimeout)
  136. defer cancelFunc()
  137. client, err := MakeUntunneledHTTPClient(
  138. feedbackUploadCtx,
  139. config,
  140. untunneledDialConfig,
  141. nil,
  142. uploadURL.SkipVerify)
  143. if err != nil {
  144. return errors.Trace(err)
  145. }
  146. parsedURL, err := url.Parse(uploadURL.URL)
  147. if err != nil {
  148. return errors.TraceMsg(err, "failed to parse feedback upload URL")
  149. }
  150. parsedURL.Path = path.Join(parsedURL.Path, uploadPath, uploadId)
  151. request, err := http.NewRequestWithContext(feedbackUploadCtx, "PUT", parsedURL.String(), bytes.NewBuffer(secureFeedback))
  152. if err != nil {
  153. return errors.Trace(err)
  154. }
  155. for k, v := range uploadURL.RequestHeaders {
  156. request.Header.Set(k, v)
  157. }
  158. request.Header.Set("User-Agent", MakePsiphonUserAgent(config))
  159. err = uploadFeedback(client, request)
  160. cancelFunc()
  161. if err != nil {
  162. if ctx.Err() != nil {
  163. // Input context has completed
  164. return errors.TraceMsg(err,
  165. fmt.Sprintf("feedback upload attempt %d/%d cancelled", i+1, feedbackUploadMaxAttempts))
  166. }
  167. // Do not sleep after the last attempt
  168. if i+1 < feedbackUploadMaxAttempts {
  169. // Log error, sleep and then retry
  170. timeUntilRetry := prng.Period(feedbackUploadMinRetryDelay, feedbackUploadMaxRetryDelay)
  171. NoticeWarning(
  172. "feedback upload attempt %d/%d failed (retry in %.0fs): %s",
  173. i+1, feedbackUploadMaxAttempts, timeUntilRetry.Seconds(), errors.Trace(err))
  174. select {
  175. case <-ctx.Done():
  176. return errors.TraceNew(
  177. fmt.Sprintf("feedback upload attempt %d/%d cancelled before attempt",
  178. i+2, feedbackUploadMaxAttempts))
  179. case <-time.After(timeUntilRetry):
  180. }
  181. continue
  182. }
  183. return errors.TraceMsg(err,
  184. fmt.Sprintf("feedback upload failed after %d attempts", i+1))
  185. }
  186. return nil
  187. }
  188. return nil
  189. }
  190. // Attempt to upload feedback data to server.
  191. func uploadFeedback(
  192. client *http.Client, req *http.Request) error {
  193. resp, err := client.Do(req)
  194. if err != nil {
  195. return errors.Trace(err)
  196. }
  197. defer resp.Body.Close()
  198. if resp.StatusCode != http.StatusOK {
  199. return errors.TraceNew("unexpected HTTP status: " + resp.Status)
  200. }
  201. return nil
  202. }
  203. // Pad src to the next block boundary with PKCS7 padding
  204. // (https://tools.ietf.org/html/rfc5652#section-6.3).
  205. func addPKCS7Padding(src []byte, blockSize int) []byte {
  206. paddingLen := blockSize - (len(src) % blockSize)
  207. padding := bytes.Repeat([]byte{byte(paddingLen)}, paddingLen)
  208. return append(src, padding...)
  209. }
  210. // Encrypt plaintext with AES in CBC mode.
  211. func encryptAESCBC(plaintext []byte) ([]byte, []byte, []byte, error) {
  212. // CBC mode works on blocks so plaintexts need to be padded to the
  213. // next whole block (https://tools.ietf.org/html/rfc5246#section-6.2.3.2).
  214. plaintext = addPKCS7Padding(plaintext, aes.BlockSize)
  215. ciphertext := make([]byte, len(plaintext))
  216. iv, err := common.MakeSecureRandomBytes(aes.BlockSize)
  217. if err != nil {
  218. return nil, nil, nil, err
  219. }
  220. key, err := common.MakeSecureRandomBytes(aes.BlockSize)
  221. if err != nil {
  222. return nil, nil, nil, errors.Trace(err)
  223. }
  224. block, err := aes.NewCipher(key)
  225. if err != nil {
  226. return nil, nil, nil, errors.Trace(err)
  227. }
  228. mode := cipher.NewCBCEncrypter(block, iv)
  229. mode.CryptBlocks(ciphertext, plaintext)
  230. return iv, key, ciphertext, nil
  231. }
  232. // Encrypt plaintext with RSA public key.
  233. func encryptWithPublicKey(plaintext, publicKey []byte) ([]byte, error) {
  234. parsedKey, err := x509.ParsePKIXPublicKey(publicKey)
  235. if err != nil {
  236. return nil, errors.Trace(err)
  237. }
  238. if rsaPubKey, ok := parsedKey.(*rsa.PublicKey); ok {
  239. rsaEncryptOutput, err := rsa.EncryptOAEP(sha1.New(), rand.Reader, rsaPubKey, plaintext, nil)
  240. if err != nil {
  241. return nil, errors.Trace(err)
  242. }
  243. return rsaEncryptOutput, nil
  244. }
  245. return nil, errors.TraceNew("feedback key is not an RSA public key")
  246. }
  247. // Generate HMAC for Encrypt-then-MAC paradigm.
  248. func generateHMAC(iv, plaintext []byte) ([]byte, []byte, error) {
  249. key, err := common.MakeSecureRandomBytes(16)
  250. if err != nil {
  251. return nil, nil, err
  252. }
  253. mac := hmac.New(sha256.New, key)
  254. mac.Write(iv)
  255. mac.Write(plaintext)
  256. digest := mac.Sum(nil)
  257. return digest, key, nil
  258. }