Debian Codegraph @

signer/plugin.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 signer
15
16 import (
17 "context"
18 "crypto/x509"
19 "encoding/json"
20 "errors"
21 "fmt"
22 "time"
23
24 "oras.land/oras-go/v2/content"
25
26 "github.com/notaryproject/notation-core-go/signature"
27 "github.com/notaryproject/notation-go"
28 "github.com/notaryproject/notation-go/internal/envelope"
29 "github.com/notaryproject/notation-go/log"
30 "github.com/notaryproject/notation-go/plugin/proto"
31 "github.com/notaryproject/notation-plugin-framework-go/plugin"
32 ocispec "github.com/opencontainers/image-spec/specs-go/v1"
33 )
34
35 // PluginSigner signs artifacts and generates signatures.
36 // It implements notation.Signer
37 type PluginSigner struct {
38 plugin plugin.SignPlugin
39 keyID string
40 pluginConfig map[string]string
41 manifestAnnotations map[string]string
42 }
43
44 // NewFromPlugin creates a notation.Signer that signs artifacts and generates
45 // signatures by delegating the one or more operations to the named plugin,
46 // as defined in https://github.com/notaryproject/notaryproject/blob/main/specs/plugin-extensibility.md#signing-interfaces.
47 //
48 // Deprecated: NewFromPlugin function exists for historical compatibility and should not be used.
49 // To create PluginSigner, use NewPluginSigner() function.
50 func NewFromPlugin(plugin plugin.SignPlugin, keyID string, pluginConfig map[string]string) (notation.Signer, error) {
51 return NewPluginSigner(plugin, keyID, pluginConfig)
52 }
53
54 // NewPluginSigner creates a notation.Signer that signs artifacts and generates
55 // signatures by delegating the one or more operations to the named plugin,
56 // as defined in https://github.com/notaryproject/notaryproject/blob/main/specs/plugin-extensibility.md#signing-interfaces.
57 func NewPluginSigner(plugin plugin.SignPlugin, keyID string, pluginConfig map[string]string) (*PluginSigner, error) {
58 if plugin == nil {
59 return nil, errors.New("nil plugin")
60 }
61 if keyID == "" {
62 return nil, errors.New("keyID not specified")
63 }
64
65 return &PluginSigner{
66 plugin: plugin,
67 keyID: keyID,
68 pluginConfig: pluginConfig,
69 }, nil
70 }
71
72 // PluginAnnotations returns signature manifest annotations returned from plugin
73 func (s *PluginSigner) PluginAnnotations() map[string]string {
74 return s.manifestAnnotations
75 }
76
77 // Sign signs the artifact described by its descriptor and returns the
78 // marshalled envelope.
79 func (s *PluginSigner) Sign(ctx context.Context, desc ocispec.Descriptor, opts notation.SignerSignOptions) ([]byte, *signature.SignerInfo, error) {
80 logger := log.GetLogger(ctx)
81 mergedConfig := s.mergeConfig(opts.PluginConfig)
82
83 logger.Debug("Invoking plugin's get-plugin-metadata command")
84 metadata, err := s.plugin.GetMetadata(ctx, &plugin.GetMetadataRequest{PluginConfig: mergedConfig})
85 if err != nil {
86 return nil, nil, err
87 }
88
89 logger.Debugf("Using plugin %v with capabilities %v to sign oci artifact %v in signature media type %v", metadata.Name, metadata.Capabilities, desc.Digest, opts.SignatureMediaType)
90 if metadata.HasCapability(plugin.CapabilitySignatureGenerator) {
91 ks, err := s.getKeySpec(ctx, mergedConfig)
92 if err != nil {
93 return nil, nil, fmt.Errorf("failed to sign with the plugin %s: %w", metadata.Name, err)
94 }
95
96 sig, signerInfo, err := s.generateSignature(ctx, desc, opts, ks, metadata, mergedConfig)
97 if err != nil {
98 return nil, nil, fmt.Errorf("failed to sign with the plugin %s: %w", metadata.Name, err)
99 }
100 return sig, signerInfo, nil
101 } else if metadata.HasCapability(plugin.CapabilityEnvelopeGenerator) {
102 sig, signerInfo, err := s.generateSignatureEnvelope(ctx, desc, opts)
103 if err != nil {
104 return nil, nil, fmt.Errorf("failed to sign with the plugin %s: %w", metadata.Name, err)
105 }
106 return sig, signerInfo, nil
107 }
108
109 return nil, nil, fmt.Errorf("plugin does not have signing capabilities")
110 }
111
112 func (s *PluginSigner) getKeySpec(ctx context.Context, config map[string]string) (signature.KeySpec, error) {
113 logger := log.GetLogger(ctx)
114 logger.Debug("Invoking plugin's describe-key command")
115 descKeyResp, err := s.describeKey(ctx, config)
116 if err != nil {
117 return signature.KeySpec{}, err
118 }
119
120 if s.keyID != descKeyResp.KeyID {
121 return signature.KeySpec{}, fmt.Errorf("keyID in describeKey response %q does not match request %q", descKeyResp.KeyID, s.keyID)
122 }
123
124 return proto.DecodeKeySpec(descKeyResp.KeySpec)
125 }
126
127 func (s *PluginSigner) generateSignature(ctx context.Context, desc ocispec.Descriptor, opts notation.SignerSignOptions, ks signature.KeySpec, metadata *plugin.GetMetadataResponse, pluginConfig map[string]string) ([]byte, *signature.SignerInfo, error) {
128 logger := log.GetLogger(ctx)
129 logger.Debug("Generating signature by plugin")
130 genericSigner := GenericSigner{
131 signer: &pluginPrimitiveSigner{
132 ctx: ctx,
133 plugin: s.plugin,
134 keyID: s.keyID,
135 pluginConfig: pluginConfig,
136 keySpec: ks,
137 },
138 }
139
140 opts.SigningAgent = fmt.Sprintf("%s %s/%s", signingAgent, metadata.Name, metadata.Version)
141 return genericSigner.Sign(ctx, desc, opts)
142 }
143
144 func (s *PluginSigner) generateSignatureEnvelope(ctx context.Context, desc ocispec.Descriptor, opts notation.SignerSignOptions) ([]byte, *signature.SignerInfo, error) {
145 logger := log.GetLogger(ctx)
146 logger.Debug("Generating signature envelope by plugin")
147 payload := envelope.Payload{TargetArtifact: envelope.SanitizeTargetArtifact(desc)}
148 payloadBytes, err := json.Marshal(payload)
149 if err != nil {
150 return nil, nil, fmt.Errorf("envelope payload can't be marshalled: %w", err)
151 }
152 // Execute plugin sign command.
153 req := &plugin.GenerateEnvelopeRequest{
154 ContractVersion: plugin.ContractVersion,
155 KeyID: s.keyID,
156 Payload: payloadBytes,
157 SignatureEnvelopeType: opts.SignatureMediaType,
158 PayloadType: envelope.MediaTypePayloadV1,
159 ExpiryDurationInSeconds: uint64(opts.ExpiryDuration / time.Second),
160 PluginConfig: s.mergeConfig(opts.PluginConfig),
161 }
162 resp, err := s.plugin.GenerateEnvelope(ctx, req)
163 if err != nil {
164 return nil, nil, fmt.Errorf("plugin failed to sign with following error: %w", err)
165 }
166
167 // Check signatureEnvelopeType is honored.
168 if resp.SignatureEnvelopeType != req.SignatureEnvelopeType {
169 return nil, nil, fmt.Errorf(
170 "signatureEnvelopeType in generateEnvelope response %q does not match request %q",
171 resp.SignatureEnvelopeType, req.SignatureEnvelopeType,
172 )
173 }
174
175 logger.Debug("Verifying signature envelope generated by the plugin")
176 sigEnv, err := signature.ParseEnvelope(opts.SignatureMediaType, resp.SignatureEnvelope)
177 if err != nil {
178 return nil, nil, err
179 }
180
181 envContent, err := sigEnv.Verify()
182 if err != nil {
183 return nil, nil, fmt.Errorf("generated signature failed verification: %w", err)
184 }
185 if err := envelope.ValidatePayloadContentType(&envContent.Payload); err != nil {
186 return nil, nil, err
187 }
188
189 content := envContent.Payload.Content
190 var signedPayload envelope.Payload
191 if err = json.Unmarshal(content, &signedPayload); err != nil {
192 return nil, nil, fmt.Errorf("signed envelope payload can't be unmarshalled: %w", err)
193 }
194
195 if !isPayloadDescriptorValid(desc, signedPayload.TargetArtifact) {
196 return nil, nil, fmt.Errorf("during signing descriptor subject has changed from %+v to %+v", desc, signedPayload.TargetArtifact)
197 }
198
199 if unknownAttributes := areUnknownAttributesAdded(content); len(unknownAttributes) != 0 {
200 return nil, nil, fmt.Errorf("during signing, following unknown attributes were added to subject descriptor: %+q", unknownAttributes)
201 }
202
203 s.manifestAnnotations = resp.Annotations
204 return resp.SignatureEnvelope, &envContent.SignerInfo, nil
205 }
206
207 func (s *PluginSigner) mergeConfig(config map[string]string) map[string]string {
208 c := make(map[string]string, len(s.pluginConfig)+len(config))
209 // First clone s.PluginConfig.
210 for k, v := range s.pluginConfig {
211 c[k] = v
212 }
213 // Then set or override entries from config.
214 for k, v := range config {
215 c[k] = v
216 }
217 return c
218 }
219
220 func (s *PluginSigner) describeKey(ctx context.Context, config map[string]string) (*plugin.DescribeKeyResponse, error) {
221 req := &plugin.DescribeKeyRequest{
222 ContractVersion: plugin.ContractVersion,
223 KeyID: s.keyID,
224 PluginConfig: config,
225 }
226 resp, err := s.plugin.DescribeKey(ctx, req)
227 if err != nil {
228 return nil, err
229 }
230
231 return resp, nil
232 }
233
234 // isDescriptorSubset checks if the both descriptors point to the same
235 // resource and that newDesc hasn't replaced or overridden existing annotations.
236 func isDescriptorSubset(original, newDesc ocispec.Descriptor) bool {
237 if !content.Equal(original, newDesc) {
238 return false
239 }
240 // Plugins may append additional annotations but not replace/override
241 // existing.
242 for k, v := range original.Annotations {
243 if v2, ok := newDesc.Annotations[k]; !ok || v != v2 {
244 return false
245 }
246 }
247 return true
248 }
249
250 func isPayloadDescriptorValid(originalDesc, newDesc ocispec.Descriptor) bool {
251 return content.Equal(originalDesc, newDesc) &&
252 isDescriptorSubset(originalDesc, newDesc)
253 }
254
255 func areUnknownAttributesAdded(content []byte) []string {
256 var targetArtifactMap map[string]interface{}
257 // Ignoring error because we already successfully unmarshalled before this
258 // point
259 _ = json.Unmarshal(content, &targetArtifactMap)
260 descriptor := targetArtifactMap["targetArtifact"].(map[string]interface{})
261
262 // Explicitly remove expected keys to check if any are left over
263 delete(descriptor, "mediaType")
264 delete(descriptor, "digest")
265 delete(descriptor, "size")
266 delete(descriptor, "urls")
267 delete(descriptor, "annotations")
268 delete(descriptor, "data")
269 delete(descriptor, "platform")
270 delete(descriptor, "artifactType")
271 delete(targetArtifactMap, "targetArtifact")
272
273 unknownAttributes := append(getKeySet(descriptor), getKeySet(targetArtifactMap)...)
274 return unknownAttributes
275 }
276
277 func getKeySet(inputMap map[string]interface{}) []string {
278 keySet := make([]string, 0, len(inputMap))
279 for k := range inputMap {
280 keySet = append(keySet, k)
281 }
282 return keySet
283 }
284
285 func parseCertChain(certChain [][]byte) ([]*x509.Certificate, error) {
286 certs := make([]*x509.Certificate, len(certChain))
287 for i, cert := range certChain {
288 cert, err := x509.ParseCertificate(cert)
289 if err != nil {
290 return nil, err
291 }
292 certs[i] = cert
293 }
294 return certs, nil
295 }
296
297 // pluginPrimitiveSigner implements signature.Signer
298 type pluginPrimitiveSigner struct {
299 ctx context.Context
300 plugin plugin.SignPlugin
301 keyID string
302 pluginConfig map[string]string
303 keySpec signature.KeySpec
304 }
305
306 // Sign signs the digest by calling the underlying plugin.
307 func (s *pluginPrimitiveSigner) Sign(payload []byte) ([]byte, []*x509.Certificate, error) {
308 // Execute plugin sign command.
309 keySpec, err := proto.EncodeKeySpec(s.keySpec)
310 if err != nil {
311 return nil, nil, err
312 }
313
314 keySpecHash, err := proto.HashAlgorithmFromKeySpec(s.keySpec)
315 if err != nil {
316 return nil, nil, err
317 }
318
319 req := &plugin.GenerateSignatureRequest{
320 ContractVersion: plugin.ContractVersion,
321 KeyID: s.keyID,
322 KeySpec: keySpec,
323 Hash: keySpecHash,
324 Payload: payload,
325 PluginConfig: s.pluginConfig,
326 }
327
328 resp, err := s.plugin.GenerateSignature(s.ctx, req)
329 if err != nil {
330 return nil, nil, err
331 }
332
333 // Check keyID is honored.
334 if req.KeyID != resp.KeyID {
335 return nil, nil, fmt.Errorf("keyID in generateSignature response %q does not match request %q", resp.KeyID, req.KeyID)
336 }
337
338 var certs []*x509.Certificate
339 if certs, err = parseCertChain(resp.CertificateChain); err != nil {
340 return nil, nil, err
341 }
342 return resp.Signature, certs, nil
343 }
344
345 // KeySpec returns the keySpec of a keyID by calling describeKey and do some
346 // keySpec validation.
347 func (s *pluginPrimitiveSigner) KeySpec() (signature.KeySpec, error) {
348 return s.keySpec, nil
349 }