attributes.go 16.8 KB
Newer Older
1
package irma
2
3
4

import (
	"crypto/sha256"
5
	"encoding/binary"
Sietse Ringers's avatar
Sietse Ringers committed
6
	"encoding/hex"
7
	"encoding/json"
8
	"math/big"
9
	"time"
10

11
	"fmt"
12

Sietse Ringers's avatar
Sietse Ringers committed
13
	"github.com/go-errors/errors"
14
15
16
	"github.com/mhe/gabi"
)

17
18
const (
	// ExpiryFactor is the precision for the expiry attribute. Value is one week.
19
20
	ExpiryFactor   = 60 * 60 * 24 * 7
	metadataLength = 1 + 3 + 2 + 2 + 16
21
22
)

23
type AttributeResult struct {
Tomas's avatar
Tomas committed
24
	AttributeValue       TranslatedString        `json:"value"` // Value of the disclosed attribute
25
26
	AttributeId          AttributeTypeIdentifier `json:"id"`
	AttributeProofStatus AttributeProofStatus    `json:"status"`
27
28
}

29
30
type AttributeResultList []*AttributeResult

31
// AttributeProofStatus is the proof status of a single attribute
32
33
34
type AttributeProofStatus string

const (
Koen van Ingen's avatar
Koen van Ingen committed
35
36
	PRESENT       = AttributeProofStatus("PRESENT")       // Attribute is disclosed and matches the value
	EXTRA         = AttributeProofStatus("EXTRA")         // Attribute is disclosed, but wasn't requested in request
37
38
39
40
	MISSING       = AttributeProofStatus("MISSING")       // Attribute is NOT disclosed, but should be according to request
	INVALID_VALUE = AttributeProofStatus("INVALID_VALUE") // Attribute is disclosed, but has invalid value according to request
)

41
var (
Sietse Ringers's avatar
Sietse Ringers committed
42
43
44
45
46
	versionField     = metadataField{1, 0}
	signingDateField = metadataField{3, 1}
	validityField    = metadataField{2, 4}
	keyCounterField  = metadataField{2, 6}
	credentialID     = metadataField{16, 8}
47
48
)

Sietse Ringers's avatar
Sietse Ringers committed
49
50
// metadataField contains the length and offset of a field within a metadata attribute.
type metadataField struct {
51
52
53
54
	length int
	offset int
}

55
// metadataAttribute represents a metadata attribute. Contains the credential type, signing date, validity, and the public key counter.
56
type MetadataAttribute struct {
57
58
59
	Int  *big.Int
	pk   *gabi.PublicKey
	Conf *Configuration
60
61
}

62
63
64
// AttributeList contains attributes, excluding the secret key,
// providing convenient access to the metadata attribute.
type AttributeList struct {
65
	*MetadataAttribute `json:"-"`
66
	Ints               []*big.Int
Sietse Ringers's avatar
Sietse Ringers committed
67
	strings            []TranslatedString
68
	info               *CredentialInfo
69
	h                  string
70
71
}

72
// NewAttributeListFromInts initializes a new AttributeList from a list of bigints.
73
func NewAttributeListFromInts(ints []*big.Int, conf *Configuration) *AttributeList {
74
	return &AttributeList{
75
		Ints:              ints,
76
		MetadataAttribute: MetadataFromInt(ints[0], conf),
77
	}
78
79
}

80
func (al *AttributeList) Info() *CredentialInfo {
81
	if al.info == nil {
82
		al.info = NewCredentialInfo(al.Ints, al.Conf)
83
	}
84
	return al.info
85
86
}

87
func (al *AttributeList) Hash() string {
88
89
90
	if al.h == "" {
		bytes := []byte{}
		for _, i := range al.Ints {
91
			bytes = append(bytes, i.Bytes()...)
92
93
94
		}
		shasum := sha256.Sum256(bytes)
		al.h = hex.EncodeToString(shasum[:])
95
	}
96
	return al.h
97
98
}

99
// Strings converts the current instance to human-readable strings.
Sietse Ringers's avatar
Sietse Ringers committed
100
func (al *AttributeList) Strings() []TranslatedString {
101
	if al.strings == nil {
Sietse Ringers's avatar
Sietse Ringers committed
102
		al.strings = make([]TranslatedString, len(al.Ints)-1)
103
104
105
106
		for i := range al.Ints[1:] { // skip metadata
			val := al.decode(i)
			if val == nil {
				continue
107
			}
Tomas's avatar
Tomas committed
108
			al.strings[i] = translateAttribute(val)
109
110
111
112
		}
	}
	return al.strings
}
113

