common.go 9.19 KB
Newer Older
1
package common
2
3
4

import (
	"crypto/rand"
5
	"encoding/base64"
6
	"encoding/hex"
7
8
	"encoding/json"
	"encoding/xml"
9
	"fmt"
10
	"io"
11
12
13
	"io/ioutil"
	"os"
	"path"
14
	"path/filepath"
15

16
	"github.com/go-errors/errors"
17
	"github.com/privacybydesign/gabi/big"
18
	"github.com/sirupsen/logrus"
19
20
)

21
22
var Logger *logrus.Logger

23
24
25
26
27
// 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

28
const (
29
30
31
	AlphanumericChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	NumericChars      = "0123456789"

32
	sessionTokenLength = 20
33
	pairingCodeLength  = 4
34
35
)

36
// AssertPathExists returns nil only if it has been successfully
37
38
39
40
41
42
43
44
45
46
// 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)
		}
47
48
49
50
	}
	return nil
}

51
52
53
54
55
56
57
58
59
60
61
62
63
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
}

64
65
// PathExists checks if the specified path exists.
func PathExists(path string) (bool, error) {
66
	_, exists, err := Stat(path)
67
68
69
	return exists, err
}

70
func Stat(path string) (os.FileInfo, bool, error) {
71
	info, err := os.Lstat(path)
72
	if err == nil {
73
		return info, true, nil
74
75
	}
	if os.IsNotExist(err) {
76
		return nil, false, nil
77
	}
78
	return nil, false, err
79
80
81
}

func EnsureDirectoryExists(path string) error {
82
	info, exists, err := Stat(path)
83
84
85
	if err != nil {
		return err
	}
86
87
	if !exists {
		return os.MkdirAll(path, 0700)
88
	}
89
	if !info.IsDir() {
90
		return errors.Errorf("path %s exists but is not a directory", path)
91
92
	}
	return nil
93
94
95
96
97
}

// Save the filecontents 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
98
func SaveFile(fpath string, content []byte) (err error) {
99
	fpath = filepath.FromSlash(fpath)
100
	Logger.Debug("writing ", fpath)
101
102
103
104
105
	info, exists, err := Stat(fpath)
	if err != nil {
		return err
	}
	if exists && (info.IsDir() || !info.Mode().IsRegular()) {
106
107
108
109
110
		return errors.New("invalid destination path: not a file")
	}

	// Only accept 'simple' paths without . or .. or multiple separators
	if fpath != filepath.Clean(fpath) {
111
112
		return errors.New("invalid destination path")
	}
113
114
115
116
117
118
119
120
121
122

	// 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
123
	dir := path.Dir(fpath)
124
	err = ioutil.WriteFile(filepath.Join(dir, tempfilename), content, 0600)
125
126
127
128
129
	if err != nil {
		return
	}

	// Rename, overwriting old file
130
	return os.Rename(filepath.Join(dir, tempfilename), fpath)
131
}
132
133
134
135
136
137

func CopyDirectory(src, dest string) error {
	if err := EnsureDirectoryExists(dest); err != nil {
		return err
	}

138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
	return filepath.Walk(src, func(path string, info os.FileInfo, err error) (e error) {
		if err != nil {
			return err
		}
		if path == src {
			return
		}
		subpath := path[len(src):]
		if info.IsDir() {
			if err := EnsureDirectoryExists(dest + subpath); err != nil {
				return err
			}
		} else {
			srcfile, err := os.Open(path)
			if err != nil {
				return err
154
			}
155
156
157
158
			defer func() { e = srcfile.Close() }()
			bts, err := ioutil.ReadAll(srcfile)
			if err != nil {
				return err
159
			}
160
161
162
163
164
165
166
			if err := SaveFile(dest+subpath, bts); err != nil {
				return err
			}
		}
		return
	})

167
}
168

169
170
171
172
173
174
175
176
// 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")
	}

177
	var bts []byte
178
179
180
181
182
183

	if path == "" {
		bts = []byte(key)
	} else {
		stat, err := os.Stat(path)
		if err != nil {
184
			return nil, errors.WrapPrefix(err, "failed to stat key", 0)
185
		}
186
187
188
		if stat.IsDir() {
			return nil, errors.New("cannot read key from a directory")
		}
189
190
191
		if !stat.Mode().IsRegular() {
			return nil, errors.New("cannot read key from nonregular file")
		}
192
		bts, err = ioutil.ReadFile(path)
193
194
195
		if err != nil {
			return nil, err
		}
196
197
198
199
	}

	if len(bts) == 0 {
		return nil, errors.New("empty key provided")
200
201
202
203
	}
	return bts, nil
}

204
205
// Base64Decode decodes the specified bytes as any of the Base64 dialects:
// standard encoding (+, /) and URL encoding (-, _), with or without padding.
206
207
208
209
210
211
212
213
214
215
216
217
218
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
}
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

// 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)
	})
}
266
267
268
269
270
271
272
273

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
}
274
275
276
277

type SSECtx struct {
	Component, Arg string
}
278
279

func NewSessionToken() string {
280
	return NewRandomString(sessionTokenLength, AlphanumericChars)
281
282
}

283
func NewPairingCode() string {
284
	return NewRandomString(pairingCodeLength, NumericChars)
285
286
}

287
func NewRandomString(count int, characterSet string) string {
288
	r := make([]byte, count)
289
290
291
292
293
	_, err := rand.Read(r)
	if err != nil {
		panic(err)
	}

294
	b := make([]byte, count)
295
	for i := range b {
296
		b[i] = characterSet[r[i]%byte(len(characterSet))]
297
298
299
	}
	return string(b)
}
300
301

func IsIrmaconfDir(dir string) (bool, error) {
302
	if ok, err := containsSchemes(dir); err != nil || !ok {
303
304
305
306
307
		return false, err
	}
	return true, nil
}

308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
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
327
328
	}

329
330
	return false, nil
}
331

332
func containsSchemes(dir string) (bool, error) {
333
334
335
336
337
338
339
340
341
	var (
		hasSubdirs     bool
		hasOnlySchemes = true
	)
	err := IterateSubfolders(dir, func(d string, info os.FileInfo) error {
		if !hasOnlySchemes {
			return nil
		}
		hasSubdirs = true
342
		s, err := IsScheme(d, true)
343
344
345
346
347
348
349
350
351
352
353
354
355
		if err != nil {
			return err
		}
		hasOnlySchemes = s
		return nil
	})

	if !hasSubdirs || !hasOnlySchemes {
		return false, nil
	}
	return err == nil, err
}

356
357
358
359
360
361
362
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
363
	}
364
365
	if temp.Type == "" {
		temp.Type = "issuer"
366
367
	}

368
369
	if temp.Type != "issuer" && temp.Type != "requestor" {
		return "", "", errors.New("unsupported scheme type")
370
	}
371
	return temp.ID, temp.Type, nil
372
373
}

374
375
376
377
378
379
380
381
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")
382
383
384
	}
}

385
386
387
388
389
390
391
392
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
393
394
		}
	}
395
	return "", errors.New("no scheme file found")
396
}
397
398

var SchemeFilenames = []string{"description.xml", "description.json"}
399
400
401
402
403

// Helper for absorbing errors in the `defer x.Close()` pattern
func Close(o io.Closer) {
	_ = o.Close()
}