authPackage.go 14 KB

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