feedback.go 9.8 KB

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