verify.go 10.1 KB
Newer Older
1 2 3 4 5 6
package irma

import (
	"fmt"
	"math/big"
	"time"
7 8 9

	"github.com/go-errors/errors"
	"github.com/mhe/gabi"
10 11 12 13 14 15 16 17 18
)

// ProofStatus is the status of the complete proof
type ProofStatus string

const (
	VALID              = ProofStatus("VALID")
	EXPIRED            = ProofStatus("EXPIRED")
	INVALID_CRYPTO     = ProofStatus("INVALID_CRYPTO")
19
	UNMATCHED_REQUEST  = ProofStatus("UNMATCHED_REQUEST")
20 21 22 23 24
	MISSING_ATTRIBUTES = ProofStatus("MISSING_ATTRIBUTES")
)

// ProofResult is a result of a complete proof, containing all the disclosed attributes and corresponding request
type ProofResult struct {
25
	Disjunctions []*DisclosedAttributeDisjunction `json:"disjunctions"`
26 27 28 29
	ProofStatus  ProofStatus
}

type SignatureProofResult struct {
30
	*ProofResult
31
	Message string `json:"message"`
32 33 34 35 36
}

// DisclosedCredential contains raw disclosed credentials, without any extra parsing information
type DisclosedCredential struct {
	metadataAttribute *MetadataAttribute
37
	Attributes        map[AttributeTypeIdentifier]*string `json:"attributes"`
38 39
}

40 41 42 43 44 45
type DisclosedCredentialList []*DisclosedCredential

// Helper function to check if an attribute is satisfied against a list of disclosed attributes
// This is the case if:
// attribute is contained in disclosed AND if a value is present: equal to that value
// al can be nil if you don't want to include attribute status for proof
46
func (disclosed DisclosedCredentialList) isAttributeSatisfied(attributeId AttributeTypeIdentifier, requestedValue *string) (bool, *AttributeResult) {
47 48 49 50 51
	ar := AttributeResult{
		AttributeId: attributeId,
	}

	for _, cred := range disclosed {
52
		disclosedAttributeValue := cred.Attributes[attributeId]
53 54

		// Continue to next credential if requested attribute isn't disclosed in this credential
55
		if disclosedAttributeValue == nil {
56 57 58 59 60 61 62
			continue
		}

		// If this is the disclosed attribute, check if value matches
		// Attribute is satisfied if:
		// - Attribute is disclosed (i.e. not nil)
		// - Value is empty OR value equal to disclosedValue
63
		ar.AttributeValue = *disclosedAttributeValue
64

65
		if requestedValue == nil || *disclosedAttributeValue == *requestedValue {
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
			ar.AttributeProofStatus = PRESENT
			return true, &ar
		} else {
			// If attribute is disclosed and present, but not equal to required value, mark it as invalid_value
			// We won't return true and continue searching in other disclosed attributes
			ar.AttributeProofStatus = INVALID_VALUE
		}
	}

	// If there is never a value assigned, then this attribute isn't disclosed, and thus missing
	if ar.AttributeValue == "" {
		ar.AttributeProofStatus = MISSING
	}
	return false, &ar
}

// Create a signature proof result and check disclosed credentials against a signature request
func (disclosed DisclosedCredentialList) createAndCheckSignatureProofResult(configuration *Configuration, sigRequest *SignatureRequest) *SignatureProofResult {
	signatureProofResult := SignatureProofResult{
		ProofResult: &ProofResult{},
86
		Message:     sigRequest.Message,
87 88 89
	}
	for _, content := range sigRequest.Content {
		isSatisfied, disjunction := content.SatisfyDisclosed(disclosed, configuration)
90
		signatureProofResult.Disjunctions = append(signatureProofResult.Disjunctions, disjunction)
91 92 93 94 95 96 97 98 99 100 101

		// If satisfied, continue to next one
		if isSatisfied {
			continue
		}

		// Else, set proof status to missing_attributes, but check other as well to add other disjunctions to result
		// (so user also knows attribute status of other disjunctions)
		signatureProofResult.ProofStatus = MISSING_ATTRIBUTES
	}

102
	signatureProofResult.Disjunctions = addExtraAttributes(disclosed, signatureProofResult.ProofResult)
103 104 105 106 107 108 109 110 111 112 113 114 115
	return &signatureProofResult
}