Tomas's avatar
Tomas committed
114
115
116
117
118
119
120
121
// Localize raw attribute values (to be implemented)
func translateAttribute(attr *string) TranslatedString {
	if attr == nil {
		return nil
	}
	return map[string]string{"en": *attr, "nl": *attr}
}

122
func (al *AttributeList) decode(i int) *string {
123
124
125
126
127
128
129
130
131
	attr := al.Ints[i+1]
	metadataVersion := al.MetadataAttribute.Version()
	return decodeAttribute(attr, metadataVersion)
}

// Decode attribute value into string according to metadataVersion
func decodeAttribute(attr *big.Int, metadataVersion byte) *string {
	bi := new(big.Int).Set(attr)
	if metadataVersion >= 3 {
132
133
134
135
136
137
138
139
140
141
142
		if bi.Bit(0) == 0 { // attribute does not exist
			return nil
		}
		bi.Rsh(bi, 1)
	}
	str := string(bi.Bytes())
	return &str
}

// UntranslatedAttribute decodes the bigint corresponding to the specified attribute.
func (al *AttributeList) UntranslatedAttribute(identifier AttributeTypeIdentifier) *string {
143
	if al.CredentialType().Identifier() != identifier.CredentialTypeIdentifier() {
144
		return nil
145
	}
146
	for i, desc := range al.CredentialType().Attributes {
147
		if desc.ID == string(identifier.Name()) {
148
			return al.decode(i)
149
150
		}
	}
151
	return nil
152
153
}

Sietse Ringers's avatar
Sietse Ringers committed
154
155
156
157
158
159
160
161
162
163
164
165
166
// Attribute returns the content of the specified attribute, or "" if not present in this attribute list.
func (al *AttributeList) Attribute(identifier AttributeTypeIdentifier) TranslatedString {
	if al.CredentialType().Identifier() != identifier.CredentialTypeIdentifier() {
		return nil
	}
	for i, desc := range al.CredentialType().Attributes {
		if desc.ID == string(identifier.Name()) {
			return al.Strings()[i]
		}
	}
	return nil
}

167
// MetadataFromInt wraps the given Int
168
169
func MetadataFromInt(i *big.Int, conf *Configuration) *MetadataAttribute {
	return &MetadataAttribute{Int: i, Conf: conf}
170
171
172
}

// NewMetadataAttribute constructs a new instance containing the default values:
173
// provided version as versionField
174
175
176
// now as signing date
// 0 as keycounter
// ValidityDefault (half a year) as default validity.
177
func NewMetadataAttribute(version byte) *MetadataAttribute {
178
	val := MetadataAttribute{new(big.Int), nil, nil}
179
	val.setField(versionField, []byte{version})
180
181
	val.setSigningDate()
	val.setKeyCounter(0)
182
	val.setDefaultValidityDuration()
183
184
185
186
187
188
189
190
191
192
193
194
195
196
	return &val
}

// Bytes returns this metadata attribute as a byte slice.
func (attr *MetadataAttribute) Bytes() []byte {
	bytes := attr.Int.Bytes()
	if len(bytes) < metadataLength {
		bytes = append(bytes, make([]byte, metadataLength-len(bytes))...)
	}
	return bytes
}

// PublicKey extracts identifier of the Idemix public key with which this instance was signed,
// and returns this public key.
197
func (attr *MetadataAttribute) PublicKey() (*gabi.PublicKey, error) {
198
	if attr.pk == nil {
199
		var err error
200
		attr.pk, err = attr.Conf.PublicKey(attr.CredentialType().IssuerIdentifier(), attr.KeyCounter())
201
202
203
		if err != nil {
			return nil, err
		}
204
	}
205
	return attr.pk, nil
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
}

// Version returns the metadata version of this instance
func (attr *MetadataAttribute) Version() byte {
	return attr.field(versionField)[0]
}

// SigningDate returns the time at which this instance was signed
func (attr *MetadataAttribute) SigningDate() time.Time {
	bytes := attr.field(signingDateField)
	bytes = bytes[1:] // The signing date field is one byte too long
	timestamp := int64(binary.BigEndian.Uint16(bytes)) * ExpiryFactor
	return time.Unix(timestamp, 0)
}

func (attr *MetadataAttribute) setSigningDate() {
	attr.setField(signingDateField, shortToByte(int(time.Now().Unix()/ExpiryFactor)))
}

