/
context.go
186 lines (158 loc) · 4.87 KB
/
context.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
package security
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha1"
"fmt"
"hash"
"io"
"io/ioutil"
"os"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/pbkdf2"
)
const (
keyIterations = 100000
passwordEnvVar = "KOPI_PASSWORD"
keyLength = 32 // Bytes for AES-256,
SaltLength = 128 // Bytes
SaltFileName = "salt"
)
type Context struct {
Salt []byte
newHash func() hash.Hash
cipherBlock cipher.Block
}
func NewContext(outputDir string, withCrypto bool) (*Context, error) {
ctx := &Context{
newHash: sha1.New}
if err := ctx.loadSalt(outputDir); err != nil {
return nil, err
}
if withCrypto {
if err := ctx.initCrypto(); err != nil {
return nil, err
}
log.Info("encryption enabled")
} else {
log.Info("encryption disabled")
}
return ctx, nil
}
func (ctx *Context) loadSalt(outputDir string) error {
saltPath := fmt.Sprintf("%s/%s", outputDir, SaltFileName)
ctx.Salt = make([]byte, SaltLength)
if saltFile, err := os.Open(saltPath); err == nil {
// Read existing salt
bytesRead, err := saltFile.Read(ctx.Salt)
if err != nil {
return fmt.Errorf("failed to read salt: %s", err.Error())
} else if bytesRead != SaltLength {
return fmt.Errorf("incomplete salt read: %d of %d bytes read", bytesRead, SaltLength)
}
} else if os.IsNotExist(err) {
// Create salt
if bytesRead, err := rand.Read(ctx.Salt); err != nil || bytesRead != SaltLength {
return fmt.Errorf("failed to generate salt: %s", err.Error())
} else {
if err := ioutil.WriteFile(saltPath, ctx.Salt, 0655); err != nil {
return fmt.Errorf("failed to save salt: %s", err.Error())
}
log.Info("salt created")
}
} else {
return fmt.Errorf("failed to open salt file: %s", err.Error())
}
return nil
}
func (ctx *Context) initCrypto() error {
if passwordString, found := os.LookupEnv(passwordEnvVar); !found {
return fmt.Errorf("environment variable undefined: %s", passwordEnvVar)
} else {
password := []byte(passwordString)
key := pbkdf2.Key(password, ctx.Salt, keyIterations, keyLength, sha1.New)
block, err := aes.NewCipher(key)
if err != nil {
return fmt.Errorf("failed to init cipher: %s", err.Error())
}
ctx.cipherBlock = block
return nil
}
}
func (ctx *Context) NewHasher() (hash.Hash, error) {
hasher := ctx.newHash()
if bytesWritten, err := hasher.Write(ctx.Salt); err != nil {
return nil, fmt.Errorf("failed to write salt: %s", err.Error())
} else if bytesWritten != SaltLength {
return nil, fmt.Errorf("incomplete salt write: %d of %d bytes written", bytesWritten, SaltLength)
}
return hasher, nil
}
func (ctx *Context) Encode(input []byte) ([]byte, error) {
if ctx.cipherBlock == nil {
return input, nil
}
cipher, err := cipher.NewGCM(ctx.cipherBlock)
if err != nil {
return nil, fmt.Errorf("failed to init cipher: %s", err.Error())
}
nonceSize := cipher.NonceSize()
blockSize := ctx.cipherBlock.BlockSize()
inputSize := len(input)
paddingSize := 0
blockSizeModulo := inputSize % blockSize
if blockSizeModulo != 0 {
paddingSize += (blockSize - blockSizeModulo)
}
log.WithFields(log.Fields{
"block_size_modulo": blockSizeModulo,
"pading": paddingSize,
"padded_size": inputSize + paddingSize}).Debug("clear text padding")
paddedInput := make([]byte, inputSize+paddingSize)
copy(paddedInput, input)
if bytesRead, err := rand.Read(paddedInput[inputSize:]); err != nil {
return nil, fmt.Errorf("failed to pad clear text: %s", err.Error())
} else if bytesRead != paddingSize {
return nil, fmt.Errorf("incomplete clear text padding: %d out of %d bytes read", bytesRead, paddingSize)
}
nonce := make([]byte, nonceSize)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, fmt.Errorf("failed to read nonce: %s", err.Error())
}
log.WithFields(log.Fields{
"block_size": blockSize,
"clear_text": inputSize,
"padded_clear_text": len(paddedInput)}).Debug("encrypting")
cipherText := cipher.Seal(nil, nonce, paddedInput, nil)
output := append(nonce, cipherText...)
return output, nil
}
func (ctx *Context) Decode(input []byte) (output []byte, err error) {
if ctx.cipherBlock == nil {
return input, nil
}
defer func() {
if r := recover(); r != nil {
output = nil
err = fmt.Errorf("decryption failed: %s", r)
}
}()
cipher, err := cipher.NewGCM(ctx.cipherBlock)
if err != nil {
return nil, fmt.Errorf("failed to init cipher: %s", err.Error())
}
nonceSize := cipher.NonceSize()
blockSize := ctx.cipherBlock.BlockSize()
nonce := input[:nonceSize]
cipherTextSize := len(input) - nonceSize
if cipherTextSize%blockSize != 0 {
return nil, fmt.Errorf("cipher text size is not a multiple of block size")
}
log.WithField("size", cipherTextSize).Debug("decrypting block data")
output, err = cipher.Open(nil, nonce, input[nonceSize:], nil)
if err != nil {
return nil, fmt.Errorf("failed to decrypt: %s", err.Error())
}
return output, nil
}