attributes.go 12.2 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

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

15
16
17
18
19
20
21
22
23
24
25
const (
	// ExpiryFactor is the precision for the expiry attribute. Value is one week.
	ExpiryFactor = 60 * 60 * 24 * 7
	// ValidityDefault is the default validity of new credentials (half a year).
	ValidityDefault = 52 / 2
	metadataLength  = 1 + 3 + 2 + 2 + 16
)

var (
	metadataVersion = []byte{0x02}

Sietse Ringers's avatar
Sietse Ringers committed
26
27
28
29
30
	versionField     = metadataField{1, 0}
	signingDateField = metadataField{3, 1}
	validityField    = metadataField{2, 4}
	keyCounterField  = metadataField{2, 6}
	credentialID     = metadataField{16, 8}
31
32
)

Sietse Ringers's avatar
Sietse Ringers committed
33
34
// metadataField contains the length and offset of a field within a metadata attribute.
type metadataField struct {
35
36
37
38
39
40
	length int
	offset int
}

// MetadataAttribute represent a metadata attribute. Contains the credential type, signing date, validity, and the public key counter.
type MetadataAttribute struct {
41
42
43
	Int  *big.Int
	pk   *gabi.PublicKey
	Conf *Configuration
44
45
}

46
47
48
// AttributeList contains attributes, excluding the secret key,
// providing convenient access to the metadata attribute.
type AttributeList struct {
49
	*MetadataAttribute `json:"-"`
50
	Ints               []*big.Int
Sietse Ringers's avatar
Sietse Ringers committed
51
	strings            []TranslatedString
52
	info               *CredentialInfo
53
	h                  string
54
55
}

56
// NewAttributeListFromInts initializes a new AttributeList from a list of bigints.
57
func NewAttributeListFromInts(ints []*big.Int, conf *Configuration) *AttributeList {
58
	return &AttributeList{
59
		Ints:              ints,
60
		MetadataAttribute: MetadataFromInt(ints[0], conf),
61
	}
62
63
}

64
func (al *AttributeList) Info() *CredentialInfo {
65
	if al.info == nil {
66
		al.info = NewCredentialInfo(al.Ints, al.Conf)
67
	}
68
	return al.info
69
70
}

71
func (al *AttributeList) Hash() string {
72
73
74
75
76
77
78
	if al.h == "" {
		bytes := []byte{}
		for _, i := range al.Ints {
			bytes = append(bytes, i.Bytes()...)
		}
		shasum := sha256.Sum256(bytes)
		al.h = hex.EncodeToString(shasum[:])
79
	}
80
	return al.h
81
82
}

83
// Strings converts the current instance to human-readable strings.
Sietse Ringers's avatar
Sietse Ringers committed
84
func (al *AttributeList) Strings() []TranslatedString {
85
	if al.strings == nil {
Sietse Ringers's avatar
Sietse Ringers committed
86
		al.strings = make([]TranslatedString, len(al.Ints)-1)
87
		for index, num := range al.Ints[1:] { // skip metadata
Sietse Ringers's avatar
Sietse Ringers committed
88
			al.strings[index] = map[string]string{"en": string(num.Bytes()), "nl": string(num.Bytes())} // TODO
89
90
91
92
		}
	}
	return al.strings
}
93

94
func (al *AttributeList) UntranslatedAttribute(identifier AttributeTypeIdentifier) string {
95
96
97
	if al.CredentialType().Identifier() != identifier.CredentialTypeIdentifier() {
		return ""
	}
98
	for i, desc := range al.CredentialType().Attributes {
99
		if desc.ID == string(identifier.Name()) {
Sietse Ringers's avatar
Sietse Ringers committed
100
			return string(al.Ints[i+1].Bytes())
101
102
103
104
105
		}
	}
	return ""
}

Sietse Ringers's avatar
Sietse Ringers committed
106
107
108
109
110
111
112
113
114
115
116
117
118
// 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
}

119
// MetadataFromInt wraps the given Int
120
121
func MetadataFromInt(i *big.Int, conf *Configuration) *MetadataAttribute {
	return &MetadataAttribute{Int: i, Conf: conf}
122
123
124
125
126
127
128
129
}