// KeyCounter return the public key counter of the metadata attribute
func (attr *MetadataAttribute) KeyCounter() int {
	return int(binary.BigEndian.Uint16(attr.field(keyCounterField)))
}

func (attr *MetadataAttribute) setKeyCounter(i int) {
	attr.setField(keyCounterField, shortToByte(i))
}

// ValidityDuration returns the amount of epochs during which this instance is valid
func (attr *MetadataAttribute) ValidityDuration() int {
	return int(binary.BigEndian.Uint16(attr.field(validityField)))
}

func (attr *MetadataAttribute) setValidityDuration(weeks int) {
	attr.setField(validityField, shortToByte(weeks))
}

243
244
245
246
func (attr *MetadataAttribute) setDefaultValidityDuration() {
	attr.setExpiryDate(nil)
}

Sietse Ringers's avatar
Sietse Ringers committed
247
func (attr *MetadataAttribute) setExpiryDate(timestamp *Timestamp) error {
248
	var expiry int64
Sietse Ringers's avatar
Sietse Ringers committed
249
	if timestamp == nil {
250
		expiry = time.Now().AddDate(0, 6, 0).Unix()
251
252
	} else {
		expiry = time.Time(*timestamp).Unix()
Sietse Ringers's avatar
Sietse Ringers committed
253
	}
Sietse Ringers's avatar
Sietse Ringers committed
254
255
256
257
258
	signing := attr.SigningDate().Unix()
	attr.setValidityDuration(int((expiry - signing) / ExpiryFactor))
	return nil
}

259
// CredentialType returns the credential type of the current instance
260
// using the Configuration.
261
func (attr *MetadataAttribute) CredentialType() *CredentialType {
262
	return attr.Conf.hashToCredentialType(attr.field(credentialID))
263
264
}

265
func (attr *MetadataAttribute) setCredentialTypeIdentifier(id string) {
266
267
268
269
	bytes := sha256.Sum256([]byte(id))
	attr.setField(credentialID, bytes[:16])
}

270
271
272
273
func (attr *MetadataAttribute) CredentialTypeHash() []byte {
	return attr.field(credentialID)
}

274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// Expiry returns the expiry date of this instance
func (attr *MetadataAttribute) Expiry() time.Time {
	expiry := attr.SigningDate().Unix() + int64(attr.ValidityDuration()*ExpiryFactor)
	return time.Unix(expiry, 0)
}

// IsValidOn returns whether this instance is still valid at the given time
func (attr *MetadataAttribute) IsValidOn(t time.Time) bool {
	return attr.Expiry().After(t)
}

// IsValid returns whether this instance is valid.
func (attr *MetadataAttribute) IsValid() bool {
	return attr.IsValidOn(time.Now())
}

290
291
292
293
294
295
296
// FloorToEpochBoundary returns the greatest time not greater than the argument
// that falls on the boundary of an epoch for attribute validity or expiry,
// of which the value is defined by ExpiryFactor (one week).
func FloorToEpochBoundary(t time.Time) time.Time {
	return time.Unix((t.Unix()/ExpiryFactor)*ExpiryFactor, 0)
}

Sietse Ringers's avatar
Sietse Ringers committed
297
func (attr *MetadataAttribute) field(field metadataField) []byte {
298
299
300
	return attr.Bytes()[field.offset : field.offset+field.length]
}

Sietse Ringers's avatar
Sietse Ringers committed
301
func (attr *MetadataAttribute) setField(field metadataField, value []byte) {
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
	if len(value) > field.length {
		panic("Specified metadata field too large")
	}

	bytes := attr.Bytes()

	// Push the value to the right within the field. Graphical representation:
	// --xxxXXX----
	// "-" indicates a byte of another field
	// "X" is a byte of the value and "x" of our field
	// In this example, our field has offset 2, length 6,
	// but the specified value is only 3 bytes long.
	startindex := field.length - len(value)
	for i := 0; i < field.length; i++ {
		if i < startindex {
			bytes[i+field.offset] = 0
		} else {
			bytes[i+field.offset] = value[i-startindex]
		}
	}

	attr.Int.SetBytes(bytes)
}

func shortToByte(x int) []byte {
	bytes := make([]byte, 2)
	binary.BigEndian.PutUint16(bytes, uint16(x))
	return bytes
}
331

332
333
334
335
336
// A DisclosureChoice contains the attributes chosen to be disclosed.
type DisclosureChoice struct {
	Attributes []*AttributeIdentifier
}

