package.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * Copyright (c) 2015, 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 psiphon
  20. import (
  21. "crypto"
  22. "crypto/rsa"
  23. "crypto/sha256"
  24. "crypto/x509"
  25. "encoding/base64"
  26. "encoding/json"
  27. "errors"
  28. )
  29. // AuthenticatedDataPackage is a JSON record containing some Psiphon data
  30. // payload, such as list of Psiphon server entries. As it may be downloaded
  31. // from various sources, it is digitally signed so that the data may be
  32. // authenticated.
  33. type AuthenticatedDataPackage struct {
  34. Data string `json:"data"`
  35. SigningPublicKeyDigest string `json:"signingPublicKeyDigest"`
  36. Signature string `json:"signature"`
  37. }
  38. func ReadAuthenticatedDataPackage(
  39. rawPackage []byte, signingPublicKey string) (data string, err error) {
  40. var authenticatedDataPackage *AuthenticatedDataPackage
  41. err = json.Unmarshal(rawPackage, &authenticatedDataPackage)
  42. if err != nil {
  43. return "", ContextError(err)
  44. }
  45. derEncodedPublicKey, err := base64.StdEncoding.DecodeString(signingPublicKey)
  46. if err != nil {
  47. return "", ContextError(err)
  48. }
  49. publicKey, err := x509.ParsePKIXPublicKey(derEncodedPublicKey)
  50. if err != nil {
  51. return "", ContextError(err)
  52. }
  53. rsaPublicKey, ok := publicKey.(*rsa.PublicKey)
  54. if !ok {
  55. return "", ContextError(errors.New("unexpected signing public key type"))
  56. }
  57. signature, err := base64.StdEncoding.DecodeString(authenticatedDataPackage.Signature)
  58. if err != nil {
  59. return "", ContextError(err)
  60. }
  61. // TODO: can distinguish signed-with-different-key from other errors:
  62. // match digest(publicKey) against authenticatedDataPackage.SigningPublicKeyDigest
  63. hash := sha256.New()
  64. hash.Write([]byte(authenticatedDataPackage.Data))
  65. digest := hash.Sum(nil)
  66. err = rsa.VerifyPKCS1v15(rsaPublicKey, crypto.SHA256, digest, signature)
  67. if err != nil {
  68. return "", ContextError(err)
  69. }
  70. return authenticatedDataPackage.Data, nil
  71. }