feedback.go 9.1 KB

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