1/*
2Copyright 2017 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17// Package secretbox transforms values for storage at rest using XSalsa20 and Poly1305.
18package secretbox
19
20import (
21	"crypto/rand"
22	"fmt"
23
24	"golang.org/x/crypto/nacl/secretbox"
25
26	"k8s.io/apiserver/pkg/storage/value"
27)
28
29// secretbox implements at rest encryption of the provided values given a 32 byte secret key.
30// Uses a standard 24 byte nonce (placed at the beginning of the cipher text) generated
31// from crypto/rand. Does not perform authentication of the data at rest.
32type secretboxTransformer struct {
33	key [32]byte
34}
35
36const nonceSize = 24
37
38// NewSecretboxTransformer takes the given key and performs encryption and decryption on the given
39// data.
40func NewSecretboxTransformer(key [32]byte) value.Transformer {
41	return &secretboxTransformer{key: key}
42}
43
44func (t *secretboxTransformer) TransformFromStorage(data []byte, context value.Context) ([]byte, bool, error) {
45	if len(data) < (secretbox.Overhead + nonceSize) {
46		return nil, false, fmt.Errorf("the stored data was shorter than the required size")
47	}
48	var nonce [nonceSize]byte
49	copy(nonce[:], data[:nonceSize])
50	data = data[nonceSize:]
51	out := make([]byte, 0, len(data)-secretbox.Overhead)
52	result, ok := secretbox.Open(out, data, &nonce, &t.key)
53	if !ok {
54		return nil, false, fmt.Errorf("output array was not large enough for encryption")
55	}
56	return result, false, nil
57}
58
59func (t *secretboxTransformer) TransformToStorage(data []byte, context value.Context) ([]byte, error) {
60	var nonce [nonceSize]byte
61	n, err := rand.Read(nonce[:])
62	if err != nil {
63		return nil, err
64	}
65	if n != nonceSize {
66		return nil, fmt.Errorf("unable to read sufficient random bytes")
67	}
68	return secretbox.Seal(nonce[:], data, &nonce, &t.key), nil
69}
70