| 1 |
package rekor |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"crypto/sha256" |
| 6 |
"encoding/base64" |
| 7 |
"encoding/hex" |
| 8 |
"encoding/json" |
| 9 |
"errors" |
| 10 |
"fmt" |
| 11 |
"net/http" |
| 12 |
"net/url" |
| 13 |
"strings" |
| 14 |
|
| 15 |
"github.com/hashicorp/go-cleanhttp" |
| 16 |
"github.com/hashicorp/go-retryablehttp" |
| 17 |
"github.com/sirupsen/logrus" |
| 18 |
"go.podman.io/image/v5/signature/internal" |
| 19 |
signerInternal "go.podman.io/image/v5/signature/sigstore/internal" |
| 20 |
) |
| 21 |
|
| 22 |
const ( |
| 23 |
// defaultRetryCount is the default number of retries |
| 24 |
defaultRetryCount = 3 |
| 25 |
) |
| 26 |
|
| 27 |
// WithRekor asks the generated signature to be uploaded to the specified Rekor server, |
| 28 |
// and to include a log inclusion proof in the signature. |
| 29 |
func WithRekor(rekorURL *url.URL) signerInternal.Option { |
| 30 |
return func(s *signerInternal.SigstoreSigner) error { |
| 31 |
logrus.Debugf("Using Rekor server at %s", rekorURL.Redacted()) |
| 32 |
client := newRekorClient(rekorURL) |
| 33 |
s.RekorUploader = client.uploadKeyOrCert |
| 34 |
return nil |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
// rekorClient allows uploading entries to Rekor. |
| 39 |
type rekorClient struct { |
| 40 |
rekorURL *url.URL // Only Scheme and Host is actually used, consistent with github.com/sigstore/rekor/pkg/client. |
| 41 |
basePath string |
| 42 |
httpClient *http.Client |
| 43 |
} |
| 44 |
|
| 45 |
// newRekorClient creates a rekorClient for rekorURL. |
| 46 |
func newRekorClient(rekorURL *url.URL) *rekorClient { |
| 47 |
retryableClient := retryablehttp.NewClient() |
| 48 |
retryableClient.HTTPClient = cleanhttp.DefaultClient() |
| 49 |
retryableClient.RetryMax = defaultRetryCount |
| 50 |
retryableClient.Logger = leveledLoggerForLogrus(logrus.StandardLogger()) |
| 51 |
basePath := rekorURL.Path |
| 52 |
if !strings.HasPrefix(basePath, "/") { // Includes basePath == "", i.e. URL just a https://hostname |
| 53 |
basePath = "/" + basePath |
| 54 |
} |
| 55 |
return &rekorClient{ |
| 56 |
rekorURL: rekorURL, |
| 57 |
basePath: basePath, |
| 58 |
httpClient: retryableClient.StandardClient(), |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
// rekorEntryToSET converts a Rekor log entry into a sigstore “signed entry timestamp”. |
| 63 |
func rekorEntryToSET(entry *rekorLogEntryAnon) (internal.UntrustedRekorSET, error) { |
| 64 |
// We could plausibly call entry.Validate() here; that mostly just uses unnecessary reflection instead of direct == nil checks. |
| 65 |
// Right now the only extra validation .Validate() does is *entry.LogIndex >= 0 and a regex check on *entry.LogID; |
| 66 |
// we don’t particularly care about either of these (notably signature verification only uses the Body value). |
| 67 |
if entry.Verification == nil || entry.IntegratedTime == nil || entry.LogIndex == nil || entry.LogID == nil { |
| 68 |
return internal.UntrustedRekorSET{}, fmt.Errorf("invalid Rekor entry (missing data): %#v", *entry) |
| 69 |
} |
| 70 |
bodyBase64, ok := entry.Body.(string) |
| 71 |
if !ok { |
| 72 |
return internal.UntrustedRekorSET{}, fmt.Errorf("unexpected Rekor entry body type: %#v", entry.Body) |
| 73 |
} |
| 74 |
body, err := base64.StdEncoding.DecodeString(bodyBase64) |
| 75 |
if err != nil { |
| 76 |
return internal.UntrustedRekorSET{}, fmt.Errorf("error parsing Rekor entry body: %w", err) |
| 77 |
} |
| 78 |
payloadJSON, err := internal.UntrustedRekorPayload{ |
| 79 |
Body: body, |
| 80 |
IntegratedTime: *entry.IntegratedTime, |
| 81 |
LogIndex: *entry.LogIndex, |
| 82 |
LogID: *entry.LogID, |
| 83 |
}.MarshalJSON() |
| 84 |
if err != nil { |
| 85 |
return internal.UntrustedRekorSET{}, err |
| 86 |
} |
| 87 |
|
| 88 |
return internal.UntrustedRekorSET{ |
| 89 |
UntrustedSignedEntryTimestamp: entry.Verification.SignedEntryTimestamp, |
| 90 |
UntrustedPayload: payloadJSON, |
| 91 |
}, nil |
| 92 |
} |
| 93 |
|
| 94 |
// uploadEntry ensures proposedEntry exists in Rekor (usually uploading it), and returns the resulting log entry. |
| 95 |
func (r *rekorClient) uploadEntry(ctx context.Context, proposedEntry rekorProposedEntry) (rekorLogEntry, error) { |
| 96 |
logrus.Debugf("Calling Rekor's CreateLogEntry") |
| 97 |
resp, err := r.createLogEntry(ctx, proposedEntry) |
| 98 |
if err != nil { |
| 99 |
// In ordinary operation, we should not get duplicate entries, because our payload contains a timestamp, |
| 100 |
// so it is supposed to be unique; and the default key format, ECDSA p256, also contains a nonce. |
| 101 |
// But conflicts can fairly easily happen during debugging and experimentation, so it pays to handle this. |
| 102 |
var conflictErr *createLogEntryConflictError |
| 103 |
if errors.As(err, &conflictErr) && conflictErr.location != "" { |
| 104 |
location := conflictErr.location |
| 105 |
logrus.Debugf("CreateLogEntry reported a conflict, location = %s", location) |
| 106 |
// We might be able to just GET the returned Location, but let’s use the formal API method. |
| 107 |
// OTOH that requires us to hard-code the URI structure… |
| 108 |
uuidDelimiter := strings.LastIndexByte(location, '/') |
| 109 |
if uuidDelimiter != -1 { // Otherwise the URI is unexpected, and fall through to the bottom |
| 110 |
uuid := location[uuidDelimiter+1:] |
| 111 |
logrus.Debugf("Calling Rekor's NewGetLogEntryByUUIDParamsWithContext") |
| 112 |
resp2, err := r.getLogEntryByUUID(ctx, uuid) |
| 113 |
if err != nil { |
| 114 |
return nil, fmt.Errorf("Error re-loading previously-created log entry with UUID %s: %w", uuid, err) |
| 115 |
} |
| 116 |
return resp2, nil |
| 117 |
} |
| 118 |
} |
| 119 |
return nil, fmt.Errorf("Error uploading a log entry: %w", err) |
| 120 |
} |
| 121 |
return resp, nil |
| 122 |
} |
| 123 |
|
| 124 |
// stringPointer is a helper to create *string fields in JSON data. |
| 125 |
func stringPointer(s string) *string { |
| 126 |
return &s |
| 127 |
} |
| 128 |
|
| 129 |
// uploadKeyOrCert integrates this code into sigstore/internal.Signer. |
| 130 |
// Given components of the created signature, it returns a SET that should be added to the signature. |
| 131 |
func (r *rekorClient) uploadKeyOrCert(ctx context.Context, keyOrCertBytes []byte, signatureBytes []byte, payloadBytes []byte) ([]byte, error) { |
| 132 |
payloadHash := sha256.Sum256(payloadBytes) // Consistent with cosign. |
| 133 |
hashedRekordSpec, err := json.Marshal(internal.RekorHashedrekordV001Schema{ |
| 134 |
Data: &internal.RekorHashedrekordV001SchemaData{ |
| 135 |
Hash: &internal.RekorHashedrekordV001SchemaDataHash{ |
| 136 |
Algorithm: stringPointer(internal.RekorHashedrekordV001SchemaDataHashAlgorithmSha256), |
| 137 |
Value: stringPointer(hex.EncodeToString(payloadHash[:])), |
| 138 |
}, |
| 139 |
}, |
| 140 |
Signature: &internal.RekorHashedrekordV001SchemaSignature{ |
| 141 |
Content: signatureBytes, |
| 142 |
PublicKey: &internal.RekorHashedrekordV001SchemaSignaturePublicKey{ |
| 143 |
Content: keyOrCertBytes, |
| 144 |
}, |
| 145 |
}, |
| 146 |
}) |
| 147 |
if err != nil { |
| 148 |
return nil, err |
| 149 |
} |
| 150 |
proposedEntry := internal.RekorHashedrekord{ |
| 151 |
APIVersion: stringPointer(internal.RekorHashedRekordV001APIVersion), |
| 152 |
Spec: hashedRekordSpec, |
| 153 |
} |
| 154 |
|
| 155 |
uploadedPayload, err := r.uploadEntry(ctx, &proposedEntry) |
| 156 |
if err != nil { |
| 157 |
return nil, err |
| 158 |
} |
| 159 |
|
| 160 |
if len(uploadedPayload) != 1 { |
| 161 |
return nil, fmt.Errorf("expected 1 Rekor entry, got %d", len(uploadedPayload)) |
| 162 |
} |
| 163 |
var storedEntry *rekorLogEntryAnon |
| 164 |
// This “loop” extracts the single value from the uploadedPayload map. |
| 165 |
for _, p := range uploadedPayload { |
| 166 |
storedEntry = &p |
| 167 |
break |
| 168 |
} |
| 169 |
|
| 170 |
rekorBundle, err := rekorEntryToSET(storedEntry) |
| 171 |
if err != nil { |
| 172 |
return nil, err |
| 173 |
} |
| 174 |
rekorSETBytes, err := json.Marshal(rekorBundle) |
| 175 |
if err != nil { |
| 176 |
return nil, err |
| 177 |
} |
| 178 |
return rekorSETBytes, nil |
| 179 |
} |