File: jsonsign.go

package info (click to toggle)
golang-github-docker-libtrust 0.0~git20150526.0.9cbd2a1-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 288 kB
  • ctags: 297
  • sloc: makefile: 3
file content (657 lines) | stat: -rw-r--r-- 17,710 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
package libtrust

import (
	"bytes"
	"crypto"
	"crypto/x509"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"sort"
	"time"
	"unicode"
)

var (
	// ErrInvalidSignContent is used when the content to be signed is invalid.
	ErrInvalidSignContent = errors.New("invalid sign content")

	// ErrInvalidJSONContent is used when invalid json is encountered.
	ErrInvalidJSONContent = errors.New("invalid json content")

	// ErrMissingSignatureKey is used when the specified signature key
	// does not exist in the JSON content.
	ErrMissingSignatureKey = errors.New("missing signature key")
)

type jsHeader struct {
	JWK       PublicKey `json:"jwk,omitempty"`
	Algorithm string    `json:"alg"`
	Chain     []string  `json:"x5c,omitempty"`
}

type jsSignature struct {
	Header    jsHeader `json:"header"`
	Signature string   `json:"signature"`
	Protected string   `json:"protected,omitempty"`
}

type jsSignaturesSorted []jsSignature

func (jsbkid jsSignaturesSorted) Swap(i, j int) { jsbkid[i], jsbkid[j] = jsbkid[j], jsbkid[i] }
func (jsbkid jsSignaturesSorted) Len() int      { return len(jsbkid) }

func (jsbkid jsSignaturesSorted) Less(i, j int) bool {
	ki, kj := jsbkid[i].Header.JWK.KeyID(), jsbkid[j].Header.JWK.KeyID()
	si, sj := jsbkid[i].Signature, jsbkid[j].Signature

	if ki == kj {
		return si < sj
	}

	return ki < kj
}

type signKey struct {
	PrivateKey
	Chain []*x509.Certificate
}

// JSONSignature represents a signature of a json object.
type JSONSignature struct {
	payload      string
	signatures   []jsSignature
	indent       string
	formatLength int
	formatTail   []byte
}

func newJSONSignature() *JSONSignature {
	return &JSONSignature{
		signatures: make([]jsSignature, 0, 1),
	}
}

// Payload returns the encoded payload of the signature. This
// payload should not be signed directly
func (js *JSONSignature) Payload() ([]byte, error) {
	return joseBase64UrlDecode(js.payload)
}

func (js *JSONSignature) protectedHeader() (string, error) {
	protected := map[string]interface{}{
		"formatLength": js.formatLength,
		"formatTail":   joseBase64UrlEncode(js.formatTail),
		"time":         time.Now().UTC().Format(time.RFC3339),
	}
	protectedBytes, err := json.Marshal(protected)
	if err != nil {
		return "", err
	}

	return joseBase64UrlEncode(protectedBytes), nil
}

func (js *JSONSignature) signBytes(protectedHeader string) ([]byte, error) {
	buf := make([]byte, len(js.payload)+len(protectedHeader)+1)
	copy(buf, protectedHeader)
	buf[len(protectedHeader)] = '.'
	copy(buf[len(protectedHeader)+1:], js.payload)
	return buf, nil
}

// Sign adds a signature using the given private key.
func (js *JSONSignature) Sign(key PrivateKey) error {
	protected, err := js.protectedHeader()
	if err != nil {
		return err
	}
	signBytes, err := js.signBytes(protected)
	if err != nil {
		return err
	}
	sigBytes, algorithm, err := key.Sign(bytes.NewReader(signBytes), crypto.SHA256)
	if err != nil {
		return err
	}

	js.signatures = append(js.signatures, jsSignature{
		Header: jsHeader{
			JWK:       key.PublicKey(),
			Algorithm: algorithm,
		},
		Signature: joseBase64UrlEncode(sigBytes),
		Protected: protected,
	})

	return nil
}

