feedback.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. utls "github.com/Psiphon-Labs/utls"
  44. )
  45. // Conforms to the format expected by the feedback decryptor.
  46. // https://bitbucket.org/psiphon/psiphon-circumvention-system/src/default/EmailResponder/FeedbackDecryptor/decryptor.py
  47. type secureFeedback struct {
  48. IV string `json:"iv"`
  49. ContentCipherText string `json:"contentCiphertext"`
  50. WrappedEncryptionKey string `json:"wrappedEncryptionKey"`
  51. ContentMac string `json:"contentMac"`
  52. WrappedMacKey string `json:"wrappedMacKey"`
  53. }
  54. // Encrypt and marshal feedback into secure json structure utilizing the
  55. // Encrypt-then-MAC paradigm (https://tools.ietf.org/html/rfc7366#section-3).
  56. func encryptFeedback(diagnostics, b64EncodedPublicKey string) ([]byte, error) {
  57. publicKey, err := base64.StdEncoding.DecodeString(b64EncodedPublicKey)
  58. if err != nil {
  59. return nil, errors.Trace(err)
  60. }
  61. iv, encryptionKey, diagnosticsCiphertext, err := encryptAESCBC([]byte(diagnostics))
  62. if err != nil {
  63. return nil, err
  64. }
  65. digest, macKey, err := generateHMAC(iv, diagnosticsCiphertext)
  66. if err != nil {
  67. return nil, err
  68. }
  69. wrappedMacKey, err := encryptWithPublicKey(macKey, publicKey)
  70. if err != nil {
  71. return nil, err
  72. }
  73. wrappedEncryptionKey, err := encryptWithPublicKey(encryptionKey, publicKey)
  74. if err != nil {
  75. return nil, err
  76. }
  77. var securedFeedback = secureFeedback{
  78. IV: base64.StdEncoding.EncodeToString(iv),
  79. ContentCipherText: base64.StdEncoding.EncodeToString(diagnosticsCiphertext),
  80. WrappedEncryptionKey: base64.StdEncoding.EncodeToString(wrappedEncryptionKey),
  81. ContentMac: base64.StdEncoding.EncodeToString(digest),
  82. WrappedMacKey: base64.StdEncoding.EncodeToString(wrappedMacKey),
  83. }
  84. encryptedFeedback, err := json.Marshal(securedFeedback)
  85. if err != nil {
  86. return nil, errors.Trace(err)
  87. }
  88. return encryptedFeedback, nil
  89. }
  90. // Encrypt feedback and upload to server. If upload fails
  91. // the routine will sleep and retry multiple times.
  92. func SendFeedback(ctx context.Context, config *Config, diagnostics, uploadPath string) error {
  93. if !config.EnableFeedbackUpload {
  94. return errors.TraceNew("feedback upload not enabled")
  95. }
  96. if len(diagnostics) == 0 {
  97. return errors.TraceNew("error diagnostics empty")
  98. }
  99. // Initialize a resolver to use for dials. useBindToDevice is false so
  100. // that the feedback upload will be tunneled, indirectly, if it routes
  101. // through the VPN.
  102. //
  103. // config.SetResolver makes this resolver available to MakeDialParameters
  104. // in GetTactics.
  105. resolver := NewResolver(config, false)
  106. defer resolver.Stop()
  107. config.SetResolver(resolver)
  108. // Limitation: GetTactics will fail silently if the datastore used for
  109. // retrieving and storing tactics is locked by another process. This can
  110. // be the case on Android and iOS where SendFeedback is invoked by the UI
  111. // process while tunneling is run by the VPN process.
  112. //
  113. // - When the Psiphon VPN is running, GetTactics won't load tactics.
  114. // However, tactics may be less critical since feedback will be
  115. // tunneled. This outcome also avoids fetching tactics while tunneled,
  116. // where otherwise the client GeoIP used for tactics would reflect the
  117. // tunnel egress point.
  118. //
  119. // - When the Psiphon VPN is not running, this will load tactics, and
  120. // potentially fetch tactics, with either the correct, untunneled GeoIP
  121. // or a network ID of "VPN" if some other non-Psiphon VPN is running
  122. // (the caller should ensure a network ID of "VPN" in this case).
  123. doTactics := !config.DisableTactics
  124. if doTactics {
  125. // Get tactics, may update client parameters
  126. p := config.GetParameters().Get()
  127. timeout := p.Duration(parameters.FeedbackTacticsWaitPeriod)
  128. p.Close()
  129. getTacticsCtx, cancelFunc := context.WithTimeout(ctx, timeout)
  130. GetTactics(getTacticsCtx, config, true)
  131. cancelFunc()
  132. }
  133. // Get the latest client parameters
  134. p := config.GetParameters().Get()
  135. feedbackUploadMinRetryDelay := p.Duration(parameters.FeedbackUploadRetryMinDelaySeconds)
  136. feedbackUploadMaxRetryDelay := p.Duration(parameters.FeedbackUploadRetryMaxDelaySeconds)
  137. feedbackUploadTimeout := p.Duration(parameters.FeedbackUploadTimeoutSeconds)
  138. feedbackUploadMaxAttempts := p.Int(parameters.FeedbackUploadMaxAttempts)
  139. transferURLs := p.TransferURLs(parameters.FeedbackUploadURLs)
  140. p.Close()
  141. // Initialize the feedback upload dial configuration. config.DeviceBinder
  142. // is not applied; see resolver comment above.
  143. untunneledDialConfig := &DialConfig{
  144. UpstreamProxyURL: config.UpstreamProxyURL,
  145. CustomHeaders: config.CustomHeaders,
  146. DeviceBinder: nil,
  147. IPv6Synthesizer: config.IPv6Synthesizer,
  148. ResolveIP: func(ctx context.Context, hostname string) ([]net.IP, error) {
  149. // Note: when domain fronting would be used for untunneled dials a
  150. // copy of untunneledDialConfig should be used instead, which
  151. // redefines ResolveIP such that the corresponding fronting
  152. // provider ID is passed into UntunneledResolveIP to enable the use
  153. // of pre-resolved IPs.
  154. // TODO: do not use pre-resolved IPs when tunneled.
  155. IPs, err := UntunneledResolveIP(
  156. ctx, config, resolver, hostname, "")
  157. if err != nil {
  158. return nil, errors.Trace(err)
  159. }
  160. return IPs, nil
  161. },
  162. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  163. }
  164. uploadId := prng.HexString(8)
  165. tlsCache := utls.NewLRUClientSessionCache(0)
  166. for i := 0; i < feedbackUploadMaxAttempts; i++ {
  167. uploadURL := transferURLs.Select(i)
  168. if uploadURL == nil {
  169. return errors.TraceNew("error no feedback upload URL selected")
  170. }
  171. b64PublicKey := uploadURL.B64EncodedPublicKey
  172. if b64PublicKey == "" {
  173. if config.FeedbackEncryptionPublicKey == "" {
  174. return errors.TraceNew("error no default encryption key")
  175. }
  176. b64PublicKey = config.FeedbackEncryptionPublicKey
  177. }
  178. secureFeedback, err := encryptFeedback(diagnostics, b64PublicKey)
  179. if err != nil {
  180. return errors.Trace(err)
  181. }
  182. feedbackUploadCtx, cancelFunc := context.WithTimeout(
  183. ctx,
  184. feedbackUploadTimeout)
  185. defer cancelFunc()
  186. var dialConfig *DialConfig
  187. if len(uploadURL.FrontingSpecs) == 0 {
  188. // Must only set DialConfig if there are no fronting specs.
  189. dialConfig = untunneledDialConfig
  190. }
  191. // Do not use device binder when domain fronting is used. See resolver
  192. // comment above.
  193. frontingUseDeviceBinder := false
  194. // Limitation: when SendFeedback is called without the datastore
  195. // already open, as is the case in MobileLibrary, for example, then
  196. // the following, optional frontedHTTPClientInstance replay use and
  197. // storage operations will always fail with "psiphon.datastoreUpdate#242:
  198. // database not open": SelectCandidateWithNetworkReplayParameters and
  199. // SetNetworkReplayParameters. Unlike GetTactics above, which uses
  200. // TacticsStorer and its transparent OpenDataStoreWithoutRetry calls,
  201. // the replay operations currently do not attempt to automatically
  202. // open and close the datastore.
  203. payloadSecure := true
  204. client, _, err := MakeUntunneledHTTPClient(
  205. feedbackUploadCtx,
  206. config,
  207. dialConfig,
  208. tlsCache,
  209. uploadURL.SkipVerify,
  210. config.DisableSystemRootCAs,
  211. payloadSecure,
  212. uploadURL.FrontingSpecs,
  213. frontingUseDeviceBinder,
  214. func(frontingProviderID string) {
  215. NoticeInfo(
  216. "SendFeedback: selected fronting provider %s for %s",
  217. frontingProviderID, uploadURL.URL)
  218. })
  219. if err != nil {
  220. return errors.Trace(err)
  221. }
  222. parsedURL, err := url.Parse(uploadURL.URL)
  223. if err != nil {
  224. return errors.TraceMsg(err, "failed to parse feedback upload URL")
  225. }
  226. parsedURL.Path = path.Join(parsedURL.Path, uploadPath, uploadId)
  227. request, err := http.NewRequestWithContext(feedbackUploadCtx, "PUT", parsedURL.String(), bytes.NewBuffer(secureFeedback))
  228. if err != nil {
  229. return errors.Trace(err)
  230. }
  231. for k, v := range uploadURL.RequestHeaders {
  232. request.Header.Set(k, v)
  233. }
  234. request.Header.Set("User-Agent", MakePsiphonUserAgent(config))
  235. err = uploadFeedback(client, request)
  236. cancelFunc()
  237. if err != nil {
  238. if ctx.Err() != nil {
  239. // Input context has completed
  240. return errors.TraceMsg(err,
  241. fmt.Sprintf("feedback upload attempt %d/%d cancelled", i+1, feedbackUploadMaxAttempts))
  242. }
  243. // Do not sleep after the last attempt
  244. if i+1 < feedbackUploadMaxAttempts {
  245. // Log error, sleep and then retry
  246. timeUntilRetry := prng.Period(feedbackUploadMinRetryDelay, feedbackUploadMaxRetryDelay)
  247. NoticeWarning(
  248. "feedback upload attempt %d/%d failed (retry in %.0fs): %s",
  249. i+1, feedbackUploadMaxAttempts, timeUntilRetry.Seconds(), errors.Trace(err))
  250. select {
  251. case <-ctx.Done():
  252. return errors.TraceNew(
  253. fmt.Sprintf("feedback upload attempt %d/%d cancelled before attempt",
  254. i+2, feedbackUploadMaxAttempts))
  255. case <-time.After(timeUntilRetry):
  256. }
  257. continue
  258. }
  259. return errors.TraceMsg(err,
  260. fmt.Sprintf("feedback upload failed after %d attempts", i+1))
  261. }
  262. return nil
  263. }
  264. return nil
  265. }
  266. // Attempt to upload feedback data to server.
  267. func uploadFeedback(
  268. client *http.Client, req *http.Request) error {
  269. resp, err := client.Do(req)
  270. if err != nil {
  271. return errors.Trace(err)
  272. }
  273. defer resp.Body.Close()
  274. if resp.StatusCode != http.StatusOK {
  275. return errors.TraceNew("unexpected HTTP status: " + resp.Status)
  276. }
  277. return nil
  278. }
  279. // Pad src to the next block boundary with PKCS7 padding
  280. // (https://tools.ietf.org/html/rfc5652#section-6.3).
  281. func addPKCS7Padding(src []byte, blockSize int) []byte {
  282. paddingLen := blockSize - (len(src) % blockSize)
  283. padding := bytes.Repeat([]byte{byte(paddingLen)}, paddingLen)
  284. return append(src, padding...)
  285. }
  286. // Encrypt plaintext with AES in CBC mode.
  287. func encryptAESCBC(plaintext []byte) ([]byte, []byte, []byte, error) {
  288. // CBC mode works on blocks so plaintexts need to be padded to the
  289. // next whole block (https://tools.ietf.org/html/rfc5246#section-6.2.3.2).
  290. plaintext = addPKCS7Padding(plaintext, aes.BlockSize)
  291. ciphertext := make([]byte, len(plaintext))
  292. iv, err := common.MakeSecureRandomBytes(aes.BlockSize)
  293. if err != nil {
  294. return nil, nil, nil, err
  295. }
  296. key, err := common.MakeSecureRandomBytes(aes.BlockSize)
  297. if err != nil {
  298. return nil, nil, nil, errors.Trace(err)
  299. }
  300. block, err := aes.NewCipher(key)
  301. if err != nil {
  302. return nil, nil, nil, errors.Trace(err)
  303. }
  304. mode := cipher.NewCBCEncrypter(block, iv)
  305. mode.CryptBlocks(ciphertext, plaintext)
  306. return iv, key, ciphertext, nil
  307. }
  308. // Encrypt plaintext with RSA public key.
  309. func encryptWithPublicKey(plaintext, publicKey []byte) ([]byte, error) {
  310. parsedKey, err := x509.ParsePKIXPublicKey(publicKey)
  311. if err != nil {
  312. return nil, errors.Trace(err)
  313. }
  314. if rsaPubKey, ok := parsedKey.(*rsa.PublicKey); ok {
  315. rsaEncryptOutput, err := rsa.EncryptOAEP(sha1.New(), rand.Reader, rsaPubKey, plaintext, nil)
  316. if err != nil {
  317. return nil, errors.Trace(err)
  318. }
  319. return rsaEncryptOutput, nil
  320. }
  321. return nil, errors.TraceNew("feedback key is not an RSA public key")
  322. }
  323. // Generate HMAC for Encrypt-then-MAC paradigm.
  324. func generateHMAC(iv, plaintext []byte) ([]byte, []byte, error) {
  325. key, err := common.MakeSecureRandomBytes(16)
  326. if err != nil {
  327. return nil, nil, err
  328. }
  329. mac := hmac.New(sha256.New, key)
  330. mac.Write(iv)
  331. mac.Write(plaintext)
  332. digest := mac.Sum(nil)
  333. return digest, key, nil
  334. }