storage.go 6.33 KB
Newer Older
1
2
3
4
5
6
7
8
9
package irmago

import (
	"encoding/json"
	"errors"
	"io/ioutil"
	"os"
	"strconv"

Sietse Ringers's avatar
Sietse Ringers committed
10
11
12
13
	"crypto/rand"
	"encoding/hex"
	"math/big"
	"path"
14
15

	"github.com/mhe/gabi"
16
17
18
19
20
21
)

// Filenames in which we store stuff
const (
	skFile         = "sk"
	attributesFile = "attrs"
22
23
	kssFile        = "kss"
	paillierFile   = "paillier"
24
	signaturesDir  = "sigs"
Sietse Ringers's avatar
Sietse Ringers committed
25
	cardemuXML     = "../cardemu.xml"
26
27
)

Sietse Ringers's avatar
Sietse Ringers committed
28
// PathExists checks if the specified path exists.
29
func PathExists(path string) (bool, error) {
30
31
32
33
34
35
36
37
38
39
40
41
42
43
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return true, err
}

func (cm *CredentialManager) path(file string) string {
	return cm.storagePath + "/" + file
}

Sietse Ringers's avatar
Sietse Ringers committed
44
45
46
47
48
49
50
51
52
func (cm *CredentialManager) signatureFilename(id string, counter int) string {
	return cm.path(signaturesDir) + "/" + id + "-" + strconv.Itoa(counter)
}

// ensureStorageExists initializes the credential storage folder,
// ensuring that it is in a usable state.
// NOTE: we do not create the folder if it does not exist!
// Setting it up in a properly protected location (e.g., with automatic
// backups to iCloud/Google disabled) is the responsibility of the user.
53
func (cm *CredentialManager) ensureStorageExists() (err error) {
54
	exist, err := PathExists(cm.storagePath)
55
56
57
58
59
60
61
	if err != nil {
		return
	}
	if !exist {
		return errors.New("credential storage path does not exist")
	}

62
	exist, err = PathExists(cm.path(signaturesDir))
63
64
65
66
67
68
69
70
71
72
	if err != nil {
		return err
	}
	if !exist {
		err = os.Mkdir(cm.path(signaturesDir), 0700)
	}

	return
}

Sietse Ringers's avatar
Sietse Ringers committed
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
func (cm *CredentialManager) storeSecretKey(sk *big.Int) error {
	return ioutil.WriteFile(cm.path(skFile), sk.Bytes(), 0600)
}

// 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
func (cm *CredentialManager) saveFile(filepath string, content []byte) (err error) {
	dir := path.Dir(filepath)

	// 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
	err = ioutil.WriteFile(dir+"/"+tempfilename, content, 0600)
	if err != nil {
		return
	}

	// Rename, overwriting old file
	return os.Rename(dir+"/"+tempfilename, filepath)
99
100
}

Sietse Ringers's avatar
Sietse Ringers committed
101
func (cm *CredentialManager) storeSignature(cred *credential, counter int) (err error) {
102
103
104
105
106
107
108
109
110
111
	if cred.CredentialType() == nil {
		return errors.New("cannot add unknown credential type")
	}

	credbytes, err := json.Marshal(cred.Signature)
	if err != nil {
		return err
	}

	// TODO existence check
112
	filename := cm.signatureFilename(cred.CredentialType().Identifier().String(), counter)
113
114
115
116
117
	err = ioutil.WriteFile(filename, credbytes, 0600)
	return
}

func (cm *CredentialManager) storeAttributes() (err error) {
118
	// Unfortunately, the type of cm.attributes (map[CredentialTypeIdentifier][]*AttributeList)
119
120
121
122
123
124
	// cannot be passed directly to json.Marshal(), so we copy it into a temp list.
	temp := make(map[string][]*AttributeList)
	for credid, list := range cm.attributes {
		temp[credid.String()] = list
	}
	attrbytes, err := json.Marshal(temp)
125
	if err != nil {
126
		return err
127
128
129
130
131
132
	}

	// TODO existence check
	err = ioutil.WriteFile(cm.path(attributesFile), attrbytes, 0600)
	return
}
Sietse Ringers's avatar
Sietse Ringers committed
133

134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
func (cm *CredentialManager) storeKeyshareServers() (err error) {
	temp := make(map[string]*keyshareServer)
	for name, kss := range cm.keyshareServers {
		temp[name.String()] = kss
	}
	bts, err := json.Marshal(temp)
	if err != nil {
		return
	}
	err = ioutil.WriteFile(cm.path(kssFile), bts, 0600)
	return
}