// Returns true if one of the disclosed credentials is expired
func (disclosed DisclosedCredentialList) IsExpired() bool {
	for _, cred := range disclosed {
		if cred.IsExpired() {
			return true
		}
	}
	return false
}

116
func (proofResult *ProofResult) ToAttributeResultList() AttributeResultList {
117 118
	var resultList AttributeResultList

119
	for _, v := range proofResult.Disjunctions {
120 121 122 123 124 125
		result := AttributeResult{
			AttributeValue:       v.DisclosedValue,
			AttributeId:          v.DisclosedId,
			AttributeProofStatus: v.ProofStatus,
		}

126
		resultList = append(resultList, &result)
127
	}
128
	return resultList
129 130 131 132
}

// Returns true if this attrId is present in one of the disjunctions
func (proofResult *ProofResult) ContainsAttribute(attrId AttributeTypeIdentifier) bool {
133
	for _, disj := range proofResult.Disjunctions {
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
		for _, attr := range disj.Attributes {
			if attr == attrId {
				return true
			}
		}
	}

	return false
}

func (cred *DisclosedCredential) IsExpired() bool {
	return cred.metadataAttribute.Expiry().Before(time.Now())
}

func NewDisclosedCredentialFromADisclosed(aDisclosed map[int]*big.Int, configuration *Configuration) *DisclosedCredential {
149
	attributes := make(map[AttributeTypeIdentifier]*string)
150 151 152 153 154 155 156 157 158 159

	metadata := MetadataFromInt(aDisclosed[1], configuration) // index 1 is metadata attribute
	cred := metadata.CredentialType()

	for k, v := range aDisclosed {
		if k < 2 {
			continue
		}

		description := cred.Attributes[k-2]
160 161
		attributeValue := decodeAttribute(v, metadata.Version())
		attributes[description.GetAttributeTypeIdentifier(cred.Identifier())] = attributeValue
162 163 164 165 166 167 168 169
	}

	return &DisclosedCredential{
		metadataAttribute: metadata,
		Attributes:        attributes,
	}
}

170 171
func extractPublicKeys(configuration *Configuration, proofList gabi.ProofList) ([]*gabi.PublicKey, error) {
	var publicKeys = make([]*gabi.PublicKey, 0, len(proofList))
172

173
	for _, v := range proofList {
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
		switch v.(type) {
		case *gabi.ProofD:
			proof := v.(*gabi.ProofD)
			metadata := MetadataFromInt(proof.ADisclosed[1], configuration) // index 1 is metadata attribute
			publicKey, err := metadata.PublicKey()
			if err != nil {
				return nil, err
			}
			publicKeys = append(publicKeys, publicKey)
		default:
			return nil, errors.New("Cannot extract public key, not a disclosure proofD!")
		}
	}
	return publicKeys, nil
}

190 191
func extractDisclosedCredentials(conf *Configuration, proofList gabi.ProofList) (DisclosedCredentialList, error) {
	var credentials = make(DisclosedCredentialList, 0, len(proofList))
192

193
	for _, v := range proofList {
194 195 196 197 198 199 200 201 202 203 204 205 206 207
		switch v.(type) {
		case *gabi.ProofD:
			proof := v.(*gabi.ProofD)
			cred := NewDisclosedCredentialFromADisclosed(proof.ADisclosed, conf)
			credentials = append(credentials, cred)
		default:
			return nil, errors.New("Cannot extract credentials from proof, not a disclosure proofD!")
		}
	}

	return credentials, nil
}

