Skip to content

Commit 58ae149

Browse files
authored
Fix spec violations in policy, EKU, and hash verification (#1375)
To prevent clients from specifying their own TSA policy OIDs, obtaining signatures over arbitrary extensions, and utilizing weak digests, this change: * Introduces server flags for default/accepted policy OIDs and custom extensions * Configures server-side validation to reject unauthorized policy OIDs and custom request extensions by default * Updates client-side verification to build paths including TSR-embedded intermediates and enforce EKU chaining constraints on every intermediate CA * Configures client-side verification to reject SHA-1, which is the server already does Signed-off-by: Hayden <[email protected]>
1 parent 506ec57 commit 58ae149

10 files changed

Lines changed: 320 additions & 90 deletions

File tree

‎cmd/timestamp-server/app/root.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,10 @@ func init() {
8686
rootCmd.PersistentFlags().Uint64("max-request-body-size", 1048576, "Maximum allowed size for request bodies in bytes (1MB by default)")
8787
rootCmd.PersistentFlags().Duration("cleanup-timeout", 620*time.Second, "grace period for which to wait before killing idle connections")
8888

89+
rootCmd.PersistentFlags().String("default-policy-oid", "1.3.6.1.4.1.57264.2", "Default policy OID to use if none is specified in the request")
90+
rootCmd.PersistentFlags().StringSlice("accepted-policy-oids", []string{"1.3.6.1.4.1.57264.2"}, "List of policy OIDs accepted in timestamp requests")
91+
rootCmd.PersistentFlags().Bool("allow-custom-extensions", false, "Whether to allow and copy custom request extensions into the signed timestamp")
92+
8993
if err := viper.BindPFlags(rootCmd.PersistentFlags()); err != nil {
9094
log.Logger.Fatal(err)
9195
}

‎pkg/api/api.go‎

Lines changed: 51 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,12 @@ import (
2020
"context"
2121
"crypto"
2222
"crypto/x509"
23+
"encoding/asn1"
2324
"fmt"
2425
"os"
2526
"path/filepath"
27+
"strconv"
28+
"strings"
2629

2730
"github.com/pkg/errors"
2831
"github.com/spf13/viper"
@@ -34,12 +37,30 @@ import (
3437
)
3538

3639
type API struct {
37-
tsaSigner crypto.Signer // the signer to use for timestamping
38-
tsaSignerHash crypto.Hash // hash algorithm used to hash pre-signed timestamps
39-
certChain []*x509.Certificate // timestamping cert chain
40-
certChainPem string // PEM encoded timestamping cert chain
41-
includeChain bool // Whether to include the full issuing chain or just the leaf certificate
42-
useHTTP201 bool // Whether to use HTTP 201 Created instead of HTTP 200 OK for timestamp responses
40+
tsaSigner crypto.Signer // the signer to use for timestamping
41+
tsaSignerHash crypto.Hash // hash algorithm used to hash pre-signed timestamps
42+
certChain []*x509.Certificate // timestamping cert chain
43+
certChainPem string // PEM encoded timestamping cert chain
44+
includeChain bool // Whether to include the full issuing chain or just the leaf certificate
45+
useHTTP201 bool // Whether to use HTTP 201 Created instead of HTTP 200 OK for timestamp responses
46+
defaultPolicyOID asn1.ObjectIdentifier // Default policy OID to use if none is specified in the request
47+
acceptedPolicyOIDs []asn1.ObjectIdentifier // List of policy OIDs accepted in timestamp requests
48+
allowCustomExtensions bool // Whether to allow and copy custom request extensions into the signed timestamp
49+
}
50+
51+
func parseOID(oidStr string) (asn1.ObjectIdentifier, error) {
52+
var oid asn1.ObjectIdentifier
53+
if c := strings.Count(oidStr, "."); c > 128 {
54+
return nil, fmt.Errorf("oid has too many sub identifiers")
55+
}
56+
for _, v := range strings.SplitN(oidStr, ".", 129) {
57+
i, err := strconv.Atoi(v)
58+
if err != nil {
59+
return nil, fmt.Errorf("failed to parse OID component %q: %w", v, err)
60+
}
61+
oid = append(oid, i)
62+
}
63+
return oid, nil
4364
}
4465

4566
func NewAPI() (*API, error) {
@@ -88,13 +109,31 @@ func NewAPI() (*API, error) {
88109
return nil, fmt.Errorf("marshal certificates to PEM: %w", err)
89110
}
90111

112+
defaultPolicyOIDStr := viper.GetString("default-policy-oid")
113+
defaultPolicyOID, err := parseOID(defaultPolicyOIDStr)
114+
if err != nil {
115+
return nil, fmt.Errorf("failed to parse default policy OID %q: %w", defaultPolicyOIDStr, err)
116+
}
117+
118+
var acceptedPolicyOIDs []asn1.ObjectIdentifier
119+
for _, oidStr := range viper.GetStringSlice("accepted-policy-oids") {
120+
oid, err := parseOID(oidStr)
121+
if err != nil {
122+
return nil, fmt.Errorf("failed to parse accepted policy OID %q: %w", oidStr, err)
123+
}
124+
acceptedPolicyOIDs = append(acceptedPolicyOIDs, oid)
125+
}
126+
91127
return &API{
92-
tsaSigner: tsaSigner,
93-
tsaSignerHash: tsaSignerHash,
94-
certChain: certChain,
95-
certChainPem: string(certChainPEM),
96-
includeChain: viper.GetBool("include-chain-in-response"),
97-
useHTTP201: viper.GetBool("use-http-201"),
128+
tsaSigner: tsaSigner,
129+
tsaSignerHash: tsaSignerHash,
130+
certChain: certChain,
131+
certChainPem: string(certChainPEM),
132+
includeChain: viper.GetBool("include-chain-in-response"),
133+
useHTTP201: viper.GetBool("use-http-201"),
134+
defaultPolicyOID: defaultPolicyOID,
135+
acceptedPolicyOIDs: acceptedPolicyOIDs,
136+
allowCustomExtensions: viper.GetBool("allow-custom-extensions"),
98137
}, nil
99138
}
100139

‎pkg/api/error.go‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ const (
3232
excesssivelyLongOID = "OID should be comprised of at most 128 components"
3333
WeakHashAlgorithmTimestampRequest = "Weak hash algorithm in timestamp request"
3434
InconsistentDigestLengthTimestampRequest = "Message digest has incorrect length for specified algorithm"
35+
UnacceptedPolicyTimestampRequest = "unaccepted policy: requested TSA policy is not supported by the TSA"
36+
UnacceptedExtensionTimestampRequest = "unaccepted extension: requested extensions are not supported by the TSA"
3537
)
3638

3739
func errorMsg(message string, code int) *models.Error {

‎pkg/api/timestamp.go‎

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,13 @@ package api
1717
import (
1818
"bytes"
1919
"crypto"
20-
"encoding/asn1"
2120
"encoding/base64"
2221
"encoding/json"
2322
"fmt"
2423
"io"
2524
"math/big"
2625
"net/http"
27-
"strconv"
26+
"slices"
2827
"strings"
2928
"time"
3029

@@ -78,14 +77,10 @@ func ParseJSONRequest(reqBytes []byte) (*timestamp.Request, string, error) {
7877
if req.TSAPolicyOID == "" {
7978
oidInts = nil
8079
} else {
81-
// 128 is the max number of sub-identifiers per
82-
// https://datatracker.ietf.org/doc/html/rfc2578#section-3.5
83-
if c := strings.Count(req.TSAPolicyOID, "."); c > 128 {
84-
return nil, excesssivelyLongOID, fmt.Errorf("oid has %d sub identifiers, expected 128", c)
85-
}
86-
for _, v := range strings.SplitN(req.TSAPolicyOID, ".", 129) {
87-
i, _ := strconv.Atoi(v)
88-
oidInts = append(oidInts, i)
80+
var err error
81+
oidInts, err = parseOID(req.TSAPolicyOID)
82+
if err != nil {
83+
return nil, excesssivelyLongOID, err
8984
}
9085
}
9186

@@ -157,7 +152,7 @@ func TimestampResponseHandler(params ts.GetTimestampResponseParams) middleware.R
157152

158153
policyID := req.TSAPolicyOID
159154
if policyID.String() == "" {
160-
policyID = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 57264, 2}
155+
policyID = api.defaultPolicyOID
161156
}
162157

163158
duration, _ := time.ParseDuration("1s")
@@ -215,5 +210,16 @@ func verifyTimestampRequest(tsReq *timestamp.Request) (*timestamp.Request, strin
215210
return nil, failedToGenerateTimestampResponse, err
216211
}
217212

213+
if len(tsReq.TSAPolicyOID) > 0 {
214+
matched := slices.ContainsFunc(api.acceptedPolicyOIDs, tsReq.TSAPolicyOID.Equal)
215+
if !matched {
216+
return nil, UnacceptedPolicyTimestampRequest, verification.ErrUnacceptedPolicy
217+
}
218+
}
219+
220+
if !api.allowCustomExtensions && len(tsReq.Extensions) > 0 {
221+
return nil, UnacceptedExtensionTimestampRequest, verification.ErrUnacceptedExtension
222+
}
223+
218224
return tsReq, "", nil
219225
}

‎pkg/generated/restapi/configure_timestamp_server.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ func limitRequestBody(next http.Handler) http.Handler {
135135
if maxRequestBodySize > uint64(math.MaxInt64) {
136136
log.Logger.Fatalf("max-request-body-size (%v) exceeds supported maximum (%v)", maxRequestBodySize, maxInt64Limit)
137137
}
138-
// #nosec G115
138+
// #nosec G115 - checked above to ensure no overflow
139139
r.Body = http.MaxBytesReader(w, r.Body, int64(maxRequestBodySize))
140140
} else {
141141
log.Logger.Debug("max-request-body-size is set to 0; no limit will be enforced on request body sizes")

‎pkg/tests/api_test.go‎

Lines changed: 110 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"crypto/sha256"
2121
"crypto/x509/pkix"
2222
"encoding/asn1"
23+
"encoding/base64"
2324
"encoding/json"
2425
"io"
2526
"math/big"
@@ -267,60 +268,124 @@ func TestGetTimestampResponseWithExtsAndOID(t *testing.T) {
267268
}
268269

269270
for _, tc := range tests {
270-
url := createServer(t)
271+
t.Run(tc.name+" Default Deny", func(t *testing.T) {
272+
url := createServer(t)
271273

272-
c, err := client.GetTimestampClient(url, client.WithContentType(tc.reqMediaType))
273-
if err != nil {
274-
t.Fatalf("test '%s': unexpected error creating client: %v", tc.name, err)
275-
}
274+
c, err := client.GetTimestampClient(url, client.WithContentType(tc.reqMediaType))
275+
if err != nil {
276+
t.Fatalf("unexpected error creating client: %v", err)
277+
}
276278

277-
// populate additional request parameters for extensions and OID - atypical request structure
278-
var req *ts.Request
279-
if tc.reqMediaType == client.TimestampQueryMediaType {
280-
req, err = ts.ParseRequest(tc.reqBytes)
279+
// populate additional request parameters for extensions and OID - atypical request structure
280+
var req *ts.Request
281+
if tc.reqMediaType == client.TimestampQueryMediaType {
282+
req, err = ts.ParseRequest(tc.reqBytes)
283+
if err != nil {
284+
t.Fatalf("unexpected error parsing request: %v", err)
285+
}
286+
} else {
287+
var jsonReq api.JSONRequest
288+
if err := json.Unmarshal(tc.reqBytes, &jsonReq); err != nil {
289+
t.Fatalf("unexpected error unmarshalling request: %v", err)
290+
}
291+
decoded, _ := base64.StdEncoding.DecodeString(jsonReq.ArtifactHash)
292+
req = &ts.Request{
293+
HashAlgorithm: crypto.SHA256,
294+
HashedMessage: decoded,
295+
Certificates: jsonReq.Certificates,
296+
Nonce: jsonReq.Nonce,
297+
}
298+
}
299+
req.ExtraExtensions = []pkix.Extension{{Id: asn1.ObjectIdentifier{1, 2, 3, 4}, Value: []byte{1, 2, 3, 4}}}
300+
fakePolicyOID := asn1.ObjectIdentifier{1, 2, 3, 4, 5}
301+
req.TSAPolicyOID = fakePolicyOID
302+
tsq, err := req.Marshal()
281303
if err != nil {
282-
t.Fatalf("test '%s': unexpected error parsing request: %v", tc.name, err)
304+
t.Fatalf("unexpected error creating request: %v", err)
283305
}
284-
} else {
285-
req, _, err = api.ParseJSONRequest(tc.reqBytes)
306+
307+
params := timestamp.NewGetTimestampResponseParams()
308+
params.SetTimeout(10 * time.Second)
309+
params.Request = io.NopCloser(bytes.NewReader(tsq))
310+
311+
var respBytes bytes.Buffer
312+
clientOption := func(op *runtime.ClientOperation) {
313+
op.ConsumesMediaTypes = []string{client.TimestampQueryMediaType}
314+
}
315+
_, _, err = c.Timestamp.GetTimestampResponse(params, &respBytes, clientOption)
316+
if err == nil {
317+
t.Fatalf("expected error when requesting unaccepted policy/extensions")
318+
}
319+
if !strings.Contains(err.Error(), "unaccepted policy") {
320+
t.Fatalf("expected unaccepted policy error, got: %v", err)
321+
}
322+
})
323+
324+
t.Run(tc.name+" Allowed via Config", func(t *testing.T) {
325+
url := createServer(t, func() {
326+
viper.Set("accepted-policy-oids", []string{"1.3.6.1.4.1.57264.2", "1.2.3.4.5"})
327+
viper.Set("allow-custom-extensions", true)
328+
})
329+
330+
c, err := client.GetTimestampClient(url, client.WithContentType(tc.reqMediaType))
286331
if err != nil {
287-
t.Fatalf("test '%s': unexpected error parsing request: %v", tc.name, err)
332+
t.Fatalf("unexpected error creating client: %v", err)
288333
}
289-
}
290-
req.ExtraExtensions = []pkix.Extension{{Id: asn1.ObjectIdentifier{1, 2, 3, 4}, Value: []byte{1, 2, 3, 4}}}
291-
fakePolicyOID := asn1.ObjectIdentifier{1, 2, 3, 4, 5}
292-
req.TSAPolicyOID = fakePolicyOID
293-
tsq, err := req.Marshal()
294-
if err != nil {
295-
t.Fatalf("test '%s': unexpected error creating request: %v", tc.name, err)
296-
}
297334

298-
params := timestamp.NewGetTimestampResponseParams()
299-
params.SetTimeout(10 * time.Second)
300-
params.Request = io.NopCloser(bytes.NewReader(tsq))
335+
var req *ts.Request
336+
if tc.reqMediaType == client.TimestampQueryMediaType {
337+
req, err = ts.ParseRequest(tc.reqBytes)
338+
if err != nil {
339+
t.Fatalf("unexpected error parsing request: %v", err)
340+
}
341+
} else {
342+
var jsonReq api.JSONRequest
343+
if err := json.Unmarshal(tc.reqBytes, &jsonReq); err != nil {
344+
t.Fatalf("unexpected error unmarshalling request: %v", err)
345+
}
346+
decoded, _ := base64.StdEncoding.DecodeString(jsonReq.ArtifactHash)
347+
req = &ts.Request{
348+
HashAlgorithm: crypto.SHA256,
349+
HashedMessage: decoded,
350+
Certificates: jsonReq.Certificates,
351+
Nonce: jsonReq.Nonce,
352+
}
353+
}
354+
req.ExtraExtensions = []pkix.Extension{{Id: asn1.ObjectIdentifier{1, 2, 3, 4}, Value: []byte{1, 2, 3, 4}}}
355+
fakePolicyOID := asn1.ObjectIdentifier{1, 2, 3, 4, 5}
356+
req.TSAPolicyOID = fakePolicyOID
357+
tsq, err := req.Marshal()
358+
if err != nil {
359+
t.Fatalf("unexpected error creating request: %v", err)
360+
}
301361

302-
var respBytes bytes.Buffer
303-
clientOption := func(op *runtime.ClientOperation) {
304-
op.ConsumesMediaTypes = []string{client.TimestampQueryMediaType}
305-
}
306-
_, _, err = c.Timestamp.GetTimestampResponse(params, &respBytes, clientOption)
307-
if err != nil {
308-
t.Fatalf("test '%s': unexpected error getting timestamp response: %v", tc.name, err)
309-
}
362+
params := timestamp.NewGetTimestampResponseParams()
363+
params.SetTimeout(10 * time.Second)
364+
params.Request = io.NopCloser(bytes.NewReader(tsq))
310365

311-
tsr, err := ts.ParseResponse(respBytes.Bytes())
312-
if err != nil {
313-
t.Fatalf("test '%s': unexpected error parsing response: %v", tc.name, err)
314-
}
366+
var respBytes bytes.Buffer
367+
clientOption := func(op *runtime.ClientOperation) {
368+
op.ConsumesMediaTypes = []string{client.TimestampQueryMediaType}
369+
}
370+
_, _, err = c.Timestamp.GetTimestampResponse(params, &respBytes, clientOption)
371+
if err != nil {
372+
t.Fatalf("unexpected error getting timestamp response: %v", err)
373+
}
315374

316-
// check policy OID
317-
if !tsr.Policy.Equal(fakePolicyOID) {
318-
t.Fatalf("test '%s': unexpected policy ID", tc.name)
319-
}
320-
// check extension is present
321-
if len(tsr.Extensions) != 1 {
322-
t.Fatalf("test '%s': expected 1 extension, got %d", tc.name, len(tsr.Extensions))
323-
}
375+
tsr, err := ts.ParseResponse(respBytes.Bytes())
376+
if err != nil {
377+
t.Fatalf("unexpected error parsing response: %v", err)
378+
}
379+
380+
// check policy OID
381+
if !tsr.Policy.Equal(fakePolicyOID) {
382+
t.Fatalf("unexpected policy ID")
383+
}
384+
// check extension is present
385+
if len(tsr.Extensions) != 1 {
386+
t.Fatalf("expected 1 extension, got %d", len(tsr.Extensions))
387+
}
388+
})
324389
}
325390
}
326391

@@ -329,7 +394,7 @@ func TestGetTimestampResponseWithNoCertificateOrNonce(t *testing.T) {
329394
includeCerts := false
330395
hashFunc := crypto.SHA256
331396
hashName := "sha256"
332-
oidStr := "1.2.3.4"
397+
oidStr := "1.3.6.1.4.1.57264.2"
333398

334399
opts := ts.RequestOptions{
335400
Certificates: includeCerts,

‎pkg/tests/server.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@ import (
2929
func createServer(t *testing.T, flagsToSet ...func()) string {
3030
viper.Set("timestamp-signer", "memory")
3131
viper.Set("timestamp-signer-hash", "sha256")
32+
viper.Set("accepted-policy-oids", []string{"1.3.6.1.4.1.57264.2"})
33+
viper.Set("allow-custom-extensions", false)
34+
viper.Set("default-policy-oid", "1.3.6.1.4.1.57264.2")
3235
for _, flag := range flagsToSet {
3336
flag()
3437
}

0 commit comments

Comments
 (0)