337
338
339
340
341
// An AttributeDisjunction encapsulates a list of possible attributes, one
// of which should be disclosed.
type AttributeDisjunction struct {
	Label      string
	Attributes []AttributeTypeIdentifier
342
	Values     map[AttributeTypeIdentifier]*string
343
344
345
346

	selected *AttributeTypeIdentifier
}

Koen van Ingen's avatar
Koen van Ingen committed
347
// AttributeDisjunction with the disclosed value that is used to satisfy the disjunction
348
349
350
type DisclosedAttributeDisjunction struct {
	AttributeDisjunction

Tomas's avatar
Tomas committed
351
	DisclosedValue TranslatedString
352
353
354
355
	DisclosedId    AttributeTypeIdentifier
	ProofStatus    AttributeProofStatus
}

356
357
358
// An AttributeDisjunctionList is a list of AttributeDisjunctions.
type AttributeDisjunctionList []*AttributeDisjunction

359
360
// Convert disjunction to a DisclosedAttributeDisjunction that contains disclosed attribute+value
func (disjunction *AttributeDisjunction) ToDisclosedAttributeDisjunction(ar *AttributeResult) *DisclosedAttributeDisjunction {
361
	return &DisclosedAttributeDisjunction{
362
		AttributeDisjunction: *disjunction,
363
364
365
366
367
368
		DisclosedValue:       ar.AttributeValue,
		DisclosedId:          ar.AttributeId,
		ProofStatus:          ar.AttributeProofStatus,
	}
}

369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
// HasValues indicates if the attributes of this disjunction have values
// that should be satisfied.
func (disjunction *AttributeDisjunction) HasValues() bool {
	return disjunction.Values != nil && len(disjunction.Values) != 0
}

// Satisfied indicates if this disjunction has a valid chosen attribute
// to be disclosed.
func (disjunction *AttributeDisjunction) Satisfied() bool {
	if disjunction.selected == nil {
		return false
	}
	for _, attr := range disjunction.Attributes {
		if *disjunction.selected == attr {
			return true
		}
	}
	return false
}

389
390
// Check whether specified attributedisjunction satisfy a list of disclosed attributes
// We return true if one of the attributes in the disjunction is satisfied
391
func (disjunction *AttributeDisjunction) SatisfyDisclosed(disclosed DisclosedCredentialList, conf *Configuration) (bool, *DisclosedAttributeDisjunction) {
392
	var attributeResult *AttributeResult
393
	for _, attr := range disjunction.Attributes {
394
		requestedValue := disjunction.Values[attr]
395

396
		var isSatisfied bool
397
		isSatisfied, attributeResult = disclosed.isAttributeSatisfied(attr, requestedValue)
398

399
		if isSatisfied {
400
			return true, disjunction.ToDisclosedAttributeDisjunction(attributeResult)
401
402
403
		}
	}

404
405
	// Nothing satisfied, attributeResult will contain the last attribute of the original request
	// TODO: do we want this?
406
	return false, disjunction.ToDisclosedAttributeDisjunction(attributeResult)
407
408
}

409
410
411
// MatchesConfig returns true if all attributes contained in the disjunction are
// present in the specified configuration.
func (disjunction *AttributeDisjunction) MatchesConfig(conf *Configuration) bool {
412
	for ai := range disjunction.Values {
413
		creddescription, exists := conf.CredentialTypes[ai.CredentialTypeIdentifier()]
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
		if !exists {
			return false
		}
		if !creddescription.ContainsAttribute(ai) {
			return false
		}
	}
	return true
}

// Satisfied indicates whether each contained attribute disjunction has a chosen attribute.
func (dl AttributeDisjunctionList) Satisfied() bool {
	for _, disjunction := range dl {
		if !disjunction.Satisfied() {
			return false
		}
	}
	return true
}

// Find searches for and returns the disjunction that contains the specified attribute identifier, or nil if not found.
func (dl AttributeDisjunctionList) Find(ai AttributeTypeIdentifier) *AttributeDisjunction {
	for _, disjunction := range dl {
		for _, attr := range disjunction.Attributes {
			if attr == ai {
				return disjunction
			}
		}
	}
	return nil
}

