Debian Codegraph @

signature/jws/jws.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 "strings"
22
23 "github.com/notaryproject/notation-core-go/signature"
24 )
25
26 func parseProtectedHeaders(encoded string) (*jwsProtectedHeader, error) {
27 rawProtected, err := base64.RawURLEncoding.DecodeString(encoded)
28 if err != nil {
29 return nil, &signature.InvalidSignatureError{
30 Msg: fmt.Sprintf("jws envelope protected header can't be decoded: %s", err.Error())}
31 }
32
33 // To Unmarshal JSON with some known(jwsProtectedHeader), and some unknown(jwsProtectedHeader.ExtendedAttributes) field names.
34 // We unmarshal twice: once into a value of type jwsProtectedHeader and once into a value of type jwsProtectedHeader.ExtendedAttributes(map[string]interface{})
35 // and removing the keys are already been defined in jwsProtectedHeader.
36 var protected jwsProtectedHeader
37 if err = json.Unmarshal(rawProtected, &protected); err != nil {
38 return nil, &signature.InvalidSignatureError{
39 Msg: fmt.Sprintf("jws envelope protected header can't be decoded: %s", err.Error())}
40 }
41 if err = json.Unmarshal(rawProtected, &protected.ExtendedAttributes); err != nil {
42 return nil, &signature.InvalidSignatureError{
43 Msg: fmt.Sprintf("jws envelope protected header can't be decoded: %s", err.Error())}
44 }
45
46 // delete attributes that are already defined in jwsProtectedHeader.
47 for _, headerKey := range headerKeys {
48 delete(protected.ExtendedAttributes, headerKey)
49 }
50 return &protected, nil
51 }
52
53 func populateProtectedHeaders(protectedHeader *jwsProtectedHeader, signerInfo *signature.SignerInfo) error {
54 err := validateProtectedHeaders(protectedHeader)
55 if err != nil {
56 return err
57 }
58
59 if signerInfo.SignatureAlgorithm, err = getSignatureAlgorithm(protectedHeader.Algorithm); err != nil {
60 return err
61 }
62
63 signerInfo.SignedAttributes.ExtendedAttributes = getExtendedAttributes(protectedHeader.ExtendedAttributes, protectedHeader.Critical)
64 signerInfo.SignedAttributes.SigningScheme = protectedHeader.SigningScheme
65 if protectedHeader.Expiry != nil {
66 signerInfo.SignedAttributes.Expiry = *protectedHeader.Expiry
67 }
68 switch protectedHeader.SigningScheme {
69 case signature.SigningSchemeX509:
70 if protectedHeader.SigningTime != nil {
71 signerInfo.SignedAttributes.SigningTime = *protectedHeader.SigningTime
72 }
73 case signature.SigningSchemeX509SigningAuthority:
74 if protectedHeader.AuthenticSigningTime != nil {
75 signerInfo.SignedAttributes.SigningTime = *protectedHeader.AuthenticSigningTime
76 }
77 default:
78 return &signature.InvalidSignatureError{
79 Msg: fmt.Sprintf("unsupported SigningScheme: `%v`", protectedHeader.SigningScheme),
80 }
81 }
82 return nil
83 }
84
85 func validateProtectedHeaders(protectedHeader *jwsProtectedHeader) error {
86 // validate headers that should not be present as per signing schemes
87 switch protectedHeader.SigningScheme {
88 case signature.SigningSchemeX509:
89 if protectedHeader.AuthenticSigningTime != nil {
90 return &signature.InvalidSignatureError{Msg: fmt.Sprintf("%q header must not be present for %s signing scheme", headerKeyAuthenticSigningTime, signature.SigningSchemeX509)}
91 }
92 case signature.SigningSchemeX509SigningAuthority:
93 if protectedHeader.SigningTime != nil {
94 return &signature.InvalidSignatureError{Msg: fmt.Sprintf("%q header must not be present for %s signing scheme", headerKeySigningTime, signature.SigningSchemeX509SigningAuthority)}
95 }
96 if protectedHeader.AuthenticSigningTime == nil {
97 return &signature.InvalidSignatureError{Msg: fmt.Sprintf("%q header must be present for %s signing scheme", headerKeyAuthenticSigningTime, signature.SigningSchemeX509)}
98 }
99 default:
100 return &signature.InvalidSignatureError{Msg: fmt.Sprintf("unsupported SigningScheme: `%v`", protectedHeader.SigningScheme)}
101 }
102
103 return validateCriticalHeaders(protectedHeader)
104 }
105
106 func validateCriticalHeaders(protectedHeader *jwsProtectedHeader) error {
107 if len(protectedHeader.Critical) == 0 {
108 return &signature.InvalidSignatureError{Msg: `missing "crit" header`}
109 }
110
111 mustMarkedCrit := map[string]bool{headerKeySigningScheme: true}
112 if protectedHeader.Expiry != nil && !protectedHeader.Expiry.IsZero() {
113 mustMarkedCrit[headerKeyExpiry] = true
114 }
115
116 if protectedHeader.SigningScheme == signature.SigningSchemeX509SigningAuthority {
117 mustMarkedCrit[headerKeyAuthenticSigningTime] = true
118 }
119
120 for _, val := range protectedHeader.Critical {
121 if _, ok := mustMarkedCrit[val]; ok {
122 delete(mustMarkedCrit, val)
123 } else {
124 if _, ok := protectedHeader.ExtendedAttributes[val]; !ok {
125 return &signature.InvalidSignatureError{
126 Msg: fmt.Sprintf("%q header is marked critical but not present", val)}
127 }
128 }
129 }
130
131 // validate all required critical headers headers(as per spec) are marked as critical.
132 if len(mustMarkedCrit) != 0 {
133 // This is not taken care by VerifySignerInfo method
134 keys := make([]string, 0, len(mustMarkedCrit))
135 for k := range mustMarkedCrit {
136 keys = append(keys, k)
137 }
138 return &signature.InvalidSignatureError{Msg: fmt.Sprintf("these required headers are not marked as critical: %v", keys)}
139 }
140
141 return nil
142 }
143
144 func getSignatureAlgorithm(alg string) (signature.Algorithm, error) {
145 signatureAlg, ok := jwsAlgSignatureAlgMap[alg]
146 if !ok {
147 return 0, &signature.UnsupportedSignatureAlgoError{Alg: alg}
148 }
149
150 return signatureAlg, nil
151 }
152
153 func getExtendedAttributes(attrs map[string]interface{}, critical []string) []signature.Attribute {
154 extendedAttr := make([]signature.Attribute, 0, len(attrs))
155 for key, value := range attrs {
156 extendedAttr = append(extendedAttr, signature.Attribute{
157 Key: key,
158 Critical: contains(critical, key),
159 Value: value,
160 })
161 }
162 return extendedAttr
163 }
164
165 func contains(s []string, e string) bool {
166 for _, a := range s {
167 if a == e {
168 return true
169 }
170 }
171 return false
172 }
173
174 func generateJWS(compact string, req *signature.SignRequest, certs []*x509.Certificate) (*jwsEnvelope, error) {
175 parts := strings.Split(compact, ".")
176 if len(parts) != 3 {
177 // this should never happen
178 return nil, fmt.Errorf(
179 "unexpected error occurred while generating a JWS-JSON serialization from compact serialization. want: len(parts) == 3, got: len(parts) == %d", len(parts))
180 }
181
182 rawCerts := make([][]byte, len(certs))
183 for i, cert := range certs {
184 rawCerts[i] = cert.Raw
185 }
186
187 return &jwsEnvelope{
188 Protected: parts[0],
189 Payload: parts[1],
190 Signature: parts[2],
191 Header: jwsUnprotectedHeader{
192 CertChain: rawCerts,
193 SigningAgent: req.SigningAgent,
194 },
195 }, nil
196 }
197
198 // getSignerAttributes merge extended signed attributes and protected header to be signed attributes.
199 func getSignedAttributes(req *signature.SignRequest, algorithm string) (map[string]interface{}, error) {
200 extAttrs := make(map[string]interface{})
201 crit := []string{headerKeySigningScheme}
202
203 // write extended signed attributes to the extAttrs map
204 for _, elm := range req.ExtendedSignedAttributes {
205 key, ok := elm.Key.(string)
206 if !ok {
207 return nil, &signature.InvalidSignRequestError{Msg: "JWS envelope format only supports key of type string"}
208 }
209 if _, ok := extAttrs[key]; ok {
210 return nil, &signature.InvalidSignRequestError{Msg: fmt.Sprintf("%q already exists in the extAttrs", key)}
211 }
212 extAttrs[key] = elm.Value
213 if elm.Critical {
214 crit = append(crit, key)
215 }
216 }
217
218 jwsProtectedHeader := jwsProtectedHeader{
219 Algorithm: algorithm,
220 ContentType: req.Payload.ContentType,
221 SigningScheme: req.SigningScheme,
222 }
223
224 switch req.SigningScheme {
225 case signature.SigningSchemeX509:
226 jwsProtectedHeader.SigningTime = &req.SigningTime
227 case signature.SigningSchemeX509SigningAuthority:
228 crit = append(crit, headerKeyAuthenticSigningTime)
229 jwsProtectedHeader.AuthenticSigningTime = &req.SigningTime
230 default:
231 return nil, fmt.Errorf("unsupported SigningScheme: `%v`", req.SigningScheme)
232 }
233
234 if !req.Expiry.IsZero() {
235 crit = append(crit, headerKeyExpiry)
236 jwsProtectedHeader.Expiry = &req.Expiry
237 }
238
239 jwsProtectedHeader.Critical = crit
240 m, err := convertToMap(jwsProtectedHeader)
241 if err != nil {
242 return nil, fmt.Errorf("unexpected error occurred while creating protected headers, Error: %s", err.Error())
243 }
244
245 return mergeMaps(m, extAttrs)
246 }
247
248 func convertToMap(i interface{}) (map[string]interface{}, error) {
249 s, err := json.Marshal(i)
250 if err != nil {
251 return nil, err
252 }
253
254 var m map[string]interface{}
255 err = json.Unmarshal(s, &m)
256 return m, err
257 }
258
259 func mergeMaps(maps ...map[string]interface{}) (map[string]interface{}, error) {
260 result := make(map[string]interface{})
261 for _, m := range maps {
262 for k, v := range m {
263 if _, ok := result[k]; ok {
264 return nil, fmt.Errorf("attribute key:%s repeated", k)
265 }
266 result[k] = v
267 }
268 }
269 return result, nil
270 }
271
272 // compactJWS converts Flattened JWS JSON Serialization Syntax (section-7.2.2) to
273 // JWS Compact Serialization (section-7.1)
274 //
275 // [RFC 7515]: https://www.rfc-editor.org/rfc/rfc7515.html
276 func compactJWS(envelope *jwsEnvelope) string {
277 return strings.Join([]string{
278 envelope.Protected,
279 envelope.Payload,
280 envelope.Signature}, ".")
281 }