authPackage.go 15 KB

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