// MarshalJSON marshals the disjunction to JSON.
func (disjunction *AttributeDisjunction) MarshalJSON() ([]byte, error) {
	if !disjunction.HasValues() {
		temp := struct {
			Label      string                    `json:"label"`
			Attributes []AttributeTypeIdentifier `json:"attributes"`
		}{
			Label:      disjunction.Label,
			Attributes: disjunction.Attributes,
		}
		return json.Marshal(temp)
	}

	temp := struct {
460
461
		Label      string                              `json:"label"`
		Attributes map[AttributeTypeIdentifier]*string `json:"attributes"`
462
463
464
465
466
	}{
		Label:      disjunction.Label,
		Attributes: disjunction.Values,
	}
	return json.Marshal(temp)
467
468
469
470
471
472
473
474
}

// Since we have a custom MarshalJSON for AttributeDisjunction, we also need one for every struct that extends AttributeDisjunction...
func (disclosedAttributeDisjunction *DisclosedAttributeDisjunction) MarshalJSON() ([]byte, error) {
	temp := struct {
		Label      string                    `json:"label"`
		Attributes []AttributeTypeIdentifier `json:"attributes"`

Tomas's avatar
Tomas committed
475
		DisclosedValue TranslatedString        `json:"disclosedValue"`
476
477
478
479
480
481
482
483
484
485
486
487
		DisclosedId    AttributeTypeIdentifier `json:"disclosedId"`
		ProofStatus    AttributeProofStatus    `json:"proofStatus"`
	}{
		Label:      disclosedAttributeDisjunction.Label,
		Attributes: disclosedAttributeDisjunction.Attributes,

		DisclosedValue: disclosedAttributeDisjunction.DisclosedValue,
		DisclosedId:    disclosedAttributeDisjunction.DisclosedId,
		ProofStatus:    disclosedAttributeDisjunction.ProofStatus,
	}

	return json.Marshal(temp)
488
489
490
491
492
}

// UnmarshalJSON unmarshals an attribute disjunction from JSON.
func (disjunction *AttributeDisjunction) UnmarshalJSON(bytes []byte) error {
	if disjunction.Values == nil {
493
		disjunction.Values = make(map[AttributeTypeIdentifier]*string)
494
495
496
497
498
499
500
501
502
503
504
505
	}
	if disjunction.Attributes == nil {
		disjunction.Attributes = make([]AttributeTypeIdentifier, 0, 3)
	}

	// We don't know if the json element "attributes" is a list, or a map.
	// So we unmarshal it into a temporary struct that has interface{} as the
	// type of "attributes", so that we can check which of the two it is.
	temp := struct {
		Label      string      `json:"label"`
		Attributes interface{} `json:"attributes"`
	}{}
Sietse Ringers's avatar
Sietse Ringers committed
506
507
508
	if err := json.Unmarshal(bytes, &temp); err != nil {
		return err
	}
509
510
511
512
513
	disjunction.Label = temp.Label

	switch temp.Attributes.(type) {
	case map[string]interface{}:
		temp := struct {
514
515
			Label      string             `json:"label"`
			Attributes map[string]*string `json:"attributes"`
516
		}{}
Sietse Ringers's avatar
Sietse Ringers committed
517
518
519
		if err := json.Unmarshal(bytes, &temp); err != nil {
			return err
		}
520
521
522
523
524
525
526
527
528
529
		for str, value := range temp.Attributes {
			id := NewAttributeTypeIdentifier(str)
			disjunction.Attributes = append(disjunction.Attributes, id)
			disjunction.Values[id] = value
		}
	case []interface{}:
		temp := struct {
			Label      string   `json:"label"`
			Attributes []string `json:"attributes"`
		}{}
Sietse Ringers's avatar
Sietse Ringers committed
530
531
532
		if err := json.Unmarshal(bytes, &temp); err != nil {
			return err
		}
533
534
535
536
537
538
539
540
541
		for _, str := range temp.Attributes {
			disjunction.Attributes = append(disjunction.Attributes, NewAttributeTypeIdentifier(str))
		}
	default:
		return errors.New("could not parse attribute disjunction: element 'attributes' was incorrect")
	}

	return nil
}
542
543
544
545

func (al *AttributeResultList) String() string {
	// TODO: pretty print?
	str := "Attribute --- Value --- ProofStatus:"
546
	for _, v := range *al {
547
548
549
550
551
552
553
554
		str = str + "\n" + v.String()
	}
	return str
}

func (ar *AttributeResult) String() string {
	return fmt.Sprintf("%v --- %v --- %v",
		ar.AttributeId,
555
		ar.AttributeValue,
556
557
		ar.AttributeProofStatus)
}