feedback.go 12 KB

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