-
Notifications
You must be signed in to change notification settings - Fork 2
/
encryption.go
420 lines (336 loc) · 9.79 KB
/
encryption.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
// encrpytion package holds all pgp related tasks
package encryption
import (
"bytes"
"context"
"crypto"
"encoding/base64"
"encoding/json"
"errors"
"github.com/deuscapturus/tism/config"
"github.com/deuscapturus/tism/request"
"golang.org/x/crypto/openpgp"
"golang.org/x/crypto/openpgp/armor"
"golang.org/x/crypto/openpgp/packet"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
)
type MyEntityList struct {
openpgp.EntityList
}
type PublicKey struct {
Id string `json:"id"`
PubKey string `json:"pubkey"`
}
var KeyRing = MyEntityList{}
func init() {
KeyRing.GetKeyRing()
}
func SetMyKeyRing(w http.ResponseWriter, rc http.Request) (error, http.Request) {
var MyKeyRing openpgp.EntityList
AuthorizedKeys := rc.Context().Value("claims").([]string)
AuthorizedAllKeys := rc.Context().Value("claimsAll").(bool)
if AuthorizedAllKeys {
MyKeyRing = KeyRing.EntityList
} else {
// Assemble a new entity list based on the outcome of KeysById
keysUint64 := stringsToUint64(AuthorizedKeys)
for _, keyid := range keysUint64 {
for _, thisk := range KeyRing.KeysById(keyid) {
MyKeyRing = append(MyKeyRing, thisk.Entity)
}
}
}
context := context.WithValue(rc.Context(), "MyKeyRing", MyKeyRing)
return nil, *rc.WithContext(context)
}
// Decrypt decrypt the given string.
func Decrypt(w http.ResponseWriter, rc http.Request) (error, http.Request) {
var err error
req := rc.Context().Value("request").(request.Request)
MyKeyRing := rc.Context().Value("MyKeyRing").(openpgp.EntityList)
var Encoding string
//Set default encoding to base64
if req.Encoding == "" || req.Encoding != "armor" {
Encoding = "base64"
} else {
Encoding = req.Encoding
}
var dec io.Reader
if Encoding == "armor" {
encReader := bytes.NewBufferString(req.EncSecret)
encBlock, err := armor.Decode(encReader)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return err, rc
}
dec = encBlock.Body
} else if Encoding == "base64" {
decBytes, err := base64.StdEncoding.DecodeString(req.EncSecret)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return err, rc
}
dec = bytes.NewBuffer(decBytes)
}
md, err := openpgp.ReadMessage(dec, MyKeyRing, nil, nil)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return err, rc
}
message, err := ioutil.ReadAll(md.UnverifiedBody)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return err, rc
}
w.Write(message)
return nil, rc
}
// Encrypt encrypt the given string.
func Encrypt(w http.ResponseWriter, rc http.Request) (error, http.Request) {
req := rc.Context().Value("request").(request.Request)
MyKeyRing := rc.Context().Value("MyKeyRing").(openpgp.EntityList)
EntityId := stringToUint64(req.Id)
ThisKey := MyKeyRing.KeysById(EntityId)
if len(ThisKey) == 0 {
return errors.New("Key Id not found in requestors keyring"), rc
}
var Encoding string
var EncWriter io.WriteCloser
var ArmorWriter io.WriteCloser
var ThisKeyEntity []*openpgp.Entity
var err error
ThisKeyEntity = append(ThisKeyEntity, ThisKey[0].Entity)
buf := bytes.NewBuffer(nil)
//Set default encoding to base64
if req.Encoding == "" || req.Encoding != "armor" {
Encoding = "base64"
} else {
Encoding = req.Encoding
}
if Encoding == "armor" {
ArmorWriter, err = armor.Encode(buf, "PGP MESSAGE", nil)
if err != nil {
return err, rc
}
EncWriter, err = openpgp.Encrypt(ArmorWriter, ThisKeyEntity, nil, nil, nil)
if err != nil {
return err, rc
}
} else if Encoding == "base64" {
EncWriter, err = openpgp.Encrypt(buf, ThisKeyEntity, nil, nil, nil)
if err != nil {
return err, rc
}
}
_, err = EncWriter.Write([]byte(req.DecSecret))
if err != nil {
return err, rc
}
EncWriter.Close()
w.Header().Set("Content-Type", "text/text")
if Encoding == "armor" {
ArmorWriter.Close()
}
encSecret, err := ioutil.ReadAll(buf)
if err != nil {
return err, rc
}
if Encoding == "armor" {
w.Write([]byte(encSecret))
} else if Encoding == "base64" {
base64encSecret := base64.StdEncoding.EncodeToString(encSecret)
w.Write([]byte(base64encSecret))
}
return nil, rc
}
// ListKeys return json list of keys with metadata including id.
func ListKeys(w http.ResponseWriter, rc http.Request) (error, http.Request) {
list := make([]map[string]string, 0)
JsonEncode := json.NewEncoder(w)
MyKeyRing := rc.Context().Value("MyKeyRing").(openpgp.EntityList)
AuthorizedKeys := rc.Context().Value("claims")
switch AuthorizedKeys.(type) {
case string:
if AuthorizedKeys.(string) == "ALL" {
all := make(map[string]string)
all["Id"] = "ALL"
list = append(list, all)
}
}
for _, entity := range MyKeyRing {
m := make(map[string]string)
m["CreationTime"] = entity.PrimaryKey.CreationTime.String()
m["Id"] = strconv.FormatUint(entity.PrimaryKey.KeyId, 16)
for Name, _ := range entity.Identities {
m["Name"] = Name
}
list = append(list, m)
}
w.Header().Set("Content-Type", "text/json")
JsonEncode.Encode(list)
return nil, rc
}
func GetKey(w http.ResponseWriter, rc http.Request) (error, http.Request) {
MyKeyRing := rc.Context().Value("MyKeyRing").(openpgp.EntityList)
var req request.Request
req = rc.Context().Value("request").(request.Request)
EntityId, err := strconv.ParseUint(req.Id, 16, 64)
if err != nil {
return err, rc
}
ThisKey := MyKeyRing.KeysById(EntityId)
if ThisKey == nil {
w.WriteHeader(http.StatusBadRequest)
return errors.New("Key not found"), rc
}
JsonEncode := json.NewEncoder(w)
w.Header().Set("Content-Type", "text/json")
// TODO: KeysById returns a slice, though there should only ever be one id per key. For now assume only one key is ever returned. Re-consider in the future.
p := &PublicKey{req.Id, pubEntToAsciiArmor(ThisKey[0].Entity)}
JsonEncode.Encode(*p)
return nil, rc
}
// DeleteKey deletes a key by id from the system
func DeleteKey(w http.ResponseWriter, rc http.Request) (error, http.Request) {
MyKeyRing := rc.Context().Value("MyKeyRing").(openpgp.EntityList)
var req request.Request
req = rc.Context().Value("request").(request.Request)
EntityId, err := strconv.ParseUint(req.Id, 16, 64)
if err != nil {
return err, rc
}
// Make sure the key requested for deletion is in the users keyring.
ThisKey := MyKeyRing.KeysById(EntityId)
if ThisKey == nil {
w.WriteHeader(http.StatusBadRequest)
return errors.New("Key not found in your keyring"), rc
}
for key, entity := range KeyRing.EntityList {
if entity.PrimaryKey.KeyId == EntityId {
var NewKeyRing = MyEntityList{}
NewKeyRing.EntityList = append(KeyRing.EntityList[:key], KeyRing.EntityList[key+1:]...)
f, err := os.OpenFile(config.Config.KeyRingFilePath, os.O_APPEND|os.O_WRONLY|os.O_TRUNC, 0600)
if err != nil {
log.Println(err)
return err, rc
}
defer f.Close()
for _, NewEntity := range NewKeyRing.EntityList {
NewEntity.SerializePrivate(f, nil)
if err != nil {
log.Println(err)
return err, rc
}
}
log.Println("Deleted Key", req.Id)
// Reload the Keyring after the key is deleted.
defer KeyRing.GetKeyRing()
return err, rc
}
}
return errors.New("Key found in user keyring, but missing in system keyring. This should never happen"), rc
}
// NewKey will create a new private/public gpg key pair
// and return the private key id and public key.
func NewKey(w http.ResponseWriter, rc http.Request) (error, http.Request) {
var req request.Request
req = rc.Context().Value("request").(request.Request)
pgpConfig := &packet.Config{
DefaultHash: crypto.SHA256,
}
NewEntity, err := openpgp.NewEntity(req.Name, req.Comment, req.Email, pgpConfig)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Header().Set("Content-Type", "text/plain")
log.Println(err)
return err, rc
}
f, err := os.OpenFile(config.Config.KeyRingFilePath, os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
log.Println(err)
return err, rc
}
defer f.Close()
NewEntity.SerializePrivate(f, nil)
if err != nil {
log.Println(err)
return err, rc
}
// Reload the Keyring after the new key is saved.
defer KeyRing.GetKeyRing()
// Return the id and pub key in json
JsonEncode := json.NewEncoder(w)
NewEntityId := strconv.FormatUint(NewEntity.PrimaryKey.KeyId, 16)
NewEntityPublicKey := pubEntToAsciiArmor(NewEntity)
w.Header().Set("Content-Type", "text/json")
p := &PublicKey{NewEntityId, NewEntityPublicKey}
JsonEncode.Encode(*p)
return nil, rc
}
// stringsToUint64 convert a slice of strings to uint64.
func stringsToUint64(s []string) []uint64 {
var uint64List []uint64
for _, j := range s {
j, err := strconv.ParseUint(j, 16, 64)
if err != nil {
log.Println(err)
}
uint64List = append(uint64List, j)
}
return uint64List
}
// stringsToUint64 convert string to uint64.
func stringToUint64(s string) uint64 {
suint64, err := strconv.ParseUint(s, 16, 64)
if err != nil {
log.Println(err)
}
return suint64
}
// GetKeyRing return pgp keyring from a file location
func (KeyRing *MyEntityList) GetKeyRing() {
_, err := os.Stat(config.Config.KeyRingFilePath)
var KeyringFileBuffer *os.File
if os.IsNotExist(err) {
KeyringFileBuffer, err = os.Create(config.Config.KeyRingFilePath)
if err != nil {
log.Println(err)
return
}
} else {
KeyringFileBuffer, err = os.Open(config.Config.KeyRingFilePath)
if err != nil {
log.Println(err)
return
}
}
EntityList, err := openpgp.ReadKeyRing(KeyringFileBuffer)
if err != nil {
log.Println(err)
return
}
*KeyRing = MyEntityList{EntityList}
return
}
// pubEntToAsciiArmor create Ascii Armor from openpgp.Entity
func pubEntToAsciiArmor(pubEnt *openpgp.Entity) (asciiEntity string) {
gotWriter := bytes.NewBuffer(nil)
wr, err := armor.Encode(gotWriter, openpgp.PublicKeyType, nil)
if err != nil {
log.Println(err)
return
}
if pubEnt.Serialize(wr) != nil {
log.Println(err)
}
if wr.Close() != nil {
log.Println(err)
}
asciiEntity = gotWriter.String()
return
}