// SignWithChain adds a signature using the given private key
// and setting the x509 chain. The public key of the first element
// in the chain must be the public key corresponding with the sign key.
func (js *JSONSignature) SignWithChain(key PrivateKey, chain []*x509.Certificate) error {
	// Ensure key.Chain[0] is public key for key
	//key.Chain.PublicKey
	//key.PublicKey().CryptoPublicKey()

	// Verify chain
	protected, err := js.protectedHeader()
	if err != nil {
		return err
	}
	signBytes, err := js.signBytes(protected)
	if err != nil {
		return err
	}
	sigBytes, algorithm, err := key.Sign(bytes.NewReader(signBytes), crypto.SHA256)
	if err != nil {
		return err
	}

	header := jsHeader{
		Chain:     make([]string, len(chain)),
		Algorithm: algorithm,
	}

	for i, cert := range chain {
		header.Chain[i] = base64.StdEncoding.EncodeToString(cert.Raw)
	}

	js.signatures = append(js.signatures, jsSignature{
		Header:    header,
		Signature: joseBase64UrlEncode(sigBytes),
		Protected: protected,
	})

	return nil
}

// Verify verifies all the signatures and returns the list of
// public keys used to sign. Any x509 chains are not checked.
func (js *JSONSignature) Verify() ([]PublicKey, error) {
	keys := make([]PublicKey, len(js.signatures))
	for i, signature := range js.signatures {
		signBytes, err := js.signBytes(signature.Protected)
		if err != nil {
			return nil, err
		}
		var publicKey PublicKey
		if len(signature.Header.Chain) > 0 {
			certBytes, err := base64.StdEncoding.DecodeString(signature.Header.Chain[0])
			if err != nil {
				return nil, err
			}
			cert, err := x509.ParseCertificate(certBytes)
			if err != nil {
				return nil, err
			}
			publicKey, err = FromCryptoPublicKey(cert.PublicKey)
			if err != nil {
				return nil, err
			}
		} else if signature.Header.JWK != nil {
			publicKey = signature.Header.JWK
		} else {
			return nil, errors.New("missing public key")
		}

		sigBytes, err := joseBase64UrlDecode(signature.Signature)
		if err != nil {
			return nil, err
		}

		err = publicKey.Verify(bytes.NewReader(signBytes), signature.Header.Algorithm, sigBytes)
		if err != nil {
			return nil, err
		}

		keys[i] = publicKey
	}
	return keys, nil
}

// VerifyChains verifies all the signatures and the chains associated
// with each signature and returns the list of verified chains.
// Signatures without an x509 chain are not checked.
func (js *JSONSignature) VerifyChains(ca *x509.CertPool) ([][]*x509.Certificate, error) {
	chains := make([][]*x509.Certificate, 0, len(js.signatures))
	for _, signature := range js.signatures {
		signBytes, err := js.signBytes(signature.Protected)
		if err != nil {
			return nil, err
		}
		var publicKey PublicKey
		if len(signature.Header.Chain) > 0 {
			certBytes, err := base64.StdEncoding.DecodeString(signature.Header.Chain[0])
			if err != nil {
				return nil, err
			}
			cert, err := x509.ParseCertificate(certBytes)
			if err != nil {
				return nil, err
			}
			publicKey, err = FromCryptoPublicKey(cert.PublicKey)
			if err != nil {
				return nil, err
			}
			intermediates := x509.NewCertPool()
			if len(signature.Header.Chain) > 1 {
				intermediateChain := signature.Header.Chain[1:]
				for i := range intermediateChain {
					certBytes, err := base64.StdEncoding.DecodeString(intermediateChain[i])
					if err != nil {
						return nil, err
					}
					intermediate, err := x509.ParseCertificate(certBytes)
					if err != nil {
						return nil, err
					}
					intermediates.AddCert(intermediate)
				}
			}

			verifyOptions := x509.VerifyOptions{
				Intermediates: intermediates,
				Roots:         ca,
			}

			verifiedChains, err := cert.Verify(verifyOptions)
			if err != nil {
				return nil, err
			}
			chains = append(chains, verifiedChains...)

			sigBytes, err := joseBase64UrlDecode(signature.Signature)
			if err != nil {
				return nil, err
			}

			err = publicKey.Verify(bytes.NewReader(signBytes), signature.Header.Algorithm, sigBytes)
			if err != nil {
				return nil, err
			}
		}

	}
	return chains, nil
}

