session.go 7.84 KB
Newer Older
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
package cmd

import (
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"strconv"
	"strings"

	"github.com/Sirupsen/logrus"
	"github.com/go-errors/errors"
	"github.com/mdp/qrterminal"
	"github.com/privacybydesign/irmago"
	"github.com/privacybydesign/irmago/server"
	"github.com/privacybydesign/irmago/server/irmarequestor"
	"github.com/spf13/cobra"
)

// sessionCmd represents the session command
var sessionCmd = &cobra.Command{
	Use:   "session",
	Short: "Perform an IRMA disclosure, issuance or signature session",
	Example: `irma session --disclose irma-demo.MijnOverheid.root.BSN
irma session --sign irma-demo.MijnOverheid.root.BSN --message message
irma session --issue irma-demo.MijnOverheid.ageLower=yes,yes,yes,no --disclose irma-demo.MijnOverheid.root.BSN`,
	Run: func(cmd *cobra.Command, args []string) {
		request, err := configure(cmd)
		if err != nil {
			die("", err)
		}
		port, _ := cmd.Flags().GetInt("port")
		startServer(port)

		// Start the session
		resultchan := make(chan *server.SessionResult)
		qr, _, err := irmarequestor.StartSession(request, func(r *server.SessionResult) {
			resultchan <- r
		})
		if err != nil {
			die("IRMA session failed", err)
		}

		// Print QR code
		noqr, _ := cmd.Flags().GetBool("noqr")
		if err := printQr(qr, noqr); err != nil {
			die("Failed to print QR", err)
		}

		// Wait for session to finish and then print session result
		result := <-resultchan
		printSessionResult(result)

		// Done!
		_ = irmaServer.Close()
	},
}

func init() {
	RootCmd.AddCommand(sessionCmd)

	flags := sessionCmd.Flags()
	flags.SortFlags = false
	flags.StringP("irmaconf", "i", defaultIrmaconfPath(), "path to irma_configuration")
	flags.StringP("privatekeys", "k", "", "path to private keys")
	flags.IntP("port", "p", 48680, "port to listen at")
	flags.BoolP("noqr", "q", false, "Don't print as QR")
	flags.CountP("verbose", "v", "verbose (repeatable)")

	flags.StringArray("disclose", nil, "Add an attribute disjunction (comma-separated)")
	flags.StringArray("issue", nil, "Add a credential to issue")
	flags.StringArray("sign", nil, "Add an attribute disjunction to signature session")
	flags.String("message", "", "Message to sign in signature session")
}

var irmaServer *http.Server
var logger *logrus.Logger

func constructSessionRequest(cmd *cobra.Command, conf *irma.Configuration) (irma.SessionRequest, error) {
	disclose, _ := cmd.Flags().GetStringArray("disclose")
	issue, _ := cmd.Flags().GetStringArray("issue")
	sign, _ := cmd.Flags().GetStringArray("sign")
	message, _ := cmd.Flags().GetString("message")

	if len(sign) != 0 {
		if len(disclose) != 0 {
			return nil, errors.New("cannot combine disclosure and signature sessions, use either --disclose or --sign")
		}
		if len(issue) != 0 {
			return nil, errors.New("cannot combine issuance and signature sessions, use either --issue or --sign")
		}
		if message == "" {
			return nil, errors.New("signature sessions require a message to be signed using --message")
		}
	}

	var request irma.SessionRequest
	if len(disclose) != 0 {
		disjunctions, err := parseDisjunctions(disclose, conf)
		if err != nil {
			return nil, err
		}
		request = &irma.DisclosureRequest{
			BaseRequest: irma.BaseRequest{
				Type: irma.ActionDisclosing,
			},
			Content: disjunctions,
		}
	}
	if len(sign) != 0 {
		disjunctions, err := parseDisjunctions(sign, conf)
		if err != nil {
			return nil, err
		}
		request = &irma.SignatureRequest{
			DisclosureRequest: irma.DisclosureRequest{
				BaseRequest: irma.BaseRequest{
					Type: irma.ActionSigning,
				},
				Content: disjunctions,
			},
			Message: message,
		}
	}
	if len(issue) != 0 {
		creds, err := parseCredentials(issue, conf)
		if err != nil {
			return nil, err
		}
		disjunctions, err := parseDisjunctions(disclose, conf)
		if err != nil {
			return nil, err
		}
		request = &irma.IssuanceRequest{
			BaseRequest: irma.BaseRequest{
				Type: irma.ActionIssuing,
			},
			Credentials: creds,
			Disclose:    disjunctions,
		}
	}

	return request, nil
}

