-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
418 lines (371 loc) · 10.4 KB
/
main.go
File metadata and controls
418 lines (371 loc) · 10.4 KB
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
package main
import (
//"strings"
"io/ioutil"
"encoding/json"
"net/http"
"log"
"os"
"flag"
"sync"
"bytes"
"errors"
"crypto/sha256"
"crypto/rsa"
"crypto/aes"
"crypto/cipher"
"crypto/x509"
"crypto/rand"
"encoding/pem"
"encoding/base64"
"path/filepath"
"github.com/howeyc/fsnotify"
"github.com/streadway/amqp"
)
type config struct {
HTTP string
KeyPath string
RabbitURI string
RabbitUser string
RabbitPassword string
RabbitQueue string
RoutingKey string
Exchange string
}
// Tasks are encrypted with a symmetric key (EncryptedKey), which is
// encrypted with the asymmetric key in KeyFingerprint
type EncryptedTask struct {
KeyFingerprint string
EncryptedKey []byte
Encrypted []byte
IV []byte
}
type Task struct {
PrimaryURI string `json:"primaryURI"`
SecondaryURI string `json:"secondaryURI"`
Filename string `json:"filename"`
Tasks map[string][]string `json:"tasks"`
Tags []string `json:"tags"`
Attempts int `json:"attempts"`
}
var conf *config
var keys map[string]rsa.PrivateKey
var keysMutex = &sync.Mutex{}
var rabbitChannel *amqp.Channel
var rabbitQueue amqp.Queue
func aesEncrypt(plaintext []byte, key []byte, iv []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return []byte(""), err
}
mode := cipher.NewCBCEncrypter(block, iv)
padLength := mode.BlockSize()-len(plaintext)%mode.BlockSize()
ciphertext := make([]byte,len(plaintext))
copy(ciphertext, plaintext)
ciphertext = append(ciphertext, bytes.Repeat([]byte{byte(padLength)}, padLength)...)
mode.CryptBlocks(ciphertext,ciphertext)
return ciphertext, nil
}
func aesDecrypt(ciphertext []byte, key []byte, iv []byte) ( []byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return []byte(""), err
}
mode := cipher.NewCBCDecrypter(block, iv)
plaintext := make([]byte,len(ciphertext))
mode.CryptBlocks(plaintext,ciphertext)
if len(plaintext) == 0 {
return []byte(""), errors.New("Empty plaintext")
}
padLength := int(plaintext[len(plaintext)-1])
if padLength > len(plaintext) {
return []byte(""), errors.New("Invalid padding size")
}
plaintext = plaintext[:len(plaintext)-padLength]
return plaintext, nil
}
func rsaEncrypt(plaintext []byte, key *rsa.PrivateKey) ([]byte, error) {
label := []byte("")
ciphertext, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, &key.PublicKey, plaintext, label)
return ciphertext, err
}
func rsaDecrypt(ciphertext []byte, key *rsa.PrivateKey) ([]byte, error) {
label := []byte("")
plaintext, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, key, ciphertext, label)
return plaintext, err
}
func decryptTask(enc *EncryptedTask) (string, error) {
// Fetch private key corresponding to enc.keyFingerprint
keysMutex.Lock()
asymKey := keys[enc.KeyFingerprint]
keysMutex.Unlock()
// Decrypt symmetric key using the asymmetric key
symKey, err := rsaDecrypt(enc.EncryptedKey, &asymKey)
if err != nil{
return "", err
}
log.Printf("Symmetric Key: %s\n", symKey)
// Decrypt using the symmetric key
decrypted, err := aesDecrypt(enc.Encrypted, symKey, enc.IV)
return string(decrypted), err
}
func stringPrintable(s string) (bool) {
for i := 0; i < len(s); i++{
c := int(s[i])
if c < 0x9 || (c > 0x0d && c < 0x20) || (c >0x7e){
return false
}
}
return true
}
func validateTask(task string) ([]Task, error) {
var tasks []Task
err := json.Unmarshal([]byte(task), &tasks)
if err != nil {
return nil, err
}
// Check for required fields; Check whether strings are in printable ascii-range
for i := 0; i < len(tasks); i++ {
t := tasks[i]
log.Printf("Validating %+v\n", t)
if t.PrimaryURI == "" || !stringPrintable(t.PrimaryURI) {
return nil, errors.New("Invalid Task (PrimaryURI invalid)")
}
if !stringPrintable(t.SecondaryURI) {
return nil, errors.New("Invalid Task (SecondaryURI invalid)")
}
if t.Filename == "" || !stringPrintable(t.Filename) {
return nil, errors.New("Invalid Task (Filename invalid)")
}
if len(t.Tasks) == 0 {
return nil, errors.New("Invalid Task")
}
for k := range t.Tasks {
if k == "" || !stringPrintable(k) {
return nil, errors.New("Invalid Task")
}
}
for j := 0; j < len(t.Tags); j++ {
if !stringPrintable(t.Tags[j]) {
return nil, errors.New("Invalid Task (Tag invalid)")
}
}
if t.Attempts < 0 {
return nil, errors.New("Invalid Task (Negative number of attempts)")
}
}
return tasks, err
}
func checkACL(task Task) (error){
//TODO: How shall ACL-Check be executed?
return nil
}
func decodeTask(r *http.Request) (*EncryptedTask, error) {
ek, err := base64.StdEncoding.DecodeString(r.FormValue("EncryptedKey"))
if err != nil {
return nil, err
}
iv, err := base64.StdEncoding.DecodeString(r.FormValue("IV"))
if err != nil {
return nil, err
}
en, err := base64.StdEncoding.DecodeString(r.FormValue("Encrypted"))
if err != nil {
return nil, err
}
task := EncryptedTask{
KeyFingerprint : r.FormValue("KeyFingerprint"),
EncryptedKey : ek,
Encrypted : en,
IV : iv }
log.Printf("New task request:\n%+v\n", task);
return &task, err
}
func httpRequestIncoming(w http.ResponseWriter, r *http.Request) {
task, err := decodeTask(r)
if err != nil {
log.Println("Error while decoding: ", err)
return
}
decTask, err := decryptTask(task)
if err != nil {
log.Println("Error while decrypting: ", err)
return
}
log.Println("Decrypted task:", decTask)
tasks, err := validateTask(decTask)
if err != nil {
log.Println("Error while validating: ", err)
return
}
for i := 0; i < len(tasks); i++ {
err = checkACL(tasks[i])
if err != nil {
log.Println("Error while checking ACL: ", err)
continue
}
// Push to transport
log.Printf("%+v\n", tasks[i])
msgBody, err := json.Marshal(tasks[i])
if err != nil {
log.Println("Error while Marshalling: ", err)
}
log.Printf("marshalled: %s\n", msgBody)
err = rabbitChannel.Publish(
conf.Exchange, // exchange
conf.RoutingKey, // key
false, // mandatory
false, // immediate
amqp.Publishing {DeliveryMode: amqp.Persistent, ContentType: "text/plain", Body: []byte(msgBody),}) //msg
if err != nil {
log.Println("Error while pushing to transport: ", err)
continue
}
}
}
func failOnError(err error, msg string) {
if err != nil {
log.Fatalf("%s: %s", msg, err)
}
}
func loadKey(path string)(rsa.PrivateKey, string){
log.Println(path)
f, err := ioutil.ReadFile(path)
failOnError(err, "Error reading key (Read)")
priv, rem := pem.Decode(f)
if len(rem) != 0 {
log.Fatal("Error reading key (Decode) ", rem)
}
key, err := x509.ParsePKCS1PrivateKey(priv.Bytes)
failOnError(err, "Error reading key (Parse)")
// strip the path from its directory and ".priv"-extension
path = filepath.Base(path)
path = path[:len(path)-5]
return rsa.PrivateKey(*key), path
}
func keyWalkFn(path string, fi os.FileInfo, err error) (error) {
if fi.IsDir(){
return nil
}
if !(filepath.Ext(path) == ".priv"){
return nil
}
log.Println(path)
key, name := loadKey(path)
keysMutex.Lock()
keys[name] = key
keysMutex.Unlock()
return nil
}
func readKeys() {
err := filepath.Walk(conf.KeyPath, keyWalkFn)
failOnError(err, "Error loading keys ")
// Setup directory watcher
watcher, err := fsnotify.NewWatcher()
failOnError(err, "Error setting up directory-watcher")
// Process events
go func() {
for {
select {
case ev := <-watcher.Event:
if filepath.Ext(ev.Name) == ".priv" {
log.Println("event:", ev)
if ev.IsCreate(){
log.Println("New private key", ev.Name)
key, name := loadKey(ev.Name)
keysMutex.Lock()
keys[name] = key
keysMutex.Unlock()
} else if ev.IsDelete() || ev.IsRename(){
// For renamed keys, there is a CREATE-event afterwards so it is just removed here
log.Println("Removed private key", ev.Name)
name := filepath.Base(ev.Name)
name = name[:len(name)-5]
keysMutex.Lock()
delete(keys, name)
keysMutex.Unlock()
} else if ev.IsModify(){
log.Println("Modified private key", ev.Name)
name := filepath.Base(ev.Name)
name = name[:len(name)-5]
keysMutex.Lock()
delete(keys, name)
keysMutex.Unlock()
key, name := loadKey(ev.Name)
keysMutex.Lock()
keys[name] = key
keysMutex.Unlock()
}
//log.Println(keys)
}
case err := <-watcher.Error:
log.Println("error:", err)
}
}
}()
err = watcher.Watch(conf.KeyPath)
failOnError(err, "Error setting up directory-watcher")
}
func connectRabbit() {
conn, err := amqp.Dial("amqp://"+conf.RabbitUser+":"+conf.RabbitPassword+"@"+conf.RabbitURI)
failOnError(err, "Failed to connect to RabbitMQ")
//defer conn.Close()
rabbitChannel, err = conn.Channel()
failOnError(err, "Failed to open a channel")
//defer rabbitChannel.Close()
rabbitQueue, err = rabbitChannel.QueueDeclare(
conf.RabbitQueue, //name
true, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
failOnError(err, "Failed to declare a queue")
err = rabbitChannel.ExchangeDeclare(
conf.Exchange, // name
"topic", // type
true, // durable
false, // auto-deleted
false, // internal
false, // no-wait
nil, // arguments
)
failOnError(err, "Failed to declare an exchange")
err = rabbitChannel.QueueBind(
rabbitQueue.Name, // queue name
conf.RoutingKey, // routing key
conf.Exchange, // exchange
false, // nowait
nil, // arguments
)
failOnError(err, "Failed to bind queue")
log.Printf("Connected to Rabbit on channel %s\n", rabbitQueue.Name)
}
func initHTTP() {
http.HandleFunc("/task/", httpRequestIncoming)
log.Printf("Listening on %s\n", conf.HTTP)
log.Fatal(http.ListenAndServe(conf.HTTP, nil))
}
func main() {
// Parse the configuration
var confPath string
flag.StringVar(&confPath, "config", "", "Path to the config file")
flag.Parse()
if confPath == "" {
confPath, _ = filepath.Abs(filepath.Dir(os.Args[0]))
confPath += "/config.json"
}
conf = &config{}
cfile, _ := os.Open(confPath)
err := json.NewDecoder(cfile).Decode(&conf)
failOnError(err, "Couldn't read config file")
// Parse the private keys
keys = make(map[string]rsa.PrivateKey)
readKeys()
//log.Println(keys)
// Connect to rabbitmq
connectRabbit()
// Setup the HTTP-listener
initHTTP()
}