// JWS returns JSON serialized JWS according to
// http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-31#section-7.2
func (js *JSONSignature) JWS() ([]byte, error) {
	if len(js.signatures) == 0 {
		return nil, errors.New("missing signature")
	}

	sort.Sort(jsSignaturesSorted(js.signatures))

	jsonMap := map[string]interface{}{
		"payload":    js.payload,
		"signatures": js.signatures,
	}

	return json.MarshalIndent(jsonMap, "", "   ")
}

func notSpace(r rune) bool {
	return !unicode.IsSpace(r)
}

func detectJSONIndent(jsonContent []byte) (indent string) {
	if len(jsonContent) > 2 && jsonContent[0] == '{' && jsonContent[1] == '\n' {
		quoteIndex := bytes.IndexRune(jsonContent[1:], '"')
		if quoteIndex > 0 {
			indent = string(jsonContent[2 : quoteIndex+1])
		}
	}
	return
}

type jsParsedHeader struct {
	JWK       json.RawMessage `json:"jwk"`
	Algorithm string          `json:"alg"`
	Chain     []string        `json:"x5c"`
}

type jsParsedSignature struct {
	Header    jsParsedHeader `json:"header"`
	Signature string         `json:"signature"`
	Protected string         `json:"protected"`
}

// ParseJWS parses a JWS serialized JSON object into a Json Signature.
func ParseJWS(content []byte) (*JSONSignature, error) {
	type jsParsed struct {
		Payload    string              `json:"payload"`
		Signatures []jsParsedSignature `json:"signatures"`
	}
	parsed := &jsParsed{}
	err := json.Unmarshal(content, parsed)
	if err != nil {
		return nil, err
	}
	if len(parsed.Signatures) == 0 {
		return nil, errors.New("missing signatures")
	}
	payload, err := joseBase64UrlDecode(parsed.Payload)
	if err != nil {
		return nil, err
	}

	js, err := NewJSONSignature(payload)
	if err != nil {
		return nil, err
	}
	js.signatures = make([]jsSignature, len(parsed.Signatures))
	for i, signature := range parsed.Signatures {
		header := jsHeader{
			Algorithm: signature.Header.Algorithm,
		}
		if signature.Header.Chain != nil {
			header.Chain = signature.Header.Chain
		}
		if signature.Header.JWK != nil {
			publicKey, err := UnmarshalPublicKeyJWK([]byte(signature.Header.JWK))
			if err != nil {
				return nil, err
			}
			header.JWK = publicKey
		}
		js.signatures[i] = jsSignature{
			Header:    header,
			Signature: signature.Signature,
			Protected: signature.Protected,
		}
	}

	return js, nil
}

