-
Notifications
You must be signed in to change notification settings - Fork 41
/
common.go
474 lines (422 loc) · 11.7 KB
/
common.go
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
package common
import (
"crypto/rand"
"encoding/base64"
"encoding/hex"
"encoding/json"
"encoding/xml"
"fmt"
"github.com/go-errors/errors"
"github.com/privacybydesign/gabi/big"
"github.com/sirupsen/logrus"
"io"
"os"
"path"
"path/filepath"
"strings"
)
var Logger *logrus.Logger
// ForceHTTPS disables HTTP forcing in irma.HTTPTransport for all instances,
// regardless of the instance's ForceHTTPS member.
// Only for use in unit tests.
var ForceHTTPS = true
const (
AlphanumericChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
NumericChars = "0123456789"
sessionTokenLength = 20 // duplicated in SessionTokenRegex as strconv.Itoa cannot be used in const block
pairingCodeLength = 4
SessionTokenRegex = "[" + AlphanumericChars + "]{20}"
)
// AssertPathExists returns nil only if it has been successfully
// verified that all specified paths exists.
func AssertPathExists(paths ...string) error {
for _, p := range paths {
exist, err := PathExists(p)
if err != nil {
return err
}
if !exist {
return errors.Errorf("Path %s does not exist", p)
}
}
return nil
}
func AssertPathNotExists(paths ...string) error {
for _, p := range paths {
exist, err := PathExists(p)
if err != nil {
return err
}
if exist {
return errors.Errorf("Path %s exists but should not", p)
}
}
return nil
}
// PathExists checks if the specified path exists.
func PathExists(path string) (bool, error) {
_, exists, err := Stat(path)
return exists, err
}
func Stat(path string) (os.FileInfo, bool, error) {
info, err := os.Lstat(path)
if err == nil {
return info, true, nil
}
if os.IsNotExist(err) {
return nil, false, nil
}
return nil, false, err
}
func EnsureDirectoryExists(path string) error {
info, exists, err := Stat(path)
if err != nil {
return err
}
if !exists {
return os.MkdirAll(path, 0700)
}
if !info.IsDir() {
return errors.Errorf("path %s exists but is not a directory", path)
}
return nil
}
// SaveFile saves the file contents at the specified path atomically:
// - first save the content in a temp file with a random filename in the same dir
// - then rename the temp file to the specified filepath, overwriting the old file
func SaveFile(fpath string, content []byte) (err error) {
fpath = filepath.FromSlash(fpath)
Logger.Debug("writing ", fpath)
info, exists, err := Stat(fpath)
if err != nil {
return err
}
if exists && (info.IsDir() || !info.Mode().IsRegular()) {
return errors.New("invalid destination path: not a file")
}
// Only accept 'simple' paths without . or .. or multiple separators
if fpath != filepath.Clean(fpath) {
return errors.New("invalid destination path")
}
// Read random data for filename and convert to hex
randBytes := make([]byte, 16)
_, err = rand.Read(randBytes)
if err != nil {
return
}
tempfilename := hex.EncodeToString(randBytes)
// Create temp file
dir := path.Dir(fpath)
err = os.WriteFile(filepath.Join(dir, tempfilename), content, 0600)
if err != nil {
return
}
// Rename, overwriting old file
return os.Rename(filepath.Join(dir, tempfilename), fpath)
}
func CopyDirectory(src, dest string) error {
if err := EnsureDirectoryExists(dest); err != nil {
return err
}
return filepath.Walk(src, func(path string, info os.FileInfo, err error) (e error) {
if err != nil {
return err
}
if path == src {
return
}
relPath, err := filepath.Rel(src, path)
if err != nil {
return err
}
destPath := filepath.Join(dest, relPath)
if info.IsDir() {
if err := EnsureDirectoryExists(destPath); err != nil {
return err
}
} else {
srcfile, err := os.Open(path)
if err != nil {
return err
}
defer func() { e = srcfile.Close() }()
bts, err := io.ReadAll(srcfile)
if err != nil {
return err
}
if err := SaveFile(destPath, bts); err != nil {
return err
}
}
return
})
}
// ReadKey returns either the content of the file specified at path, if it exists,
// or []byte(key) otherwise. It is an error to specify both or none arguments, or
// specify an empty or unreadable file. If there is no error then the return []byte is non-empty.
func ReadKey(key, path string) ([]byte, error) {
if (key != "" && path != "") || (key == "" && path == "") {
return nil, errors.New("provide either key or path to key")
}
var bts []byte
if path == "" {
bts = []byte(key)
} else {
stat, err := os.Stat(path)
if err != nil {
return nil, errors.WrapPrefix(err, "failed to stat key", 0)
}
if stat.IsDir() {
return nil, errors.New("cannot read key from a directory")
}
if !stat.Mode().IsRegular() {
return nil, errors.New("cannot read key from nonregular file")
}
bts, err = os.ReadFile(path)
if err != nil {
return nil, err
}
}
if len(bts) == 0 {
return nil, errors.New("empty key provided")
}
return bts, nil
}
// Base64Decode decodes the specified bytes as any of the Base64 dialects:
// standard encoding (+, /) and URL encoding (-, _), with or without padding.
func Base64Decode(b []byte) ([]byte, error) {
var (
err error
bts []byte
encodings = []*base64.Encoding{base64.RawStdEncoding, base64.URLEncoding, base64.RawURLEncoding, base64.StdEncoding}
)
for _, encoding := range encodings {
if bts, err = encoding.DecodeString(string(b)); err == nil {
break
}
}
return bts, err
}
// IterateSubfolders iterates over the subfolders of the specified path,
// calling the specified handler each time. If anything goes wrong, or
// if the caller returns a non-nil error, an error is immediately returned.
func IterateSubfolders(path string, handler func(string, os.FileInfo) error) error {
return iterateFiles(path, true, handler)
}
func iterateFiles(path string, onlyDirs bool, handler func(string, os.FileInfo) error) error {
files, err := filepath.Glob(filepath.Join(path, "*"))
if err != nil {
return err
}
for _, file := range files {
stat, err := os.Stat(file)
if err != nil {
return err
}
if onlyDirs && !stat.IsDir() {
continue
}
if filepath.Base(file) == ".git" {
continue
}
err = handler(file, stat)
if err != nil {
return err
}
}
return nil
}
// WalkDir recursively walks the file tree rooted at path, following symlinks (unlike filepath.Walk).
// Avoiding loops is the responsibility of the caller.
func WalkDir(path string, handler func(string, os.FileInfo) error) error {
return iterateFiles(path, false, func(p string, info os.FileInfo) error {
if info.IsDir() {
if err := handler(p, info); err != nil {
return err
}
return WalkDir(p, handler)
}
return handler(p, info)
})
}
func RandomBigInt(limit *big.Int) *big.Int {
res, err := big.RandInt(rand.Reader, limit)
if err != nil {
panic(fmt.Sprintf("big.RandInt failed: %v", err))
}
return res
}
type SSECtx struct {
Component, Arg string
}
func NewSessionToken() string {
return NewRandomString(sessionTokenLength, AlphanumericChars)
}
func NewPairingCode() string {
return NewRandomString(pairingCodeLength, NumericChars)
}
func NewRandomString(count int, characterSet string) string {
// We read bytes (0-255) from the secure random number generator.
// If the character set length is smaller than and not a divider of 256, we should only consider the random numbers
// smaller than the character set length minus the remainder after division. This ensures an even distribution.
byteValueUpperbound := uint8(256 - (256 % len(characterSet)))
// We collect 16 bytes of randomness at once for efficiency.
randomnessBuffer := make([]byte, 16)
b := make([]byte, count)
i := 0
for bufferIndex := 0; i < len(b); bufferIndex = (bufferIndex + 1) % len(randomnessBuffer) {
if bufferIndex == 0 {
_, err := rand.Read(randomnessBuffer)
if err != nil {
panic(err)
}
}
byteValue := randomnessBuffer[bufferIndex]
if byteValueUpperbound == 0 || byteValue < byteValueUpperbound {
if len(characterSet) < 256 {
byteValue = byteValue % byte(len(characterSet))
}
b[i] = characterSet[byteValue]
i++
}
}
return string(b)
}
func IsIrmaconfDir(dir string) (bool, error) {
if ok, err := containsSchemes(dir); err != nil || !ok {
return false, err
}
return true, nil
}
func IsScheme(dir string, expectSignature bool) (bool, error) {
filenames := []string{"description.xml", "description.json"}
filenameloop:
for _, filename := range filenames {
files := []string{filename}
if expectSignature {
files = append(files, "timestamp", "index", "index.sig")
}
for _, file := range files {
exists, err := PathExists(filepath.Join(dir, file))
if err != nil {
return false, err
}
if !exists {
continue filenameloop
}
}
return true, nil
}
return false, nil
}
func ValidateSchemeID(id string) error {
// We use the format 'schemeManager.issuer.credential.attribute' in full identifiers,
// so dots can never be in a valid scheme id.
if strings.Contains(id, ".") {
return errors.New("scheme id contains a dot")
}
if IsTempSchemeDir(id) {
return errors.New("scheme id uses forbidden prefix")
}
return nil
}
func IsTempSchemeDir(dirname string) bool {
if strings.HasPrefix(dirname, ".tempscheme") || strings.HasPrefix(dirname, ".oldscheme") {
return true
}
// In irmago version 0.11.0 and below, temporary directories were not marked as hidden yet. So, there
// might be directories starting with 'tempscheme' or 'oldscheme' that should not be considered as a scheme.
// To prevent directory name clashes, we forbid scheme IDs starting with these prefixes.
if strings.HasPrefix(dirname, "tempscheme") || strings.HasPrefix(dirname, "oldscheme") {
return true
}
return false
}
func containsSchemes(dir string) (bool, error) {
var (
hasSubdirs bool
hasOnlySchemes = true
)
err := IterateSubfolders(dir, func(d string, info os.FileInfo) error {
if !hasOnlySchemes {
return nil
}
hasSubdirs = true
s, err := IsScheme(d, true)
if err != nil {
return err
}
hasOnlySchemes = s
return nil
})
if !hasSubdirs || !hasOnlySchemes {
return false, nil
}
return err == nil, err
}
func SchemeInfo(filename string, bts []byte) (string, string, error) {
temp := struct {
Type string `json:"schemetype" xml:"SchemeType"`
ID string `json:"id" xml:"Id"`
}{}
if err := Unmarshal(filename, bts, &temp); err != nil {
return "", "", err
}
if temp.Type == "" {
temp.Type = "issuer"
}
if temp.Type != "issuer" && temp.Type != "requestor" {
return "", "", errors.New("unsupported scheme type")
}
if err := ValidateSchemeID(temp.ID); err != nil {
return "", "", errors.WrapPrefix(err, fmt.Sprintf("invalid scheme id %s", temp.ID), 0)
}
return temp.ID, temp.Type, nil
}
func Unmarshal(filename string, bts []byte, dest interface{}) error {
switch filepath.Ext(filename) {
case ".xml":
return xml.Unmarshal(bts, dest)
case ".json":
return json.Unmarshal(bts, dest)
default:
return errors.New("unsupported file format")
}
}
func SchemeFilename(dir string) (string, error) {
for _, filename := range SchemeFilenames {
exists, err := PathExists(filepath.Join(dir, filename))
if err != nil {
return "", err
}
if exists {
return filename, nil
}
}
return "", errors.Errorf("no scheme file found in directory %s", dir)
}
var SchemeFilenames = []string{"description.xml", "description.json"}
// Close is a helper for absorbing errors in the `defer x.Close()` pattern
func Close(o io.Closer) {
_ = o.Close()
}
func ParseLDContext(bts []byte) (string, error) {
var v struct {
LDContext string `json:"@context"`
}
if err := json.Unmarshal(bts, &v); err != nil {
return "", err
}
return v.LDContext, nil
}
func ParseNestedLDContext(bts []byte) (string, error) {
var v struct {
Request struct {
LDContext string `json:"@context"`
} `json:"request"`
}
if err := json.Unmarshal(bts, &v); err != nil {
return "", err
}
return v.Request.LDContext, nil
}