feedback.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. // Limitation: GetTactics will fail silently if the datastore used for
  111. // retrieving and storing tactics is opened by another process. This can
  112. // be the case on Android an iOS where SendFeedback is invoked by the UI
  113. // process while tunneling is run by the VPN process.
  114. //
  115. // - When the Psiphon VPN is running, GetTactics won't load tactics.
  116. // However, tactics may be less critical since feedback will be
  117. // tunneled. This outcome also avoids fetching tactics while tunneled,
  118. // where otherwise the client GeoIP used for tactics would reflect the
  119. // tunnel egress point.
  120. //
  121. // - When the Psiphon VPN is not running, this will load tactics, and
  122. // potentially fetch tactics, with either the correct, untunneled GeoIP
  123. // or a network ID of "VPN" if some other non-Psiphon VPN is running
  124. // (the caller should ensure a network ID of "VPN" in this case).
  125. GetTactics(getTacticsCtx, config)
  126. // Get the latest client parameters
  127. p = config.GetParameters().Get()
  128. feedbackUploadMinRetryDelay := p.Duration(parameters.FeedbackUploadRetryMinDelaySeconds)
  129. feedbackUploadMaxRetryDelay := p.Duration(parameters.FeedbackUploadRetryMaxDelaySeconds)
  130. feedbackUploadTimeout := p.Duration(parameters.FeedbackUploadTimeoutSeconds)
  131. feedbackUploadMaxAttempts := p.Int(parameters.FeedbackUploadMaxAttempts)
  132. transferURLs := p.TransferURLs(parameters.FeedbackUploadURLs)
  133. p.Close()
  134. // Initialize the feedback upload dial configuration. config.DeviceBinder
  135. // is not applied; see resolver comment above.
  136. untunneledDialConfig := &DialConfig{
  137. UpstreamProxyURL: config.UpstreamProxyURL,
  138. CustomHeaders: config.CustomHeaders,
  139. DeviceBinder: nil,
  140. IPv6Synthesizer: config.IPv6Synthesizer,
  141. ResolveIP: func(ctx context.Context, hostname string) ([]net.IP, error) {
  142. IPs, err := UntunneledResolveIP(
  143. ctx, config, resolver, hostname)
  144. if err != nil {
  145. return nil, errors.Trace(err)
  146. }
  147. return IPs, nil
  148. },
  149. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  150. }
  151. uploadId := prng.HexString(8)
  152. for i := 0; i < feedbackUploadMaxAttempts; i++ {
  153. uploadURL := transferURLs.Select(i)
  154. if uploadURL == nil {
  155. return errors.TraceNew("error no feedback upload URL selected")
  156. }
  157. b64PublicKey := uploadURL.B64EncodedPublicKey
  158. if b64PublicKey == "" {
  159. if config.FeedbackEncryptionPublicKey == "" {
  160. return errors.TraceNew("error no default encryption key")
  161. }
  162. b64PublicKey = config.FeedbackEncryptionPublicKey
  163. }
  164. secureFeedback, err := encryptFeedback(diagnostics, b64PublicKey)
  165. if err != nil {
  166. return errors.Trace(err)
  167. }
  168. feedbackUploadCtx, cancelFunc := context.WithTimeout(
  169. ctx,
  170. feedbackUploadTimeout)
  171. defer cancelFunc()
  172. client, err := MakeUntunneledHTTPClient(
  173. feedbackUploadCtx,
  174. config,
  175. untunneledDialConfig,
  176. uploadURL.SkipVerify || config.TransferURLsAlwaysSkipVerify)
  177. if err != nil {
  178. return errors.Trace(err)
  179. }
  180. parsedURL, err := url.Parse(uploadURL.URL)
  181. if err != nil {
  182. return errors.TraceMsg(err, "failed to parse feedback upload URL")
  183. }
  184. parsedURL.Path = path.Join(parsedURL.Path, uploadPath, uploadId)
  185. request, err := http.NewRequestWithContext(feedbackUploadCtx, "PUT", parsedURL.String(), bytes.NewBuffer(secureFeedback))
  186. if err != nil {
  187. return errors.Trace(err)
  188. }
  189. for k, v := range uploadURL.RequestHeaders {
  190. request.Header.Set(k, v)
  191. }
  192. request.Header.Set("User-Agent", MakePsiphonUserAgent(config))
  193. err = uploadFeedback(client, request)
  194. cancelFunc()
  195. if err != nil {
  196. if ctx.Err() != nil {
  197. // Input context has completed
  198. return errors.TraceMsg(err,
  199. fmt.Sprintf("feedback upload attempt %d/%d cancelled", i+1, feedbackUploadMaxAttempts))
  200. }
  201. // Do not sleep after the last attempt
  202. if i+1 < feedbackUploadMaxAttempts {
  203. // Log error, sleep and then retry
  204. timeUntilRetry := prng.Period(feedbackUploadMinRetryDelay, feedbackUploadMaxRetryDelay)
  205. NoticeWarning(
  206. "feedback upload attempt %d/%d failed (retry in %.0fs): %s",
  207. i+1, feedbackUploadMaxAttempts, timeUntilRetry.Seconds(), errors.Trace(err))
  208. select {
  209. case <-ctx.Done():
  210. return errors.TraceNew(
  211. fmt.Sprintf("feedback upload attempt %d/%d cancelled before attempt",
  212. i+2, feedbackUploadMaxAttempts))
  213. case <-time.After(timeUntilRetry):
  214. }
  215. continue
  216. }
  217. return errors.TraceMsg(err,
  218. fmt.Sprintf("feedback upload failed after %d attempts", i+1))
  219. }
  220. return nil
  221. }
  222. return nil
  223. }
  224. // Attempt to upload feedback data to server.
  225. func uploadFeedback(
  226. client *http.Client, req *http.Request) error {
  227. resp, err := client.Do(req)
  228. if err != nil {
  229. return errors.Trace(err)
  230. }
  231. defer resp.Body.Close()
  232. if resp.StatusCode != http.StatusOK {
  233. return errors.TraceNew("unexpected HTTP status: " + resp.Status)
  234. }
  235. return nil
  236. }
  237. // Pad src to the next block boundary with PKCS7 padding
  238. // (https://tools.ietf.org/html/rfc5652#section-6.3).
  239. func addPKCS7Padding(src []byte, blockSize int) []byte {
  240. paddingLen := blockSize - (len(src) % blockSize)
  241. padding := bytes.Repeat([]byte{byte(paddingLen)}, paddingLen)
  242. return append(src, padding...)
  243. }
  244. // Encrypt plaintext with AES in CBC mode.
  245. func encryptAESCBC(plaintext []byte) ([]byte, []byte, []byte, error) {
  246. // CBC mode works on blocks so plaintexts need to be padded to the
  247. // next whole block (https://tools.ietf.org/html/rfc5246#section-6.2.3.2).
  248. plaintext = addPKCS7Padding(plaintext, aes.BlockSize)
  249. ciphertext := make([]byte, len(plaintext))
  250. iv, err := common.MakeSecureRandomBytes(aes.BlockSize)
  251. if err != nil {
  252. return nil, nil, nil, err
  253. }
  254. key, err := common.MakeSecureRandomBytes(aes.BlockSize)
  255. if err != nil {
  256. return nil, nil, nil, errors.Trace(err)
  257. }
  258. block, err := aes.NewCipher(key)
  259. if err != nil {
  260. return nil, nil, nil, errors.Trace(err)
  261. }
  262. mode := cipher.NewCBCEncrypter(block, iv)
  263. mode.CryptBlocks(ciphertext, plaintext)
  264. return iv, key, ciphertext, nil
  265. }
  266. // Encrypt plaintext with RSA public key.
  267. func encryptWithPublicKey(plaintext, publicKey []byte) ([]byte, error) {
  268. parsedKey, err := x509.ParsePKIXPublicKey(publicKey)
  269. if err != nil {
  270. return nil, errors.Trace(err)
  271. }
  272. if rsaPubKey, ok := parsedKey.(*rsa.PublicKey); ok {
  273. rsaEncryptOutput, err := rsa.EncryptOAEP(sha1.New(), rand.Reader, rsaPubKey, plaintext, nil)
  274. if err != nil {
  275. return nil, errors.Trace(err)
  276. }
  277. return rsaEncryptOutput, nil
  278. }
  279. return nil, errors.TraceNew("feedback key is not an RSA public key")
  280. }
  281. // Generate HMAC for Encrypt-then-MAC paradigm.
  282. func generateHMAC(iv, plaintext []byte) ([]byte, []byte, error) {
  283. key, err := common.MakeSecureRandomBytes(16)
  284. if err != nil {
  285. return nil, nil, err
  286. }
  287. mac := hmac.New(sha256.New, key)
  288. mac.Write(iv)
  289. mac.Write(plaintext)
  290. digest := mac.Sum(nil)
  291. return digest, key, nil
  292. }