Debian Codegraph @

signature/jws/envelope.go

raw
1 // Copyright The Notary Project Authors.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package jws
15
16 import (
17 "crypto/x509"
18 "encoding/base64"
19 "encoding/json"
20 "fmt"
21
22 "github.com/golang-jwt/jwt/v4"
23 "github.com/notaryproject/notation-core-go/internal/timestamp"
24 "github.com/notaryproject/notation-core-go/signature"
25 "github.com/notaryproject/notation-core-go/signature/internal/base"
26 "github.com/notaryproject/tspclient-go"
27 )
28
29 // MediaTypeEnvelope defines the media type name of JWS envelope.
30 const MediaTypeEnvelope = "application/jose+json"
31
32 func init() {
33 if err := signature.RegisterEnvelopeType(MediaTypeEnvelope, NewEnvelope, ParseEnvelope); err != nil {
34 panic(err)
35 }
36 }
37
38 type envelope struct {
39 base *jwsEnvelope
40 }
41
42 // NewEnvelope generates an JWS envelope.
43 func NewEnvelope() signature.Envelope {
44 return &base.Envelope{
45 Envelope: &envelope{},
46 }
47 }
48
49 // ParseEnvelope parses the envelope bytes and return a JWS envelope.
50 func ParseEnvelope(envelopeBytes []byte) (signature.Envelope, error) {
51 var e jwsEnvelope
52 err := json.Unmarshal(envelopeBytes, &e)
53 if err != nil {
54 return nil, &signature.InvalidSignatureError{Msg: err.Error()}
55 }
56 return &base.Envelope{
57 Envelope: &envelope{base: &e},
58 Raw: envelopeBytes,
59 }, nil
60 }
61
62 // Sign generates and sign the envelope according to the sign request.
63 func (e *envelope) Sign(req *signature.SignRequest) ([]byte, error) {
64 // get signingMethod for JWT package
65 method, err := getSigningMethod(req.Signer)
66 if err != nil {
67 return nil, &signature.InvalidSignRequestError{Msg: err.Error()}
68 }
69
70 // get all attributes ready to be signed
71 signedAttrs, err := getSignedAttributes(req, method.Alg())
72 if err != nil {
73 return nil, &signature.InvalidSignRequestError{Msg: err.Error()}
74 }
75
76 // parse payload as jwt.MapClaims
77 // [jwt-go]: https://pkg.go.dev/github.com/dgrijalva/jwt-go#MapClaims
78 var payload jwt.MapClaims
79 if err = json.Unmarshal(req.Payload.Content, &payload); err != nil {
80 return nil, &signature.InvalidSignRequestError{
81 Msg: fmt.Sprintf("payload format error: %v", err.Error())}
82 }
83
84 // JWT sign and get certificate chain
85 compact, certs, err := sign(payload, signedAttrs, method)
86 if err != nil {
87 return nil, &signature.InvalidSignRequestError{Msg: err.Error()}
88 }
89
90 // generate envelope
91 env, err := generateJWS(compact, req, certs)
92 if err != nil {
93 return nil, &signature.InvalidSignatureError{Msg: err.Error()}
94 }
95
96 // timestamping
97 if err := timestampJWS(env, req, signedAttrs[headerKeySigningScheme].(string)); err != nil {
98 return nil, err
99 }
100
101 encoded, err := json.Marshal(env)
102 if err != nil {
103 return nil, &signature.InvalidSignatureError{Msg: err.Error()}
104 }
105 e.base = env
106
107 return encoded, nil
108 }
109
110 // Verify verifies the envelope and returns its enclosed payload and signer info.
111 func (e *envelope) Verify() (*signature.EnvelopeContent, error) {
112 if e.base == nil {
113 return nil, &signature.SignatureEnvelopeNotFoundError{}
114 }
115
116 if len(e.base.Header.CertChain) == 0 {
117 return nil, &signature.InvalidSignatureError{Msg: "certificate chain is not present"}
118 }
119
120 cert, err := x509.ParseCertificate(e.base.Header.CertChain[0])
121 if err != nil {
122 return nil, &signature.InvalidSignatureError{Msg: "malformed leaf certificate"}
123 }
124
125 // verify JWT
126 compact := compactJWS(e.base)
127 if err = verifyJWT(compact, cert.PublicKey); err != nil {
128 return nil, err
129 }
130
131 return e.Content()
132 }
133
134 // Content returns the payload and signer information of the envelope.
135 // Content is trusted only after the successful call to `Verify()`.
136 func (e *envelope) Content() (*signature.EnvelopeContent, error) {
137 if e.base == nil {
138 return nil, &signature.SignatureEnvelopeNotFoundError{}
139 }
140
141 // parse protected headers
142 protected, err := parseProtectedHeaders(e.base.Protected)
143 if err != nil {
144 return nil, err
145 }
146
147 // extract payload
148 payload, err := e.payload(protected)
149 if err != nil {
150 return nil, err
151 }
152
153 // extract signer info
154 signerInfo, err := e.signerInfo(protected)
155 if err != nil {
156 return nil, err
157 }
158 return &signature.EnvelopeContent{
159 SignerInfo: *signerInfo,
160 Payload: *payload,
161 }, nil
162 }
163
164 // payload returns the payload of JWS envelope.
165 func (e *envelope) payload(protected *jwsProtectedHeader) (*signature.Payload, error) {
166 payload, err := base64.RawURLEncoding.DecodeString(e.base.Payload)
167 if err != nil {
168 return nil, &signature.InvalidSignatureError{
169 Msg: fmt.Sprintf("payload error: %v", err)}
170 }
171
172 return &signature.Payload{
173 Content: payload,
174 ContentType: protected.ContentType,
175 }, nil
176 }
177
178 // signerInfo returns the SignerInfo of JWS envelope.
179 func (e *envelope) signerInfo(protected *jwsProtectedHeader) (*signature.SignerInfo, error) {
180 var signerInfo signature.SignerInfo
181
182 // populate protected header to signerInfo
183 if err := populateProtectedHeaders(protected, &signerInfo); err != nil {
184 return nil, err
185 }
186
187 // parse signature
188 sig, err := base64.RawURLEncoding.DecodeString(e.base.Signature)
189 if err != nil {
190 return nil, &signature.InvalidSignatureError{Msg: err.Error()}
191 }
192 if len(sig) == 0 {
193 return nil, &signature.InvalidSignatureError{Msg: "signature missing in jws-json envelope"}
194 }
195 signerInfo.Signature = sig
196
197 // parse headers
198 var certs []*x509.Certificate
199 for _, certBytes := range e.base.Header.CertChain {
200 cert, err := x509.ParseCertificate(certBytes)
201 if err != nil {
202 return nil, &signature.InvalidSignatureError{Msg: err.Error()}
203 }
204 certs = append(certs, cert)
205 }
206 signerInfo.CertificateChain = certs
207 signerInfo.UnsignedAttributes.SigningAgent = e.base.Header.SigningAgent
208 signerInfo.UnsignedAttributes.TimestampSignature = e.base.Header.TimestampSignature
209 return &signerInfo, nil
210 }
211
212 // sign the given payload and headers using the given signature provider.
213 func sign(payload jwt.MapClaims, headers map[string]interface{}, method signingMethod) (string, []*x509.Certificate, error) {
214 // generate token
215 token := jwt.NewWithClaims(method, payload)
216 token.Header = headers
217
218 // sign and return compact JWS
219 compact, err := token.SignedString(method.PrivateKey())
220 if err != nil {
221 return "", nil, err
222 }
223
224 // access certificate chain after sign
225 certs, err := method.CertificateChain()
226 if err != nil {
227 return "", nil, err
228 }
229 return compact, certs, nil
230 }
231
232 // timestampJWS timestamps a JWS envelope
233 func timestampJWS(env *jwsEnvelope, req *signature.SignRequest, signingScheme string) error {
234 if signingScheme != string(signature.SigningSchemeX509) || req.Timestamper == nil {
235 return nil
236 }
237 primitiveSignature, err := base64.RawURLEncoding.DecodeString(env.Signature)
238 if err != nil {
239 return &signature.TimestampError{Detail: err}
240 }
241 ks, err := req.Signer.KeySpec()
242 if err != nil {
243 return &signature.TimestampError{Detail: err}
244 }
245 hash := ks.SignatureAlgorithm().Hash()
246 if hash == 0 {
247 return &signature.TimestampError{Msg: fmt.Sprintf("got hash value 0 from key spec %+v", ks)}
248 }
249 timestampOpts := tspclient.RequestOptions{
250 Content: primitiveSignature,
251 HashAlgorithm: hash,
252 }
253 timestampToken, err := timestamp.Timestamp(req, timestampOpts)
254 if err != nil {
255 return &signature.TimestampError{Detail: err}
256 }
257
258 // on success, embed the timestamp token to TimestampSignature
259 env.Header.TimestampSignature = timestampToken
260 return nil
261 }