func parseCredentials(credentialsStr []string, conf *irma.Configuration) ([]*irma.CredentialRequest, error) {
	list := make([]*irma.CredentialRequest, 0, len(credentialsStr))

	for _, credStr := range credentialsStr {
		parts := strings.Split(credStr, "=")
		if len(parts) != 2 {
			return nil, errors.New("--issue argument must contain exactly 1 = sign")
		}
		credIdStr, attrsStr := parts[0], parts[1]
		credtype := conf.CredentialTypes[irma.NewCredentialTypeIdentifier(credIdStr)]
		if credtype == nil {
			return nil, errors.New("unknown credential type: " + credIdStr)
		}

		attrsSlice := strings.Split(attrsStr, ",")
		if len(attrsSlice) != len(credtype.AttributeTypes) {
			return nil, errors.Errorf("%d attributes required but %d provided for %s", len(credtype.AttributeTypes), len(attrsSlice), credIdStr)
		}

		attrs := make(map[string]string, len(attrsSlice))
		for i, typ := range credtype.AttributeTypes {
			attrs[typ.ID] = attrsSlice[i]
		}
		list = append(list, &irma.CredentialRequest{
			CredentialTypeID: irma.NewCredentialTypeIdentifier(credIdStr),
			Attributes:       attrs,
		})
	}

	return list, nil
}

func parseDisjunctions(disjunctionsStr []string, conf *irma.Configuration) (irma.AttributeDisjunctionList, error) {
	list := make(irma.AttributeDisjunctionList, 0, len(disjunctionsStr))
	for _, disjunctionStr := range disjunctionsStr {
		disjunction := &irma.AttributeDisjunction{}
		attrids := strings.Split(disjunctionStr, ",")
		for _, attridStr := range attrids {
			attrid := irma.NewAttributeTypeIdentifier(attridStr)
			if conf.AttributeTypes[attrid] == nil {
				return nil, errors.New("unknown attribute: " + attridStr)
			}
			disjunction.Attributes = append(disjunction.Attributes, attrid)
		}
		disjunction.Label = disjunction.Attributes[0].Name()
		list = append(list, disjunction)
	}
	return list, nil
}

func configure(cmd *cobra.Command) (irma.SessionRequest, error) {
	irmaconfigPath, err := cmd.Flags().GetString("irmaconf")
	if err != nil {
		return nil, err
	}
	privatekeysPath, err := cmd.Flags().GetString("privatekeys")
	if err != nil {
		return nil, err
	}
	ip, err := server.LocalIP()
	if err != nil {
		return nil, err
	}

	conf, err := irma.NewConfiguration(irmaconfigPath)
	if err != nil {
		return nil, err
	}
	if err = conf.ParseFolder(); err != nil {
		return nil, err
	}
	if len(conf.SchemeManagers) == 0 {
		if err = conf.DownloadDefaultSchemes(); err != nil {
			return nil, err
		}
	}

	verbosity, _ := cmd.Flags().GetCount("verbose")
	port, _ := cmd.Flags().GetInt("port")
	logger = logrus.New()
	logger.Level = server.Verbosity(verbosity)
	logger.Formatter = &logrus.TextFormatter{FullTimestamp: true}
	config := &server.Configuration{
		IrmaConfiguration: conf,
		Logger:            logger,
		URL:               "http://" + ip + ":" + strconv.Itoa(port),
	}
	if privatekeysPath != "" {
		config.IssuerPrivateKeysPath = privatekeysPath
	}

	request, err := constructSessionRequest(cmd, conf)
	if err != nil {
		return nil, err
	}
	logger.Debugf("Session request: %s", prettyprint(request))

	return request, irmarequestor.Initialize(config)
}

func startServer(port int) {
	mux := http.NewServeMux()
	mux.HandleFunc("/", irmarequestor.HttpHandlerFunc())
	irmaServer = &http.Server{Addr: ":" + strconv.Itoa(port), Handler: mux}
	go func() {
		err := irmaServer.ListenAndServe()
		if err != nil && err != http.ErrServerClosed {
			die("Failed to start server", err)
		}
	}()
}

func printQr(qr *irma.Qr, noqr bool) error {
	qrBts, err := json.Marshal(qr)
	if err != nil {
		return err
	}
	if noqr {
		fmt.Println(string(qrBts))
	} else {
		qrterminal.GenerateWithConfig(string(qrBts), qrterminal.Config{
			Level:     qrterminal.L,
			Writer:    os.Stdout,
			BlackChar: qrterminal.BLACK,
			WhiteChar: qrterminal.WHITE,
		})
	}
	return nil
}

func printSessionResult(result *server.SessionResult) {
	res, err := json.MarshalIndent(result, "", "    ")
	if err != nil {
		fmt.Println(err.Error())
	}
	fmt.Println("Session result:")
	fmt.Println(string(res))
}