// NewJSONSignature returns a new unsigned JWS from a json byte array.
// JSONSignature will need to be signed before serializing or storing.
// Optionally, one or more signatures can be provided as byte buffers,
// containing serialized JWS signatures, to assemble a fully signed JWS
// package. It is the callers responsibility to ensure uniqueness of the
// provided signatures.
func NewJSONSignature(content []byte, signatures ...[]byte) (*JSONSignature, error) {
	var dataMap map[string]interface{}
	err := json.Unmarshal(content, &dataMap)
	if err != nil {
		return nil, err
	}

	js := newJSONSignature()
	js.indent = detectJSONIndent(content)

	js.payload = joseBase64UrlEncode(content)

	// Find trailing } and whitespace, put in protected header
	closeIndex := bytes.LastIndexFunc(content, notSpace)
	if content[closeIndex] != '}' {
		return nil, ErrInvalidJSONContent
	}
	lastRuneIndex := bytes.LastIndexFunc(content[:closeIndex], notSpace)
	if content[lastRuneIndex] == ',' {
		return nil, ErrInvalidJSONContent
	}
	js.formatLength = lastRuneIndex + 1
	js.formatTail = content[js.formatLength:]

	if len(signatures) > 0 {
		for _, signature := range signatures {
			var parsedJSig jsParsedSignature

			if err := json.Unmarshal(signature, &parsedJSig); err != nil {
				return nil, err
			}

			// TODO(stevvooe): A lot of the code below is repeated in
			// ParseJWS. It will require more refactoring to fix that.
			jsig := jsSignature{
				Header: jsHeader{
					Algorithm: parsedJSig.Header.Algorithm,
				},
				Signature: parsedJSig.Signature,
				Protected: parsedJSig.Protected,
			}

			if parsedJSig.Header.Chain != nil {
				jsig.Header.Chain = parsedJSig.Header.Chain
			}

			if parsedJSig.Header.JWK != nil {
				publicKey, err := UnmarshalPublicKeyJWK([]byte(parsedJSig.Header.JWK))
				if err != nil {
					return nil, err
				}
				jsig.Header.JWK = publicKey
			}

			js.signatures = append(js.signatures, jsig)
		}
	}

	return js, nil
}

// NewJSONSignatureFromMap returns a new unsigned JSONSignature from a map or
// struct. JWS will need to be signed before serializing or storing.
func NewJSONSignatureFromMap(content interface{}) (*JSONSignature, error) {
	switch content.(type) {
	case map[string]interface{}:
	case struct{}:
	default:
		return nil, errors.New("invalid data type")
	}

	js := newJSONSignature()
	js.indent = "   "

	payload, err := json.MarshalIndent(content, "", js.indent)
	if err != nil {
		return nil, err
	}
	js.payload = joseBase64UrlEncode(payload)

	// Remove '\n}' from formatted section, put in protected header
	js.formatLength = len(payload) - 2
	js.formatTail = payload[js.formatLength:]

	return js, nil
}

func readIntFromMap(key string, m map[string]interface{}) (int, bool) {
	value, ok := m[key]
	if !ok {
		return 0, false
	}
	switch v := value.(type) {
	case int:
		return v, true
	case float64:
		return int(v), true
	default:
		return 0, false
	}
}

func readStringFromMap(key string, m map[string]interface{}) (v string, ok bool) {
	value, ok := m[key]
	if !ok {
		return "", false
	}
	v, ok = value.(string)
	return
}

// ParsePrettySignature parses a formatted signature into a
// JSON signature. If the signatures are missing the format information
// an error is thrown. The formatted signature must be created by
// the same method as format signature.
func ParsePrettySignature(content []byte, signatureKey string) (*JSONSignature, error) {
	var contentMap map[string]json.RawMessage
	err := json.Unmarshal(content, &contentMap)
	if err != nil {
		return nil, fmt.Errorf("error unmarshalling content: %s", err)
	}
	sigMessage, ok := contentMap[signatureKey]
	if !ok {
		return nil, ErrMissingSignatureKey
	}

	var signatureBlocks []jsParsedSignature
	err = json.Unmarshal([]byte(sigMessage), &signatureBlocks)
	if err != nil {
		return nil, fmt.Errorf("error unmarshalling signatures: %s", err)
	}

	js := newJSONSignature()
	js.signatures = make([]jsSignature, len(signatureBlocks))

	for i, signatureBlock := range signatureBlocks {
		protectedBytes, err := joseBase64UrlDecode(signatureBlock.Protected)
		if err != nil {
			return nil, fmt.Errorf("base64 decode error: %s", err)
		}
		var protectedHeader map[string]interface{}
		err = json.Unmarshal(protectedBytes, &protectedHeader)
		if err != nil {
			return nil, fmt.Errorf("error unmarshalling protected header: %s", err)
		}

		formatLength, ok := readIntFromMap("formatLength", protectedHeader)
		if !ok {
			return nil, errors.New("missing formatted length")
		}
		encodedTail, ok := readStringFromMap("formatTail", protectedHeader)
		if !ok {
			return nil, errors.New("missing formatted tail")
		}
		formatTail, err := joseBase64UrlDecode(encodedTail)
		if err != nil {
			return nil, fmt.Errorf("base64 decode error on tail: %s", err)
		}
		if js.formatLength == 0 {
			js.formatLength = formatLength
		} else if js.formatLength != formatLength {
			return nil, errors.New("conflicting format length")
		}
		if len(js.formatTail) == 0 {
			js.formatTail = formatTail
		} else if bytes.Compare(js.formatTail, formatTail) != 0 {
			return nil, errors.New("conflicting format tail")
		}

		header := jsHeader{
			Algorithm: signatureBlock.Header.Algorithm,
			Chain:     signatureBlock.Header.Chain,
		}
		if signatureBlock.Header.JWK != nil {
			publicKey, err := UnmarshalPublicKeyJWK([]byte(signatureBlock.Header.JWK))
			if err != nil {
				return nil, fmt.Errorf("error unmarshalling public key: %s", err)
			}
			header.JWK = publicKey
		}
		js.signatures[i] = jsSignature{
			Header:    header,
			Signature: signatureBlock.Signature,
			Protected: signatureBlock.Protected,
		}
	}
	if js.formatLength > len(content) {
		return nil, errors.New("invalid format length")
	}
	formatted := make([]byte, js.formatLength+len(js.formatTail))
	copy(formatted, content[:js.formatLength])
	copy(formatted[js.formatLength:], js.formatTail)
	js.indent = detectJSONIndent(formatted)
	js.payload = joseBase64UrlEncode(formatted)

	return js, nil
}

