authPackage.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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 common
  20. import (
  21. "bufio"
  22. "bytes"
  23. "compress/zlib"
  24. "crypto"
  25. "crypto/rand"
  26. "crypto/rsa"
  27. "crypto/sha256"
  28. "crypto/x509"
  29. "encoding/base64"
  30. "encoding/json"
  31. "io"
  32. "io/ioutil"
  33. "sync"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  35. )
  36. // AuthenticatedDataPackage is a JSON record containing some Psiphon data
  37. // payload, such as list of Psiphon server entries. As it may be downloaded
  38. // from various sources, it is digitally signed so that the data may be
  39. // authenticated.
  40. type AuthenticatedDataPackage struct {
  41. Data string `json:"data"`
  42. SigningPublicKeyDigest []byte `json:"signingPublicKeyDigest"`
  43. Signature []byte `json:"signature"`
  44. }
  45. // GenerateAuthenticatedDataPackageKeys generates a key pair
  46. // be used to sign and verify AuthenticatedDataPackages.
  47. func GenerateAuthenticatedDataPackageKeys() (string, string, error) {
  48. rsaKey, err := rsa.GenerateKey(rand.Reader, 4096)
  49. if err != nil {
  50. return "", "", errors.Trace(err)
  51. }
  52. publicKeyBytes, err := x509.MarshalPKIXPublicKey(rsaKey.Public())
  53. if err != nil {
  54. return "", "", errors.Trace(err)
  55. }
  56. privateKeyBytes := x509.MarshalPKCS1PrivateKey(rsaKey)
  57. return base64.StdEncoding.EncodeToString(publicKeyBytes),
  58. base64.StdEncoding.EncodeToString(privateKeyBytes),
  59. nil
  60. }
  61. func sha256sum(data string) []byte {
  62. digest := sha256.Sum256([]byte(data))
  63. return digest[:]
  64. }
  65. // WriteAuthenticatedDataPackage creates an AuthenticatedDataPackage
  66. // containing the specified data and signed by the given key. The output
  67. // conforms with the legacy format here:
  68. // https://bitbucket.org/psiphon/psiphon-circumvention-system/src/c25d080f6827b141fe637050ce0d5bd0ae2e9db5/Automation/psi_ops_crypto_tools.py
  69. func WriteAuthenticatedDataPackage(
  70. data string, signingPublicKey, signingPrivateKey string) ([]byte, error) {
  71. derEncodedPrivateKey, err := base64.StdEncoding.DecodeString(signingPrivateKey)
  72. if err != nil {
  73. return nil, errors.Trace(err)
  74. }
  75. rsaPrivateKey, err := x509.ParsePKCS1PrivateKey(derEncodedPrivateKey)
  76. if err != nil {
  77. return nil, errors.Trace(err)
  78. }
  79. signature, err := rsa.SignPKCS1v15(
  80. rand.Reader,
  81. rsaPrivateKey,
  82. crypto.SHA256,
  83. sha256sum(data))
  84. if err != nil {
  85. return nil, errors.Trace(err)
  86. }
  87. packageJSON, err := json.Marshal(
  88. &AuthenticatedDataPackage{
  89. Data: data,
  90. SigningPublicKeyDigest: sha256sum(signingPublicKey),
  91. Signature: signature,
  92. })
  93. if err != nil {
  94. return nil, errors.Trace(err)
  95. }
  96. compressedPackage, err := Compress(CompressionZlib, packageJSON)
  97. if err != nil {
  98. return nil, errors.Trace(err)
  99. }
  100. return compressedPackage, nil
  101. }
  102. // ReadAuthenticatedDataPackage extracts and verifies authenticated
  103. // data from an AuthenticatedDataPackage. The package must have been
  104. // signed with the given key.
  105. //
  106. // Set isCompressed to false to read packages that are not compressed.
  107. func ReadAuthenticatedDataPackage(
  108. dataPackage []byte, isCompressed bool, signingPublicKey string) (string, error) {
  109. var packageJSON []byte
  110. var err error
  111. if isCompressed {
  112. packageJSON, err = Decompress(CompressionZlib, dataPackage)
  113. if err != nil {
  114. return "", errors.Trace(err)
  115. }
  116. } else {
  117. packageJSON = dataPackage
  118. }
  119. var authenticatedDataPackage *AuthenticatedDataPackage
  120. err = json.Unmarshal(packageJSON, &authenticatedDataPackage)
  121. if err != nil {
  122. return "", errors.Trace(err)
  123. }
  124. derEncodedPublicKey, err := base64.StdEncoding.DecodeString(signingPublicKey)
  125. if err != nil {
  126. return "", errors.Trace(err)
  127. }
  128. publicKey, err := x509.ParsePKIXPublicKey(derEncodedPublicKey)
  129. if err != nil {
  130. return "", errors.Trace(err)
  131. }
  132. rsaPublicKey, ok := publicKey.(*rsa.PublicKey)
  133. if !ok {
  134. return "", errors.TraceNew("unexpected signing public key type")
  135. }
  136. if !bytes.Equal(
  137. authenticatedDataPackage.SigningPublicKeyDigest,
  138. sha256sum(signingPublicKey)) {
  139. return "", errors.TraceNew("unexpected signing public key digest")
  140. }
  141. err = rsa.VerifyPKCS1v15(
  142. rsaPublicKey,
  143. crypto.SHA256,
  144. sha256sum(authenticatedDataPackage.Data),
  145. authenticatedDataPackage.Signature)
  146. if err != nil {
  147. return "", errors.Trace(err)
  148. }
  149. return authenticatedDataPackage.Data, nil
  150. }
  151. // NewAuthenticatedDataPackageReader extracts and verifies authenticated
  152. // data from an AuthenticatedDataPackage stored in the specified file. The
  153. // package must have been signed with the given key.
  154. // NewAuthenticatedDataPackageReader does not load the entire package nor
  155. // the entire data into memory. It streams the package while verifying, and
  156. // returns an io.Reader that the caller may use to stream the authenticated
  157. // data payload.
  158. func NewAuthenticatedDataPackageReader(
  159. dataPackage io.ReadSeeker, signingPublicKey string) (io.Reader, error) {
  160. // The file is streamed in 2 passes. The first pass verifies the package
  161. // signature. No payload data should be accepted/processed until the signature
  162. // check is complete. The second pass repositions to the data payload and returns
  163. // a reader the caller will use to stream the authenticated payload.
  164. //
  165. // Note: No exclusive file lock is held between passes, so it's possible to
  166. // verify the data in one pass, and read different data in the second pass.
  167. // For Psiphon's use cases, this will not happen in practise -- the packageFileName
  168. // will not change while the returned io.Reader is used -- unless the client host
  169. // is compromised; a compromised client host is outside of our threat model.
  170. var payload io.Reader
  171. for pass := 0; pass < 2; pass++ {
  172. _, err := dataPackage.Seek(0, io.SeekStart)
  173. if err != nil {
  174. return nil, errors.Trace(err)
  175. }
  176. decompressor, err := zlib.NewReader(dataPackage)
  177. if err != nil {
  178. return nil, errors.Trace(err)
  179. }
  180. defer decompressor.Close()
  181. // TODO: need to check Close error to ensure zlib checksum is verified?
  182. hash := sha256.New()
  183. var jsonData io.Reader
  184. var jsonSigningPublicKey []byte
  185. var jsonSignature []byte
  186. jsonReadBase64Value := func(value io.Reader) ([]byte, error) {
  187. base64Value, err := ioutil.ReadAll(value)
  188. if err != nil {
  189. return nil, errors.Trace(err)
  190. }
  191. decodedValue, err := base64.StdEncoding.DecodeString(string(base64Value))
  192. if err != nil {
  193. return nil, errors.Trace(err)
  194. }
  195. return decodedValue, nil
  196. }
  197. jsonHandler := func(key string, value io.Reader) (bool, error) {
  198. switch key {
  199. case "data":
  200. if pass == 0 {
  201. _, err := io.Copy(hash, value)
  202. if err != nil {
  203. return false, errors.Trace(err)
  204. }
  205. return true, nil
  206. } else { // pass == 1
  207. jsonData = value
  208. // The JSON stream parser must halt at this position,
  209. // leaving the reader to be returned to the caller positioned
  210. // at the start of the data payload.
  211. return false, nil
  212. }
  213. case "signingPublicKeyDigest":
  214. jsonSigningPublicKey, err = jsonReadBase64Value(value)
  215. if err != nil {
  216. return false, errors.Trace(err)
  217. }
  218. return true, nil
  219. case "signature":
  220. jsonSignature, err = jsonReadBase64Value(value)
  221. if err != nil {
  222. return false, errors.Trace(err)
  223. }
  224. return true, nil
  225. }
  226. return false, errors.Tracef("unexpected key '%s'", key)
  227. }
  228. // Using a buffered reader to consume zlib output in batches
  229. // yields a significant speed up in the BenchmarkAuthenticatedPackage.
  230. jsonStreamer := &limitedJSONStreamer{
  231. reader: bufio.NewReader(decompressor),
  232. handler: jsonHandler,
  233. }
  234. err = jsonStreamer.Stream()
  235. if err != nil {
  236. return nil, errors.Trace(err)
  237. }
  238. if pass == 0 {
  239. if jsonSigningPublicKey == nil || jsonSignature == nil {
  240. return nil, errors.TraceNew("missing expected field")
  241. }
  242. derEncodedPublicKey, err := base64.StdEncoding.DecodeString(signingPublicKey)
  243. if err != nil {
  244. return nil, errors.Trace(err)
  245. }
  246. publicKey, err := x509.ParsePKIXPublicKey(derEncodedPublicKey)
  247. if err != nil {
  248. return nil, errors.Trace(err)
  249. }
  250. rsaPublicKey, ok := publicKey.(*rsa.PublicKey)
  251. if !ok {
  252. return nil, errors.TraceNew("unexpected signing public key type")
  253. }
  254. if !bytes.Equal(jsonSigningPublicKey, sha256sum(signingPublicKey)) {
  255. return nil, errors.TraceNew("unexpected signing public key digest")
  256. }
  257. err = rsa.VerifyPKCS1v15(
  258. rsaPublicKey,
  259. crypto.SHA256,
  260. hash.Sum(nil),
  261. jsonSignature)
  262. if err != nil {
  263. return nil, errors.Trace(err)
  264. }
  265. } else { // pass == 1
  266. if jsonData == nil {
  267. return nil, errors.TraceNew("missing expected field")
  268. }
  269. payload = jsonData
  270. }
  271. }
  272. return payload, nil
  273. }
  274. // limitedJSONStreamer is a streaming JSON parser that supports just the
  275. // JSON required for the AuthenticatedDataPackage format and expected data payloads.
  276. //
  277. // Unlike other common streaming JSON parsers, limitedJSONStreamer streams the JSON
  278. // _values_, as the AuthenticatedDataPackage "data" value may be too large to fit into
  279. // memory.
  280. //
  281. // limitedJSONStreamer is not intended for use outside of AuthenticatedDataPackage
  282. // and supports only a small subset of JSON: one object with string values only,
  283. // no escaped characters, no nested objects, no arrays, no numbers, etc.
  284. //
  285. // limitedJSONStreamer does support any JSON spec (http://www.json.org/) format
  286. // for its limited subset. So, for example, any whitespace/formatting should be
  287. // supported and the creator of AuthenticatedDataPackage should be able to use
  288. // any valid JSON that results in a AuthenticatedDataPackage object.
  289. //
  290. // For each key/value pair, handler is invoked with the key name and a reader
  291. // to stream the value. The handler _must_ read value to EOF (or return an error).
  292. type limitedJSONStreamer struct {
  293. reader io.Reader
  294. handler func(key string, value io.Reader) (bool, error)
  295. }
  296. const (
  297. stateJSONSeekingObjectStart = iota
  298. stateJSONSeekingKeyStart
  299. stateJSONSeekingKeyEnd
  300. stateJSONSeekingColon
  301. stateJSONSeekingStringValueStart
  302. stateJSONSeekingStringValueEnd
  303. stateJSONSeekingNextPair
  304. stateJSONObjectEnd
  305. )
  306. func (streamer *limitedJSONStreamer) Stream() error {
  307. // TODO: validate that strings are valid Unicode?
  308. isWhitespace := func(b byte) bool {
  309. return b == ' ' || b == '\t' || b == '\r' || b == '\n'
  310. }
  311. nextByte := make([]byte, 1)
  312. keyBuffer := new(bytes.Buffer)
  313. state := stateJSONSeekingObjectStart
  314. for {
  315. n, readErr := streamer.reader.Read(nextByte)
  316. if n > 0 {
  317. b := nextByte[0]
  318. switch state {
  319. case stateJSONSeekingObjectStart:
  320. if b == '{' {
  321. state = stateJSONSeekingKeyStart
  322. } else if !isWhitespace(b) {
  323. return errors.Tracef("unexpected character %#U while seeking object start", b)
  324. }
  325. case stateJSONSeekingKeyStart:
  326. if b == '"' {
  327. state = stateJSONSeekingKeyEnd
  328. keyBuffer.Reset()
  329. } else if !isWhitespace(b) {
  330. return errors.Tracef("unexpected character %#U while seeking key start", b)
  331. }
  332. case stateJSONSeekingKeyEnd:
  333. if b == '\\' {
  334. return errors.TraceNew("unsupported escaped character")
  335. } else if b == '"' {
  336. state = stateJSONSeekingColon
  337. } else {
  338. keyBuffer.WriteByte(b)
  339. }
  340. case stateJSONSeekingColon:
  341. if b == ':' {
  342. state = stateJSONSeekingStringValueStart
  343. } else if !isWhitespace(b) {
  344. return errors.Tracef("unexpected character %#U while seeking colon", b)
  345. }
  346. case stateJSONSeekingStringValueStart:
  347. if b == '"' {
  348. // Note: this assignment is flagged by github.com/gordonklaus/ineffassign,
  349. // but is technically the correct state.
  350. //
  351. //state = stateJSONSeekingStringValueEnd
  352. key := keyBuffer.String()
  353. // Wrap the main reader in a reader that will read up to the end
  354. // of the value and then EOF. The handler is expected to consume
  355. // the full value, and then stream parsing will resume after the
  356. // end of the value.
  357. valueStreamer := &limitedJSONValueStreamer{
  358. reader: streamer.reader,
  359. }
  360. continueStreaming, err := streamer.handler(key, valueStreamer)
  361. if err != nil {
  362. return errors.Trace(err)
  363. }
  364. // The handler may request that streaming halt at this point; no
  365. // further changes are made to streamer.reader, leaving the value
  366. // exactly where the hander leaves it.
  367. if !continueStreaming {
  368. return nil
  369. }
  370. state = stateJSONSeekingNextPair
  371. } else if !isWhitespace(b) {
  372. return errors.Tracef("unexpected character %#U while seeking value start", b)
  373. }
  374. case stateJSONSeekingNextPair:
  375. if b == ',' {
  376. state = stateJSONSeekingKeyStart
  377. } else if b == '}' {
  378. state = stateJSONObjectEnd
  379. } else if !isWhitespace(b) {
  380. return errors.Tracef("unexpected character %#U while seeking next name/value pair", b)
  381. }
  382. case stateJSONObjectEnd:
  383. if !isWhitespace(b) {
  384. return errors.Tracef("unexpected character %#U after object end", b)
  385. }
  386. default:
  387. return errors.TraceNew("unexpected state")
  388. }
  389. }
  390. if readErr != nil {
  391. if readErr == io.EOF {
  392. if state != stateJSONObjectEnd {
  393. return errors.TraceNew("unexpected EOF before object end")
  394. }
  395. return nil
  396. }
  397. return errors.Trace(readErr)
  398. }
  399. }
  400. }
  401. // limitedJSONValueStreamer wraps the limitedJSONStreamer reader
  402. // with a reader that reads to the end of a string value and then
  403. // terminates with EOF.
  404. type limitedJSONValueStreamer struct {
  405. mutex sync.Mutex
  406. eof bool
  407. reader io.Reader
  408. }
  409. // Read implements the io.Reader interface.
  410. func (streamer *limitedJSONValueStreamer) Read(p []byte) (int, error) {
  411. streamer.mutex.Lock()
  412. defer streamer.mutex.Unlock()
  413. if streamer.eof {
  414. return 0, io.EOF
  415. }
  416. var i int
  417. var err error
  418. for i = 0; i < len(p); i++ {
  419. var n int
  420. n, err = streamer.reader.Read(p[i : i+1])
  421. // process n == 1 before handling err, in case err is io.EOF
  422. if n == 1 {
  423. if p[i] == '"' {
  424. streamer.eof = true
  425. err = io.EOF
  426. } else if p[i] == '\\' {
  427. if err == nil {
  428. // Psiphon server list string values contain '\n', so support
  429. // that required case.
  430. n, err = streamer.reader.Read(p[i : i+1])
  431. if n == 1 && p[i] == 'n' {
  432. p[i] = '\n'
  433. } else {
  434. err = errors.TraceNew("unsupported escaped character")
  435. }
  436. }
  437. }
  438. }
  439. if err != nil {
  440. break
  441. }
  442. }
  443. return i, err
  444. }