authPackage.go 14 KB

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