func (cm *CredentialManager) storePaillierKeys() (err error) {
	bts, err := json.Marshal(cm.paillierKeyCache)
	if err != nil {
		return
	}
	err = ioutil.WriteFile(cm.path(paillierFile), bts, 0600)
	return
}

156
func (cm *CredentialManager) loadSignature(id CredentialTypeIdentifier, counter int) (signature *gabi.CLSignature, err error) {
Sietse Ringers's avatar
Cleanup    
Sietse Ringers committed
157
158
	sigpath := cm.signatureFilename(id.String(), counter)
	exists, err := PathExists(sigpath)
Sietse Ringers's avatar
Sietse Ringers committed
159
160
161
	if err != nil || !exists {
		return
	}
Sietse Ringers's avatar
Cleanup    
Sietse Ringers committed
162
	bytes, err := ioutil.ReadFile(sigpath)
163
164
165
	if err != nil {
		return
	}
Sietse Ringers's avatar
Sietse Ringers committed
166
167
168
169
170
171
172
173
	signature = new(gabi.CLSignature)
	err = json.Unmarshal(bytes, signature)
	return
}

// loadSecretKey retrieves and returns the secret key from storage, or if no secret key
// was found in storage, it generates, saves, and returns a new secret key.
func (cm *CredentialManager) loadSecretKey() (*big.Int, error) {
174
	exists, err := PathExists(cm.path(skFile))
Sietse Ringers's avatar
Sietse Ringers committed
175
176
177
178
	if err != nil {
		return nil, err
	}
	if exists {
179
180
181
		var bytes []byte
		if bytes, err = ioutil.ReadFile(cm.path(skFile)); err == nil {
			return new(big.Int).SetBytes(bytes), nil
Sietse Ringers's avatar
Sietse Ringers committed
182
		}
183
		return nil, err
Sietse Ringers's avatar
Sietse Ringers committed
184
	}
185
186
187
188
189
190
191
192
193
194

	sk, err := cm.generateSecretKey()
	if err != nil {
		return nil, err
	}
	err = cm.storeSecretKey(sk)
	if err != nil {
		return nil, err
	}
	return sk, nil
Sietse Ringers's avatar
Sietse Ringers committed
195
196
}

197
198
func (cm *CredentialManager) loadAttributes() (list map[CredentialTypeIdentifier][]*AttributeList, err error) {
	list = make(map[CredentialTypeIdentifier][]*AttributeList)
199
	temp := make(map[string][]*AttributeList)
Sietse Ringers's avatar
Sietse Ringers committed
200

201
	exists, err := PathExists(cm.path(attributesFile))
Sietse Ringers's avatar
Sietse Ringers committed
202
203
204
205
206
207
208
209
	if err != nil || !exists {
		return
	}

	bytes, err := ioutil.ReadFile(cm.path(attributesFile))
	if err != nil {
		return nil, err
	}
210
211
212
213
	err = json.Unmarshal(bytes, &temp)
	if err != nil {
		return nil, err
	}
Sietse Ringers's avatar
Sietse Ringers committed
214

215
	for credid, attrs := range temp {
216
		list[NewCredentialTypeIdentifier(credid)] = attrs
217
218
	}
	return list, nil
Sietse Ringers's avatar
Sietse Ringers committed
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

func (cm *CredentialManager) loadKeyshareServers() (ksses map[SchemeManagerIdentifier]*keyshareServer, err error) {
	ksses = make(map[SchemeManagerIdentifier]*keyshareServer)
	temp := make(map[string]*keyshareServer)

	exists, err := PathExists(cm.path(kssFile))
	if err != nil || !exists {
		return
	}
	bytes, err := ioutil.ReadFile(cm.path(kssFile))
	if err != nil {
		return nil, err
	}
	err = json.Unmarshal(bytes, &temp)
	if err != nil {
		return nil, err
	}
	for name, kss := range temp {
		kss.keyGenerator = cm
		ksses[NewSchemeManagerIdentifier(name)] = kss
	}
	return
}

func (cm *CredentialManager) loadPaillierKeys() (key *paillierPrivateKey, err error) {
	exists, err := PathExists(cm.path(paillierFile))
	if err != nil || !exists {
		return
	}
	bytes, err := ioutil.ReadFile(cm.path(paillierFile))
	if err != nil {
		return nil, err
	}
	key = new(paillierPrivateKey)
	err = json.Unmarshal(bytes, key)
	if err != nil {
		return nil, err
	}
	return
}