// PrettySignature formats a json signature into an easy to read
// single json serialized object.
func (js *JSONSignature) PrettySignature(signatureKey string) ([]byte, error) {
	if len(js.signatures) == 0 {
		return nil, errors.New("no signatures")
	}
	payload, err := joseBase64UrlDecode(js.payload)
	if err != nil {
		return nil, err
	}
	payload = payload[:js.formatLength]

	sort.Sort(jsSignaturesSorted(js.signatures))

	var marshalled []byte
	var marshallErr error
	if js.indent != "" {
		marshalled, marshallErr = json.MarshalIndent(js.signatures, js.indent, js.indent)
	} else {
		marshalled, marshallErr = json.Marshal(js.signatures)
	}
	if marshallErr != nil {
		return nil, marshallErr
	}

	buf := bytes.NewBuffer(make([]byte, 0, len(payload)+len(marshalled)+34))
	buf.Write(payload)
	buf.WriteByte(',')
	if js.indent != "" {
		buf.WriteByte('\n')
		buf.WriteString(js.indent)
		buf.WriteByte('"')
		buf.WriteString(signatureKey)
		buf.WriteString("\": ")
		buf.Write(marshalled)
		buf.WriteByte('\n')
	} else {
		buf.WriteByte('"')
		buf.WriteString(signatureKey)
		buf.WriteString("\":")
		buf.Write(marshalled)
	}
	buf.WriteByte('}')

	return buf.Bytes(), nil
}

// Signatures provides the signatures on this JWS as opaque blobs, sorted by
// keyID. These blobs can be stored and reassembled with payloads. Internally,
// they are simply marshaled json web signatures but implementations should
// not rely on this.
func (js *JSONSignature) Signatures() ([][]byte, error) {
	sort.Sort(jsSignaturesSorted(js.signatures))

	var sb [][]byte
	for _, jsig := range js.signatures {
		p, err := json.Marshal(jsig)
		if err != nil {
			return nil, err
		}

		sb = append(sb, p)
	}

	return sb, nil
}

// Merge combines the signatures from one or more other signatures into the
// method receiver. If the payloads differ for any argument, an error will be
// returned and the receiver will not be modified.
func (js *JSONSignature) Merge(others ...*JSONSignature) error {
	merged := js.signatures
	for _, other := range others {
		if js.payload != other.payload {
			return fmt.Errorf("payloads differ from merge target")
		}
		merged = append(merged, other.signatures...)
	}

	js.signatures = merged
	return nil
}