feedback.go 11 KB

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