authPackage.go 15 KB

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