shared.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. /*-
  2. * Copyright 2014 Square Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package jose
  17. import (
  18. "crypto/elliptic"
  19. "crypto/x509"
  20. "encoding/base64"
  21. "errors"
  22. "fmt"
  23. "gopkg.in/square/go-jose.v2/json"
  24. )
  25. // KeyAlgorithm represents a key management algorithm.
  26. type KeyAlgorithm string
  27. // SignatureAlgorithm represents a signature (or MAC) algorithm.
  28. type SignatureAlgorithm string
  29. // ContentEncryption represents a content encryption algorithm.
  30. type ContentEncryption string
  31. // CompressionAlgorithm represents an algorithm used for plaintext compression.
  32. type CompressionAlgorithm string
  33. // ContentType represents type of the contained data.
  34. type ContentType string
  35. var (
  36. // ErrCryptoFailure represents an error in cryptographic primitive. This
  37. // occurs when, for example, a message had an invalid authentication tag or
  38. // could not be decrypted.
  39. ErrCryptoFailure = errors.New("square/go-jose: error in cryptographic primitive")
  40. // ErrUnsupportedAlgorithm indicates that a selected algorithm is not
  41. // supported. This occurs when trying to instantiate an encrypter for an
  42. // algorithm that is not yet implemented.
  43. ErrUnsupportedAlgorithm = errors.New("square/go-jose: unknown/unsupported algorithm")
  44. // ErrUnsupportedKeyType indicates that the given key type/format is not
  45. // supported. This occurs when trying to instantiate an encrypter and passing
  46. // it a key of an unrecognized type or with unsupported parameters, such as
  47. // an RSA private key with more than two primes.
  48. ErrUnsupportedKeyType = errors.New("square/go-jose: unsupported key type/format")
  49. // ErrNotSupported serialization of object is not supported. This occurs when
  50. // trying to compact-serialize an object which can't be represented in
  51. // compact form.
  52. ErrNotSupported = errors.New("square/go-jose: compact serialization not supported for object")
  53. // ErrUnprotectedNonce indicates that while parsing a JWS or JWE object, a
  54. // nonce header parameter was included in an unprotected header object.
  55. ErrUnprotectedNonce = errors.New("square/go-jose: Nonce parameter included in unprotected header")
  56. )
  57. // Key management algorithms
  58. const (
  59. ED25519 = KeyAlgorithm("ED25519")
  60. RSA1_5 = KeyAlgorithm("RSA1_5") // RSA-PKCS1v1.5
  61. RSA_OAEP = KeyAlgorithm("RSA-OAEP") // RSA-OAEP-SHA1
  62. RSA_OAEP_256 = KeyAlgorithm("RSA-OAEP-256") // RSA-OAEP-SHA256
  63. A128KW = KeyAlgorithm("A128KW") // AES key wrap (128)
  64. A192KW = KeyAlgorithm("A192KW") // AES key wrap (192)
  65. A256KW = KeyAlgorithm("A256KW") // AES key wrap (256)
  66. DIRECT = KeyAlgorithm("dir") // Direct encryption
  67. ECDH_ES = KeyAlgorithm("ECDH-ES") // ECDH-ES
  68. ECDH_ES_A128KW = KeyAlgorithm("ECDH-ES+A128KW") // ECDH-ES + AES key wrap (128)
  69. ECDH_ES_A192KW = KeyAlgorithm("ECDH-ES+A192KW") // ECDH-ES + AES key wrap (192)
  70. ECDH_ES_A256KW = KeyAlgorithm("ECDH-ES+A256KW") // ECDH-ES + AES key wrap (256)
  71. A128GCMKW = KeyAlgorithm("A128GCMKW") // AES-GCM key wrap (128)
  72. A192GCMKW = KeyAlgorithm("A192GCMKW") // AES-GCM key wrap (192)
  73. A256GCMKW = KeyAlgorithm("A256GCMKW") // AES-GCM key wrap (256)
  74. PBES2_HS256_A128KW = KeyAlgorithm("PBES2-HS256+A128KW") // PBES2 + HMAC-SHA256 + AES key wrap (128)
  75. PBES2_HS384_A192KW = KeyAlgorithm("PBES2-HS384+A192KW") // PBES2 + HMAC-SHA384 + AES key wrap (192)
  76. PBES2_HS512_A256KW = KeyAlgorithm("PBES2-HS512+A256KW") // PBES2 + HMAC-SHA512 + AES key wrap (256)
  77. )
  78. // Signature algorithms
  79. const (
  80. EdDSA = SignatureAlgorithm("EdDSA")
  81. HS256 = SignatureAlgorithm("HS256") // HMAC using SHA-256
  82. HS384 = SignatureAlgorithm("HS384") // HMAC using SHA-384
  83. HS512 = SignatureAlgorithm("HS512") // HMAC using SHA-512
  84. RS256 = SignatureAlgorithm("RS256") // RSASSA-PKCS-v1.5 using SHA-256
  85. RS384 = SignatureAlgorithm("RS384") // RSASSA-PKCS-v1.5 using SHA-384
  86. RS512 = SignatureAlgorithm("RS512") // RSASSA-PKCS-v1.5 using SHA-512
  87. ES256 = SignatureAlgorithm("ES256") // ECDSA using P-256 and SHA-256
  88. ES384 = SignatureAlgorithm("ES384") // ECDSA using P-384 and SHA-384
  89. ES512 = SignatureAlgorithm("ES512") // ECDSA using P-521 and SHA-512
  90. PS256 = SignatureAlgorithm("PS256") // RSASSA-PSS using SHA256 and MGF1-SHA256
  91. PS384 = SignatureAlgorithm("PS384") // RSASSA-PSS using SHA384 and MGF1-SHA384
  92. PS512 = SignatureAlgorithm("PS512") // RSASSA-PSS using SHA512 and MGF1-SHA512
  93. )
  94. // Content encryption algorithms
  95. const (
  96. A128CBC_HS256 = ContentEncryption("A128CBC-HS256") // AES-CBC + HMAC-SHA256 (128)
  97. A192CBC_HS384 = ContentEncryption("A192CBC-HS384") // AES-CBC + HMAC-SHA384 (192)
  98. A256CBC_HS512 = ContentEncryption("A256CBC-HS512") // AES-CBC + HMAC-SHA512 (256)
  99. A128GCM = ContentEncryption("A128GCM") // AES-GCM (128)
  100. A192GCM = ContentEncryption("A192GCM") // AES-GCM (192)
  101. A256GCM = ContentEncryption("A256GCM") // AES-GCM (256)
  102. )
  103. // Compression algorithms
  104. const (
  105. NONE = CompressionAlgorithm("") // No compression
  106. DEFLATE = CompressionAlgorithm("DEF") // DEFLATE (RFC 1951)
  107. )
  108. // A key in the protected header of a JWS object. Use of the Header...
  109. // constants is preferred to enhance type safety.
  110. type HeaderKey string
  111. const (
  112. HeaderType HeaderKey = "typ" // string
  113. HeaderContentType = "cty" // string
  114. // These are set by go-jose and shouldn't need to be set by consumers of the
  115. // library.
  116. headerAlgorithm = "alg" // string
  117. headerEncryption = "enc" // ContentEncryption
  118. headerCompression = "zip" // CompressionAlgorithm
  119. headerCritical = "crit" // []string
  120. headerAPU = "apu" // *byteBuffer
  121. headerAPV = "apv" // *byteBuffer
  122. headerEPK = "epk" // *JSONWebKey
  123. headerIV = "iv" // *byteBuffer
  124. headerTag = "tag" // *byteBuffer
  125. headerX5c = "x5c" // []*x509.Certificate
  126. headerJWK = "jwk" // *JSONWebKey
  127. headerKeyID = "kid" // string
  128. headerNonce = "nonce" // string
  129. )
  130. // rawHeader represents the JOSE header for JWE/JWS objects (used for parsing).
  131. //
  132. // The decoding of the constituent items is deferred because we want to marshal
  133. // some members into particular structs rather than generic maps, but at the
  134. // same time we need to receive any extra fields unhandled by this library to
  135. // pass through to consuming code in case it wants to examine them.
  136. type rawHeader map[HeaderKey]*json.RawMessage
  137. // Header represents the read-only JOSE header for JWE/JWS objects.
  138. type Header struct {
  139. KeyID string
  140. JSONWebKey *JSONWebKey
  141. Algorithm string
  142. Nonce string
  143. // Unverified certificate chain parsed from x5c header.
  144. certificates []*x509.Certificate
  145. // Any headers not recognised above get unmarshaled
  146. // from JSON in a generic manner and placed in this map.
  147. ExtraHeaders map[HeaderKey]interface{}
  148. }
  149. // Certificates verifies & returns the certificate chain present
  150. // in the x5c header field of a message, if one was present. Returns
  151. // an error if there was no x5c header present or the chain could
  152. // not be validated with the given verify options.
  153. func (h Header) Certificates(opts x509.VerifyOptions) ([][]*x509.Certificate, error) {
  154. if len(h.certificates) == 0 {
  155. return nil, errors.New("square/go-jose: no x5c header present in message")
  156. }
  157. leaf := h.certificates[0]
  158. if opts.Intermediates == nil {
  159. opts.Intermediates = x509.NewCertPool()
  160. for _, intermediate := range h.certificates[1:] {
  161. opts.Intermediates.AddCert(intermediate)
  162. }
  163. }
  164. return leaf.Verify(opts)
  165. }
  166. func (parsed rawHeader) set(k HeaderKey, v interface{}) error {
  167. b, err := json.Marshal(v)
  168. if err != nil {
  169. return err
  170. }
  171. parsed[k] = makeRawMessage(b)
  172. return nil
  173. }
  174. // getString gets a string from the raw JSON, defaulting to "".
  175. func (parsed rawHeader) getString(k HeaderKey) string {
  176. v, ok := parsed[k]
  177. if !ok {
  178. return ""
  179. }
  180. var s string
  181. err := json.Unmarshal(*v, &s)
  182. if err != nil {
  183. return ""
  184. }
  185. return s
  186. }
  187. // getByteBuffer gets a byte buffer from the raw JSON. Returns (nil, nil) if
  188. // not specified.
  189. func (parsed rawHeader) getByteBuffer(k HeaderKey) (*byteBuffer, error) {
  190. v := parsed[k]
  191. if v == nil {
  192. return nil, nil
  193. }
  194. var bb *byteBuffer
  195. err := json.Unmarshal(*v, &bb)
  196. if err != nil {
  197. return nil, err
  198. }
  199. return bb, nil
  200. }
  201. // getAlgorithm extracts parsed "alg" from the raw JSON as a KeyAlgorithm.
  202. func (parsed rawHeader) getAlgorithm() KeyAlgorithm {
  203. return KeyAlgorithm(parsed.getString(headerAlgorithm))
  204. }
  205. // getSignatureAlgorithm extracts parsed "alg" from the raw JSON as a SignatureAlgorithm.
  206. func (parsed rawHeader) getSignatureAlgorithm() SignatureAlgorithm {
  207. return SignatureAlgorithm(parsed.getString(headerAlgorithm))
  208. }
  209. // getEncryption extracts parsed "enc" from the raw JSON.
  210. func (parsed rawHeader) getEncryption() ContentEncryption {
  211. return ContentEncryption(parsed.getString(headerEncryption))
  212. }
  213. // getCompression extracts parsed "zip" from the raw JSON.
  214. func (parsed rawHeader) getCompression() CompressionAlgorithm {
  215. return CompressionAlgorithm(parsed.getString(headerCompression))
  216. }
  217. func (parsed rawHeader) getNonce() string {
  218. return parsed.getString(headerNonce)
  219. }
  220. // getEPK extracts parsed "epk" from the raw JSON.
  221. func (parsed rawHeader) getEPK() (*JSONWebKey, error) {
  222. v := parsed[headerEPK]
  223. if v == nil {
  224. return nil, nil
  225. }
  226. var epk *JSONWebKey
  227. err := json.Unmarshal(*v, &epk)
  228. if err != nil {
  229. return nil, err
  230. }
  231. return epk, nil
  232. }
  233. // getAPU extracts parsed "apu" from the raw JSON.
  234. func (parsed rawHeader) getAPU() (*byteBuffer, error) {
  235. return parsed.getByteBuffer(headerAPU)
  236. }
  237. // getAPV extracts parsed "apv" from the raw JSON.
  238. func (parsed rawHeader) getAPV() (*byteBuffer, error) {
  239. return parsed.getByteBuffer(headerAPV)
  240. }
  241. // getIV extracts parsed "iv" frpom the raw JSON.
  242. func (parsed rawHeader) getIV() (*byteBuffer, error) {
  243. return parsed.getByteBuffer(headerIV)
  244. }
  245. // getTag extracts parsed "tag" frpom the raw JSON.
  246. func (parsed rawHeader) getTag() (*byteBuffer, error) {
  247. return parsed.getByteBuffer(headerTag)
  248. }
  249. // getJWK extracts parsed "jwk" from the raw JSON.
  250. func (parsed rawHeader) getJWK() (*JSONWebKey, error) {
  251. v := parsed[headerJWK]
  252. if v == nil {
  253. return nil, nil
  254. }
  255. var jwk *JSONWebKey
  256. err := json.Unmarshal(*v, &jwk)
  257. if err != nil {
  258. return nil, err
  259. }
  260. return jwk, nil
  261. }
  262. // getCritical extracts parsed "crit" from the raw JSON. If omitted, it
  263. // returns an empty slice.
  264. func (parsed rawHeader) getCritical() ([]string, error) {
  265. v := parsed[headerCritical]
  266. if v == nil {
  267. return nil, nil
  268. }
  269. var q []string
  270. err := json.Unmarshal(*v, &q)
  271. if err != nil {
  272. return nil, err
  273. }
  274. return q, nil
  275. }
  276. // sanitized produces a cleaned-up header object from the raw JSON.
  277. func (parsed rawHeader) sanitized() (h Header, err error) {
  278. for k, v := range parsed {
  279. if v == nil {
  280. continue
  281. }
  282. switch k {
  283. case headerJWK:
  284. var jwk *JSONWebKey
  285. err = json.Unmarshal(*v, &jwk)
  286. if err != nil {
  287. err = fmt.Errorf("failed to unmarshal JWK: %v: %#v", err, string(*v))
  288. return
  289. }
  290. h.JSONWebKey = jwk
  291. case headerKeyID:
  292. var s string
  293. err = json.Unmarshal(*v, &s)
  294. if err != nil {
  295. err = fmt.Errorf("failed to unmarshal key ID: %v: %#v", err, string(*v))
  296. return
  297. }
  298. h.KeyID = s
  299. case headerAlgorithm:
  300. var s string
  301. err = json.Unmarshal(*v, &s)
  302. if err != nil {
  303. err = fmt.Errorf("failed to unmarshal algorithm: %v: %#v", err, string(*v))
  304. return
  305. }
  306. h.Algorithm = s
  307. case headerNonce:
  308. var s string
  309. err = json.Unmarshal(*v, &s)
  310. if err != nil {
  311. err = fmt.Errorf("failed to unmarshal nonce: %v: %#v", err, string(*v))
  312. return
  313. }
  314. h.Nonce = s
  315. case headerX5c:
  316. c := []string{}
  317. err = json.Unmarshal(*v, &c)
  318. if err != nil {
  319. err = fmt.Errorf("failed to unmarshal x5c header: %v: %#v", err, string(*v))
  320. return
  321. }
  322. h.certificates, err = parseCertificateChain(c)
  323. if err != nil {
  324. err = fmt.Errorf("failed to unmarshal x5c header: %v: %#v", err, string(*v))
  325. return
  326. }
  327. default:
  328. if h.ExtraHeaders == nil {
  329. h.ExtraHeaders = map[HeaderKey]interface{}{}
  330. }
  331. var v2 interface{}
  332. err = json.Unmarshal(*v, &v2)
  333. if err != nil {
  334. err = fmt.Errorf("failed to unmarshal value: %v: %#v", err, string(*v))
  335. return
  336. }
  337. h.ExtraHeaders[k] = v2
  338. }
  339. }
  340. return
  341. }
  342. func parseCertificateChain(chain []string) ([]*x509.Certificate, error) {
  343. out := make([]*x509.Certificate, len(chain))
  344. for i, cert := range chain {
  345. raw, err := base64.StdEncoding.DecodeString(cert)
  346. if err != nil {
  347. return nil, err
  348. }
  349. out[i], err = x509.ParseCertificate(raw)
  350. if err != nil {
  351. return nil, err
  352. }
  353. }
  354. return out, nil
  355. }
  356. func (dst rawHeader) isSet(k HeaderKey) bool {
  357. dvr := dst[k]
  358. if dvr == nil {
  359. return false
  360. }
  361. var dv interface{}
  362. err := json.Unmarshal(*dvr, &dv)
  363. if err != nil {
  364. return true
  365. }
  366. if dvStr, ok := dv.(string); ok {
  367. return dvStr != ""
  368. }
  369. return true
  370. }
  371. // Merge headers from src into dst, giving precedence to headers from l.
  372. func (dst rawHeader) merge(src *rawHeader) {
  373. if src == nil {
  374. return
  375. }
  376. for k, v := range *src {
  377. if dst.isSet(k) {
  378. continue
  379. }
  380. dst[k] = v
  381. }
  382. }
  383. // Get JOSE name of curve
  384. func curveName(crv elliptic.Curve) (string, error) {
  385. switch crv {
  386. case elliptic.P256():
  387. return "P-256", nil
  388. case elliptic.P384():
  389. return "P-384", nil
  390. case elliptic.P521():
  391. return "P-521", nil
  392. default:
  393. return "", fmt.Errorf("square/go-jose: unsupported/unknown elliptic curve")
  394. }
  395. }
  396. // Get size of curve in bytes
  397. func curveSize(crv elliptic.Curve) int {
  398. bits := crv.Params().BitSize
  399. div := bits / 8
  400. mod := bits % 8
  401. if mod == 0 {
  402. return div
  403. }
  404. return div + 1
  405. }
  406. func makeRawMessage(b []byte) *json.RawMessage {
  407. rm := json.RawMessage(b)
  408. return &rm
  409. }