Debian Codegraph @

ietf-cms/timestamp/timestamp.go

raw symbols SCIP
1 package timestamp
2
3 import (
4 "bytes"
5 "crypto"
6 "crypto/rand"
7 "crypto/x509/pkix"
8 "encoding/asn1"
9 "fmt"
10 "io"
11 "math/big"
12 "net/http"
13 "strings"
14 "time"
15
16 "github.com/github/smimesign/ietf-cms/oid"
17 "github.com/github/smimesign/ietf-cms/protocol"
18 )
19
20 // HTTPClient is an interface for *http.Client, allowing callers to customize
21 // HTTP behavior.
22 type HTTPClient interface {
23 Do(*http.Request) (*http.Response, error)
24 }
25
26 // DefaultHTTPClient is the HTTP client used for fetching timestamps. This
27 // variable may be changed to modify HTTP behavior (eg. add timeouts).
28 var DefaultHTTPClient = HTTPClient(http.DefaultClient)
29
30 const (
31 contentTypeTSQuery = "application/timestamp-query"
32 contentTypeTSReply = "application/timestamp-reply"
33 nonceBytes = 16
34 )
35
36 // GenerateNonce generates a new nonce for this TSR.
37 func GenerateNonce() *big.Int {
38 buf := make([]byte, nonceBytes)
39 if _, err := rand.Read(buf); err != nil {
40 panic(err)
41 }
42
43 return new(big.Int).SetBytes(buf[:])
44 }
45
46 // Request is a TimeStampReq
47 // TimeStampReq ::= SEQUENCE {
48 // version INTEGER { v1(1) },
49 // messageImprint MessageImprint,
50 // --a hash algorithm OID and the hash value of the data to be
51 // --time-stamped
52 // reqPolicy TSAPolicyId OPTIONAL,
53 // nonce INTEGER OPTIONAL,
54 // certReq BOOLEAN DEFAULT FALSE,
55 // extensions [0] IMPLICIT Extensions OPTIONAL }
56 type Request struct {
57 Version int
58 MessageImprint MessageImprint
59 ReqPolicy asn1.ObjectIdentifier `asn1:"optional"`
60 Nonce *big.Int `asn1:"optional"`
61 CertReq bool `asn1:"optional,default:false"`
62 Extensions []pkix.Extension `asn1:"tag:1,optional"`
63 }
64
65 // Matches checks if the MessageImprint and Nonce from a responsee match those
66 // of the request.
67 func (req Request) Matches(tsti Info) bool {
68 if !req.MessageImprint.Equal(tsti.MessageImprint) {
69 return false
70 }
71
72 if req.Nonce != nil && tsti.Nonce == nil || req.Nonce.Cmp(tsti.Nonce) != 0 {
73 return false
74 }
75
76 return true
77 }
78
79 // Do sends this timestamp request to the specified timestamp service, returning
80 // the parsed response. The timestamp.HTTPClient is used to make the request and
81 // HTTP behavior can be modified by changing that variable.
82 func (req Request) Do(url string) (Response, error) {
83 var nilResp Response
84
85 reqDER, err := asn1.Marshal(req)
86 if err != nil {
87 return nilResp, err
88 }
89
90 httpReq, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(reqDER))
91 if err != nil {
92 return nilResp, err
93 }
94 httpReq.Header.Add("Content-Type", contentTypeTSQuery)
95
96 httpResp, err := DefaultHTTPClient.Do(httpReq)
97 if err != nil {
98 return nilResp, err
99 }
100 if ct := httpResp.Header.Get("Content-Type"); ct != contentTypeTSReply {
101 return nilResp, fmt.Errorf("Bad content-type: %s", ct)
102 }
103
104 buf := bytes.NewBuffer(make([]byte, 0, httpResp.ContentLength))
105 if _, err = io.Copy(buf, httpResp.Body); err != nil {
106 return nilResp, err
107 }
108
109 return ParseResponse(buf.Bytes())
110 }
111
112 // Response is a TimeStampResp
113 // TimeStampResp ::= SEQUENCE {
114 // status PKIStatusInfo,
115 // timeStampToken TimeStampToken OPTIONAL }
116 //
117 // TimeStampToken ::= ContentInfo
118 type Response struct {
119 Status PKIStatusInfo
120 TimeStampToken protocol.ContentInfo `asn1:"optional"`
121 }
122
123 // ParseResponse parses a BER encoded TimeStampResp.
124 func ParseResponse(ber []byte) (Response, error) {
125 var resp Response
126
127 der, err := protocol.BER2DER(ber)
128 if err != nil {
129 return resp, err
130 }
131
132 rest, err := asn1.Unmarshal(der, &resp)
133 if err != nil {
134 return resp, err
135 }
136 if len(rest) > 0 {
137 return resp, protocol.ErrTrailingData
138 }
139
140 return resp, nil
141 }
142
143 // Info gets an Info from the response, doing no validation of the SignedData.
144 func (r Response) Info() (Info, error) {
145 var nilInfo Info
146
147 if err := r.Status.GetError(); err != nil {
148 return nilInfo, err
149 }
150
151 sd, err := r.TimeStampToken.SignedDataContent()
152 if err != nil {
153 return nilInfo, err
154 }
155
156 return ParseInfo(sd.EncapContentInfo)
157 }
158
159 // PKIStatusInfo ::= SEQUENCE {
160 // status PKIStatus,
161 // statusString PKIFreeText OPTIONAL,
162 // failInfo PKIFailureInfo OPTIONAL }
163 //
164 // PKIStatus ::= INTEGER {
165 // granted (0),
166 // -- when the PKIStatus contains the value zero a TimeStampToken, as
167 // requested, is present.
168 // grantedWithMods (1),
169 // -- when the PKIStatus contains the value one a TimeStampToken,
170 // with modifications, is present.
171 // rejection (2),
172 // waiting (3),
173 // revocationWarning (4),
174 // -- this message contains a warning that a revocation is
175 // -- imminent
176 // revocationNotification (5)
177 // -- notification that a revocation has occurred }
178 //
179 // -- When the TimeStampToken is not present
180 // -- failInfo indicates the reason why the
181 // -- time-stamp request was rejected and
182 // -- may be one of the following values.
183 //
184 // PKIFailureInfo ::= BIT STRING {
185 // badAlg (0),
186 // -- unrecognized or unsupported Algorithm Identifier
187 // badRequest (2),
188 // -- transaction not permitted or supported
189 // badDataFormat (5),
190 // -- the data submitted has the wrong format
191 // timeNotAvailable (14),
192 // -- the TSA's time source is not available
193 // unacceptedPolicy (15),
194 // -- the requested TSA policy is not supported by the TSA.
195 // unacceptedExtension (16),
196 // -- the requested extension is not supported by the TSA.
197 // addInfoNotAvailable (17)
198 // -- the additional information requested could not be understood
199 // -- or is not available
200 // systemFailure (25)
201 // -- the request cannot be handled due to system failure }
202 type PKIStatusInfo struct {
203 Status int
204 StatusString PKIFreeText `asn1:"optional"`
205 FailInfo asn1.BitString `asn1:"optional"`
206 }
207
208 // Error represents an unsuccessful PKIStatusInfo as an error.
209 func (si PKIStatusInfo) GetError() error {
210 if si.Status == 0 {
211 return nil
212 }
213 return si
214 }
215
216 // Error implements the error interface.
217 func (si PKIStatusInfo) Error() string {
218 fiStr := ""
219 if si.FailInfo.BitLength > 0 {
220 fibin := make([]byte, si.FailInfo.BitLength)
221 for i := range fibin {
222 if si.FailInfo.At(i) == 1 {
223 fibin[i] = byte('1')
224 } else {
225 fibin[i] = byte('0')
226 }
227 }
228 fiStr = fmt.Sprintf(" FailInfo(0b%s)", string(fibin))
229 }
230
231 statusStr := ""
232 if len(si.StatusString) > 0 {
233 if strs, err := si.StatusString.Strings(); err == nil {
234 statusStr = fmt.Sprintf(" StatusString(%s)", strings.Join(strs, ","))
235 }
236 }
237
238 return fmt.Sprintf("Bad TimeStampResp: Status(%d)%s%s", si.Status, statusStr, fiStr)
239 }
240
241 // PKIFreeText ::= SEQUENCE SIZE (1..MAX) OF UTF8String
242 type PKIFreeText []asn1.RawValue
243
244 // Append returns a new copy of the PKIFreeText with the provided string
245 // appended.
246 func (ft PKIFreeText) Append(t string) PKIFreeText {
247 return append(ft, asn1.RawValue{
248 Class: asn1.ClassUniversal,
249 Tag: asn1.TagUTF8String,
250 Bytes: []byte(t),
251 })
252 }
253
254 // Strings decodes the PKIFreeText into a []string.
255 func (ft PKIFreeText) Strings() ([]string, error) {
256 strs := make([]string, len(ft))
257
258 for i := range ft {
259 if rest, err := asn1.Unmarshal(ft[i].FullBytes, &strs[i]); err != nil {
260 return nil, err
261 } else if len(rest) != 0 {
262 return nil, protocol.ErrTrailingData
263 }
264 }
265
266 return strs, nil
267 }
268
269 // Info is a TSTInfo
270 // TSTInfo ::= SEQUENCE {
271 // version INTEGER { v1(1) },
272 // policy TSAPolicyId,
273 // messageImprint MessageImprint,
274 // -- MUST have the same value as the similar field in
275 // -- TimeStampReq
276 // serialNumber INTEGER,
277 // -- Time-Stamping users MUST be ready to accommodate integers
278 // -- up to 160 bits.
279 // genTime GeneralizedTime,
280 // accuracy Accuracy OPTIONAL,
281 // ordering BOOLEAN DEFAULT FALSE,
282 // nonce INTEGER OPTIONAL,
283 // -- MUST be present if the similar field was present
284 // -- in TimeStampReq. In that case it MUST have the same value.
285 // tsa [0] GeneralName OPTIONAL,
286 // extensions [1] IMPLICIT Extensions OPTIONAL }
287 //
288 // TSAPolicyId ::= OBJECT IDENTIFIER
289 type Info struct {
290 Version int
291 Policy asn1.ObjectIdentifier
292 MessageImprint MessageImprint
293 SerialNumber *big.Int
294 GenTime time.Time `asn1:"generalized"`
295 Accuracy Accuracy `asn1:"optional"`
296 Ordering bool `asn1:"optional,default:false"`
297 Nonce *big.Int `asn1:"optional"`
298 TSA asn1.RawValue `asn1:"tag:0,optional"`
299 Extensions []pkix.Extension `asn1:"tag:1,optional"`
300 }
301
302 // ParseInfo parses an Info out of a CMS EncapsulatedContentInfo.
303 func ParseInfo(eci protocol.EncapsulatedContentInfo) (Info, error) {
304 i := Info{}
305
306 if !eci.EContentType.Equal(oid.ContentTypeTSTInfo) {
307 return i, protocol.ErrWrongType
308 }
309
310 ecval, err := eci.EContentValue()
311 if err != nil {
312 return i, err
313 }
314 if ecval == nil {
315 return i, protocol.ASN1Error{Message: "missing EContent for non data type"}
316 }
317
318 if rest, err := asn1.Unmarshal(ecval, &i); err != nil {
319 return i, err
320 } else if len(rest) > 0 {
321 return i, protocol.ErrTrailingData
322 }
323
324 return i, nil
325 }
326
327 // Before checks if the latest time the signature could have been generated at
328 // is before the specified time. For example, you might check that a signature
329 // was made *before* a certificate's not-after date.
330 func (i *Info) Before(t time.Time) bool {
331 return i.genTimeMax().Before(t)
332 }
333
334 // After checks if the earlier time the signature could have been generated at
335 // is before the specified time. For example, you might check that a signature
336 // was made *after* a certificate's not-before date.
337 func (i *Info) After(t time.Time) bool {
338 return i.genTimeMin().After(t)
339 }
340
341 // genTimeMax is the latest time at which the token could have been generated
342 // based on the included GenTime and Accuracy attributes.
343 func (i *Info) genTimeMax() time.Time {
344 return i.GenTime.Add(i.Accuracy.Duration())
345 }
346
347 // genTimeMin is the earliest time at which the token could have been generated
348 // based on the included GenTime and Accuracy attributes.
349 func (i *Info) genTimeMin() time.Time {
350 return i.GenTime.Add(-i.Accuracy.Duration())
351 }
352
353 // MessageImprint ::= SEQUENCE {
354 // hashAlgorithm AlgorithmIdentifier,
355 // hashedMessage OCTET STRING }
356 type MessageImprint struct {
357 HashAlgorithm pkix.AlgorithmIdentifier
358 HashedMessage []byte
359 }
360
361 // NewMessageImprint creates a new MessageImprint, digesting all bytes from the
362 // provided reader using the specified hash.
363 func NewMessageImprint(hash crypto.Hash, r io.Reader) (MessageImprint, error) {
364 digestAlgorithm := oid.CryptoHashToDigestAlgorithm[hash]
365 if len(digestAlgorithm) == 0 {
366 return MessageImprint{}, protocol.ErrUnsupported
367 }
368
369 if !hash.Available() {
370 return MessageImprint{}, protocol.ErrUnsupported
371 }
372 h := hash.New()
373 if _, err := io.Copy(h, r); err != nil {
374 return MessageImprint{}, err
375 }
376
377 return MessageImprint{
378 HashAlgorithm: pkix.AlgorithmIdentifier{Algorithm: digestAlgorithm},
379 HashedMessage: h.Sum(nil),
380 }, nil
381 }
382
383 // Hash gets the crypto.Hash associated with this SignerInfo's DigestAlgorithm.
384 // 0 is returned for unrecognized algorithms.
385 func (mi MessageImprint) Hash() (crypto.Hash, error) {
386 algo := mi.HashAlgorithm.Algorithm.String()
387 hash := oid.DigestAlgorithmToCryptoHash[algo]
388 if hash == 0 || !hash.Available() {
389 return 0, protocol.ErrUnsupported
390 }
391
392 return hash, nil
393 }
394
395 // Equal checks if this MessageImprint is identical to another MessageImprint.
396 func (mi MessageImprint) Equal(other MessageImprint) bool {
397 if !mi.HashAlgorithm.Algorithm.Equal(other.HashAlgorithm.Algorithm) {
398 return false
399 }
400 if len(mi.HashAlgorithm.Parameters.Bytes) > 0 || len(other.HashAlgorithm.Parameters.Bytes) > 0 {
401 if !bytes.Equal(mi.HashAlgorithm.Parameters.FullBytes, other.HashAlgorithm.Parameters.FullBytes) {
402 return false
403 }
404 }
405 if !bytes.Equal(mi.HashedMessage, other.HashedMessage) {
406 return false
407 }
408 return true
409 }
410
411 // Accuracy ::= SEQUENCE {
412 // seconds INTEGER OPTIONAL,
413 // millis [0] INTEGER (1..999) OPTIONAL,
414 // micros [1] INTEGER (1..999) OPTIONAL }
415 type Accuracy struct {
416 Seconds int `asn1:"optional"`
417 Millis int `asn1:"tag:0,optional"`
418 Micros int `asn1:"tag:1,optional"`
419 }
420
421 // Duration returns this Accuracy as a time.Duration.
422 func (a Accuracy) Duration() time.Duration {
423 return 0 +
424 time.Duration(a.Seconds)*time.Second +
425 time.Duration(a.Millis)*time.Millisecond +
426 time.Duration(a.Micros)*time.Microsecond
427 }