feedback.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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, configJson, diagnosticsJson, uploadPath string) error {
  91. config, err := LoadConfig([]byte(configJson))
  92. if err != nil {
  93. return errors.Trace(err)
  94. }
  95. err = config.Commit(true)
  96. if err != nil {
  97. return errors.Trace(err)
  98. }
  99. // Get tactics, may update client parameters
  100. p := config.GetClientParameters().Get()
  101. timeout := p.Duration(parameters.FeedbackTacticsWaitPeriod)
  102. p.Close()
  103. getTacticsCtx, cancelFunc := context.WithTimeout(ctx, timeout)
  104. defer cancelFunc()
  105. // Note: GetTactics will fail silently if the datastore used for retrieving
  106. // and storing tactics is opened by another process.
  107. GetTactics(getTacticsCtx, config)
  108. // Get the latest client parameters
  109. p = config.GetClientParameters().Get()
  110. feedbackUploadMinRetryDelay := p.Duration(parameters.FeedbackUploadRetryMinDelaySeconds)
  111. feedbackUploadMaxRetryDelay := p.Duration(parameters.FeedbackUploadRetryMaxDelaySeconds)
  112. feedbackUploadTimeout := p.Duration(parameters.FeedbackUploadTimeoutSeconds)
  113. feedbackUploadMaxAttempts := p.Int(parameters.FeedbackUploadMaxAttempts)
  114. transferURLs := p.TransferURLs(parameters.FeedbackUploadURLs)
  115. p.Close()
  116. untunneledDialConfig := &DialConfig{
  117. UpstreamProxyURL: config.UpstreamProxyURL,
  118. CustomHeaders: config.CustomHeaders,
  119. DeviceBinder: nil,
  120. IPv6Synthesizer: nil,
  121. DnsServerGetter: nil,
  122. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  123. }
  124. uploadId := prng.HexString(8)
  125. for i := 0; i < feedbackUploadMaxAttempts; i++ {
  126. uploadURL := transferURLs.Select(i)
  127. if uploadURL == nil {
  128. return errors.TraceNew("error no feedback upload URL selected")
  129. }
  130. b64PublicKey := uploadURL.B64EncodedPublicKey
  131. if b64PublicKey == "" {
  132. if config.FeedbackEncryptionPublicKey == "" {
  133. return errors.TraceNew("error no default encryption key")
  134. }
  135. b64PublicKey = config.FeedbackEncryptionPublicKey
  136. }
  137. secureFeedback, err := encryptFeedback(diagnosticsJson, b64PublicKey)
  138. if err != nil {
  139. return errors.Trace(err)
  140. }
  141. feedbackUploadCtx, cancelFunc := context.WithTimeout(
  142. ctx,
  143. feedbackUploadTimeout)
  144. defer cancelFunc()
  145. client, err := MakeUntunneledHTTPClient(
  146. feedbackUploadCtx,
  147. config,
  148. untunneledDialConfig,
  149. nil,
  150. uploadURL.SkipVerify)
  151. if err != nil {
  152. return errors.Trace(err)
  153. }
  154. parsedURL, err := url.Parse(uploadURL.URL)
  155. if err != nil {
  156. return errors.TraceMsg(err, "failed to parse feedback upload URL")
  157. }
  158. parsedURL.Path = path.Join(parsedURL.Path, uploadPath, uploadId)
  159. request, err := http.NewRequestWithContext(feedbackUploadCtx, "PUT", parsedURL.String(), bytes.NewBuffer(secureFeedback))
  160. if err != nil {
  161. return errors.Trace(err)
  162. }
  163. for k, v := range uploadURL.RequestHeaders {
  164. request.Header.Set(k, v)
  165. }
  166. request.Header.Set("User-Agent", MakePsiphonUserAgent(config))
  167. err = uploadFeedback(client, request)
  168. cancelFunc()
  169. if err != nil {
  170. if ctx.Err() != nil {
  171. // Input context has completed
  172. return errors.TraceMsg(err,
  173. fmt.Sprintf("feedback upload attempt %d/%d cancelled", i+1, feedbackUploadMaxAttempts))
  174. }
  175. // Do not sleep after the last attempt
  176. if i+1 < feedbackUploadMaxAttempts {
  177. // Log error, sleep and then retry
  178. timeUntilRetry := prng.Period(feedbackUploadMinRetryDelay, feedbackUploadMaxRetryDelay)
  179. NoticeWarning(
  180. "feedback upload attempt %d/%d failed (retry in %.0fs): %s",
  181. i+1, feedbackUploadMaxAttempts, timeUntilRetry.Seconds(), errors.Trace(err))
  182. select {
  183. case <-ctx.Done():
  184. return errors.TraceNew(
  185. fmt.Sprintf("feedback upload attempt %d/%d cancelled before attempt",
  186. i+2, feedbackUploadMaxAttempts))
  187. case <-time.After(timeUntilRetry):
  188. }
  189. continue
  190. }
  191. return errors.TraceMsg(err,
  192. fmt.Sprintf("feedback upload failed after %d attempts", i+1))
  193. }
  194. return nil
  195. }
  196. return nil
  197. }
  198. // Attempt to upload feedback data to server.
  199. func uploadFeedback(
  200. client *http.Client, req *http.Request) error {
  201. resp, err := client.Do(req)
  202. if err != nil {
  203. return errors.Trace(err)
  204. }
  205. defer resp.Body.Close()
  206. if resp.StatusCode != http.StatusOK {
  207. return errors.TraceNew("unexpected HTTP status: " + resp.Status)
  208. }
  209. return nil
  210. }
  211. // Pad src to the next block boundary with PKCS7 padding
  212. // (https://tools.ietf.org/html/rfc5652#section-6.3).
  213. func addPKCS7Padding(src []byte, blockSize int) []byte {
  214. paddingLen := blockSize - (len(src) % blockSize)
  215. padding := bytes.Repeat([]byte{byte(paddingLen)}, paddingLen)
  216. return append(src, padding...)
  217. }
  218. // Encrypt plaintext with AES in CBC mode.
  219. func encryptAESCBC(plaintext []byte) ([]byte, []byte, []byte, error) {
  220. // CBC mode works on blocks so plaintexts need to be padded to the
  221. // next whole block (https://tools.ietf.org/html/rfc5246#section-6.2.3.2).
  222. plaintext = addPKCS7Padding(plaintext, aes.BlockSize)
  223. ciphertext := make([]byte, len(plaintext))
  224. iv, err := common.MakeSecureRandomBytes(aes.BlockSize)
  225. if err != nil {
  226. return nil, nil, nil, err
  227. }
  228. key, err := common.MakeSecureRandomBytes(aes.BlockSize)
  229. if err != nil {
  230. return nil, nil, nil, errors.Trace(err)
  231. }
  232. block, err := aes.NewCipher(key)
  233. if err != nil {
  234. return nil, nil, nil, errors.Trace(err)
  235. }
  236. mode := cipher.NewCBCEncrypter(block, iv)
  237. mode.CryptBlocks(ciphertext, plaintext)
  238. return iv, key, ciphertext, nil
  239. }
  240. // Encrypt plaintext with RSA public key.
  241. func encryptWithPublicKey(plaintext, publicKey []byte) ([]byte, error) {
  242. parsedKey, err := x509.ParsePKIXPublicKey(publicKey)
  243. if err != nil {
  244. return nil, errors.Trace(err)
  245. }
  246. if rsaPubKey, ok := parsedKey.(*rsa.PublicKey); ok {
  247. rsaEncryptOutput, err := rsa.EncryptOAEP(sha1.New(), rand.Reader, rsaPubKey, plaintext, nil)
  248. if err != nil {
  249. return nil, errors.Trace(err)
  250. }
  251. return rsaEncryptOutput, nil
  252. }
  253. return nil, errors.TraceNew("feedback key is not an RSA public key")
  254. }
  255. // Generate HMAC for Encrypt-then-MAC paradigm.
  256. func generateHMAC(iv, plaintext []byte) ([]byte, []byte, error) {
  257. key, err := common.MakeSecureRandomBytes(16)
  258. if err != nil {
  259. return nil, nil, err
  260. }
  261. mac := hmac.New(sha256.New, key)
  262. mac.Write(iv)
  263. mac.Write(plaintext)
  264. digest := mac.Sum(nil)
  265. return digest, key, nil
  266. }