// NewMetadataAttribute constructs a new instance containing the default values:
// 0x02 as versionField
// now as signing date
// 0 as keycounter
// ValidityDefault (half a year) as default validity.
func NewMetadataAttribute() *MetadataAttribute {
130
	val := MetadataAttribute{new(big.Int), nil, nil}
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
	val.setField(versionField, metadataVersion)
	val.setSigningDate()
	val.setKeyCounter(0)
	val.setValidityDuration(ValidityDefault)
	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.
149
func (attr *MetadataAttribute) PublicKey() (*gabi.PublicKey, error) {
150
	if attr.pk == nil {
151
		var err error
152
		attr.pk, err = attr.Conf.PublicKey(attr.CredentialType().IssuerIdentifier(), attr.KeyCounter())
153
154
155
		if err != nil {
			return nil, err
		}
156
	}
157
	return attr.pk, nil
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
}

// 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))
}

Sietse Ringers's avatar
Sietse Ringers committed
195
func (attr *MetadataAttribute) setExpiryDate(timestamp *Timestamp) error {
Sietse Ringers's avatar
Sietse Ringers committed
196
	if timestamp == nil {
Sietse Ringers's avatar
Sietse Ringers committed
197
		attr.setValidityDuration(ValidityDefault)
Sietse Ringers's avatar
Sietse Ringers committed
198
199
		return nil
	}
Sietse Ringers's avatar
Sietse Ringers committed
200
201
202
203
204
205
	expiry := time.Time(*timestamp).Unix()
	signing := attr.SigningDate().Unix()
	attr.setValidityDuration(int((expiry - signing) / ExpiryFactor))
	return nil
}

206
// CredentialType returns the credential type of the current instance
207
// using the Configuration.
208
func (attr *MetadataAttribute) CredentialType() *CredentialType {
209
	return attr.Conf.hashToCredentialType(attr.field(credentialID))
210
211
}

212
func (attr *MetadataAttribute) setCredentialTypeIdentifier(id string) {
213
214
215
216
	bytes := sha256.Sum256([]byte(id))
	attr.setField(credentialID, bytes[:16])
}

217
218
219
220
func (attr *MetadataAttribute) CredentialTypeHash() []byte {
	return attr.field(credentialID)
}

221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
// 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())
}

Sietse Ringers's avatar
Sietse Ringers committed
237
func (attr *MetadataAttribute) field(field metadataField) []byte {
238
239
240
	return attr.Bytes()[field.offset : field.offset+field.length]
}

Sietse Ringers's avatar
Sietse Ringers committed
241
func (attr *MetadataAttribute) setField(field metadataField, value []byte) {
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
	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
}
271

272
273
274
275
276
// A DisclosureChoice contains the attributes chosen to be disclosed.
type DisclosureChoice struct {
	Attributes []*AttributeIdentifier
}

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
// An AttributeDisjunction encapsulates a list of possible attributes, one
// of which should be disclosed.
type AttributeDisjunction struct {
	Label      string
	Attributes []AttributeTypeIdentifier
	Values     map[AttributeTypeIdentifier]string

	selected *AttributeTypeIdentifier
}

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

// 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
}

310
311
312
// MatchesConfig returns true if all attributes contained in the disjunction are
// present in the specified configuration.
func (disjunction *AttributeDisjunction) MatchesConfig(conf *Configuration) bool {
313
	for ai := range disjunction.Values {
314
		creddescription, exists := conf.CredentialTypes[ai.CredentialTypeIdentifier()]
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
		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 {
		Label      string                             `json:"label"`
		Attributes map[AttributeTypeIdentifier]string `json:"attributes"`
	}{
		Label:      disjunction.Label,
		Attributes: disjunction.Values,
	}
	return json.Marshal(temp)
}

// UnmarshalJSON unmarshals an attribute disjunction from JSON.
func (disjunction *AttributeDisjunction) UnmarshalJSON(bytes []byte) error {
	if disjunction.Values == nil {
		disjunction.Values = make(map[AttributeTypeIdentifier]string)
	}
	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
386
387
388
	if err := json.Unmarshal(bytes, &temp); err != nil {
		return err
	}
389
390
391
392
393
394
395
396
	disjunction.Label = temp.Label

	switch temp.Attributes.(type) {
	case map[string]interface{}:
		temp := struct {
			Label      string            `json:"label"`
			Attributes map[string]string `json:"attributes"`
		}{}
Sietse Ringers's avatar
Sietse Ringers committed
397
398
399
		if err := json.Unmarshal(bytes, &temp); err != nil {
			return err
		}
400
401
402
403
404
405
406
407
408
409
		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
410
411
412
		if err := json.Unmarshal(bytes, &temp); err != nil {
			return err
		}
413
414
415
416
417
418
419
420
421
		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
}