// Add extra disclosed attributes to an existing and checked ProofResult in 'dummy disjunctions'
208
func addExtraAttributes(disclosed DisclosedCredentialList, proofResult *ProofResult) []*DisclosedAttributeDisjunction {
209 210
	returnDisjunctions := make([]*DisclosedAttributeDisjunction, len(proofResult.Disjunctions))
	copy(returnDisjunctions, proofResult.Disjunctions)
211

212
	for _, cred := range disclosed {
213 214 215 216 217 218
		for attrId := range cred.Attributes {
			if proofResult.ContainsAttribute(attrId) {
				continue
			}

			dummyDisj := DisclosedAttributeDisjunction{
219
				DisclosedValue: *cred.Attributes[attrId],
220 221 222 223 224 225 226 227 228 229 230
				DisclosedId:    attrId,
				ProofStatus:    EXTRA,
			}
			returnDisjunctions = append(returnDisjunctions, &dummyDisj)
		}
	}

	return returnDisjunctions
}

// Check an gabi prooflist against a signature proofrequest
231 232
func checkProofWithRequest(configuration *Configuration, proofList gabi.ProofList, sigRequest *SignatureRequest) *SignatureProofResult {
	disclosed, err := extractDisclosedCredentials(configuration, proofList)
233 234 235 236

	if err != nil {
		fmt.Println(err)
		return &SignatureProofResult{
237
			ProofResult: &ProofResult{
238 239 240 241 242
				ProofStatus: INVALID_CRYPTO,
			},
		}
	}

243
	signatureProofResult := disclosed.createAndCheckSignatureProofResult(configuration, sigRequest)
244 245 246 247 248 249 250 251

	// Return MISSING_ATTRIBUTES as proofstatus if one attribute is missing
	// This status takes priority over 'EXPIRED'
	if signatureProofResult.ProofStatus == MISSING_ATTRIBUTES {
		return signatureProofResult
	}

	// If all disjunctions are satisfied, check if a credential is expired
252 253 254
	if disclosed.IsExpired() {
		signatureProofResult.ProofStatus = EXPIRED
		return signatureProofResult
255 256 257 258 259 260 261 262
	}

	// All disjunctions satisfied and nothing expired, proof is valid!
	signatureProofResult.ProofStatus = VALID
	return signatureProofResult
}

// Verify an IRMA proof cryptographically
263
func verify(configuration *Configuration, proofList gabi.ProofList, context *big.Int, nonce *big.Int, isSig bool) bool {
264 265 266 267 268 269 270 271 272 273
	// Extract public keys
	pks, err := extractPublicKeys(configuration, proofList)
	if err != nil {
		return false
	}

	return proofList.Verify(pks, context, nonce, true, isSig)
}

// Verify a signature proof and check if the attributes match the attributes in the original request
274 275 276
func VerifySig(configuration *Configuration, irmaSignature *IrmaSignedMessage, sigRequest *SignatureRequest) *SignatureProofResult {
	// First, check if nonce and context of the signature match those of the signature request
	if !irmaSignature.MatchesNonceAndContext(sigRequest) {
277
		return &SignatureProofResult{
278
			ProofResult: &ProofResult{
279
				ProofStatus: UNMATCHED_REQUEST,
280 281 282 283 284
			},
		}
	}

	// Now, cryptographically verify the signature
285
	if !verify(configuration, *irmaSignature.Signature, sigRequest.GetContext(), sigRequest.GetNonce(), true) {
286
		return &SignatureProofResult{
287
			ProofResult: &ProofResult{
288 289 290 291 292 293
				ProofStatus: INVALID_CRYPTO,
			},
		}
	}

	// Finally, check whether attribute values in proof satisfy the original signature request
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
	return checkProofWithRequest(configuration, *irmaSignature.Signature, sigRequest)
}

// Verify a signature cryptographically, but do not check/compare with a signature request
func VerifySigWithoutRequest(configuration *Configuration, irmaSignature *IrmaSignedMessage) (ProofStatus, DisclosedCredentialList) {
	// First, cryptographically verify the signature
	if !verify(configuration, *irmaSignature.Signature, irmaSignature.Context, irmaSignature.GetNonce(), true) {
		return INVALID_CRYPTO, nil
	}

	// Extract attributes and return result
	disclosed, err := extractDisclosedCredentials(configuration, *irmaSignature.Signature)

	if err != nil {
		fmt.Println(err)
		return INVALID_CRYPTO, nil
	}

	if disclosed.IsExpired() {
		return EXPIRED, disclosed
	}

	return VALID, disclosed
317
}