ciphers.go 8.27 KB
Newer Older
1
// Copyright (C) 2017. See AUTHORS.
JT Olds's avatar
JT Olds committed
2 3 4 5 6 7 8 9 10 11 12 13 14
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

15 16
package openssl

Andrew Harding's avatar
Andrew Harding committed
17
// #include "shim.h"
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
import "C"

import (
	"errors"
	"fmt"
	"runtime"
	"unsafe"
)

const (
	GCM_TAG_MAXLEN = 16
)

type CipherCtx interface {
	Cipher() *Cipher
	BlockSize() int
	KeySize() int
	IVSize() int
}

Jeff Wendling's avatar
Jeff Wendling committed
38 39
type Cipher struct {
	ptr *C.EVP_CIPHER
40 41
}

42
func (c *Cipher) Nid() NID {
Andrew Harding's avatar
Andrew Harding committed
43
	return NID(C.X_EVP_CIPHER_nid(c.ptr))
44 45
}

Jeff Wendling's avatar
Jeff Wendling committed
46 47
func (c *Cipher) ShortName() (string, error) {
	return Nid2ShortName(c.Nid())
48 49
}

Jeff Wendling's avatar
Jeff Wendling committed
50
func (c *Cipher) BlockSize() int {
Andrew Harding's avatar
Andrew Harding committed
51
	return int(C.X_EVP_CIPHER_block_size(c.ptr))
Jeff Wendling's avatar
Jeff Wendling committed
52
}
53

Jeff Wendling's avatar
Jeff Wendling committed
54
func (c *Cipher) KeySize() int {
Andrew Harding's avatar
Andrew Harding committed
55
	return int(C.X_EVP_CIPHER_key_length(c.ptr))
Jeff Wendling's avatar
Jeff Wendling committed
56
}
57

Jeff Wendling's avatar
Jeff Wendling committed
58
func (c *Cipher) IVSize() int {
Andrew Harding's avatar
Andrew Harding committed
59
	return int(C.X_EVP_CIPHER_iv_length(c.ptr))
60 61
}

62
func Nid2ShortName(nid NID) (string, error) {
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
	sn := C.OBJ_nid2sn(C.int(nid))
	if sn == nil {
		return "", fmt.Errorf("NID %d not found", nid)
	}
	return C.GoString(sn), nil
}

func GetCipherByName(name string) (*Cipher, error) {
	cname := C.CString(name)
	defer C.free(unsafe.Pointer(cname))
	p := C.EVP_get_cipherbyname(cname)
	if p == nil {
		return nil, fmt.Errorf("Cipher %v not found", name)
	}
	// we can consider ciphers to use static mem; don't need to free
	return &Cipher{ptr: p}, nil
}

81
func GetCipherByNid(nid NID) (*Cipher, error) {
82 83 84 85 86 87 88
	sn, err := Nid2ShortName(nid)
	if err != nil {
		return nil, err
	}
	return GetCipherByName(sn)
}

Jeff Wendling's avatar
Jeff Wendling committed
89 90
type cipherCtx struct {
	ctx *C.EVP_CIPHER_CTX
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
}

func newCipherCtx() (*cipherCtx, error) {
	cctx := C.EVP_CIPHER_CTX_new()
	if cctx == nil {
		return nil, errors.New("failed to allocate cipher context")
	}
	ctx := &cipherCtx{cctx}
	runtime.SetFinalizer(ctx, func(ctx *cipherCtx) {
		C.EVP_CIPHER_CTX_free(ctx.ctx)
	})
	return ctx, nil
}

func (ctx *cipherCtx) applyKeyAndIV(key, iv []byte) error {
	var kptr, iptr *C.uchar
	if key != nil {
		if len(key) != ctx.KeySize() {
			return fmt.Errorf("bad key size (%d bytes instead of %d)",
				len(key), ctx.KeySize())
		}
		kptr = (*C.uchar)(&key[0])
	}
	if iv != nil {
		if len(iv) != ctx.IVSize() {
			return fmt.Errorf("bad IV size (%d bytes instead of %d)",
				len(iv), ctx.IVSize())
		}
		iptr = (*C.uchar)(&iv[0])
	}
	if kptr != nil || iptr != nil {
122
		var res C.int
Andrew Harding's avatar
Andrew Harding committed
123
		if C.X_EVP_CIPHER_CTX_encrypting(ctx.ctx) != 0 {
124 125 126 127 128
			res = C.EVP_EncryptInit_ex(ctx.ctx, nil, nil, kptr, iptr)
		} else {
			res = C.EVP_DecryptInit_ex(ctx.ctx, nil, nil, kptr, iptr)
		}
		if 1 != res {
129 130 131 132 133 134 135
			return errors.New("failed to apply key/IV")
		}
	}
	return nil
}

func (ctx *cipherCtx) Cipher() *Cipher {
Andrew Harding's avatar
Andrew Harding committed
136
	return &Cipher{ptr: C.X_EVP_CIPHER_CTX_cipher(ctx.ctx)}
137 138 139
}

func (ctx *cipherCtx) BlockSize() int {
Andrew Harding's avatar
Andrew Harding committed
140
	return int(C.X_EVP_CIPHER_CTX_block_size(ctx.ctx))
141 142 143
}

func (ctx *cipherCtx) KeySize() int {
Andrew Harding's avatar
Andrew Harding committed
144
	return int(C.X_EVP_CIPHER_CTX_key_length(ctx.ctx))
145 146 147
}

func (ctx *cipherCtx) IVSize() int {
Andrew Harding's avatar
Andrew Harding committed
148
	return int(C.X_EVP_CIPHER_CTX_iv_length(ctx.ctx))
149 150
}

151 152 153
func (ctx *cipherCtx) SetPadding(pad bool) {
	if pad {
		C.X_EVP_CIPHER_CTX_set_padding(ctx.ctx, 1)
154 155
	} else {
		C.X_EVP_CIPHER_CTX_set_padding(ctx.ctx, 0)
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
func (ctx *cipherCtx) setCtrl(code, arg int) error {
	res := C.EVP_CIPHER_CTX_ctrl(ctx.ctx, C.int(code), C.int(arg), nil)
	if res != 1 {
		return fmt.Errorf("failed to set code %d to %d [result %d]",
			code, arg, res)
	}
	return nil
}

func (ctx *cipherCtx) setCtrlBytes(code, arg int, value []byte) error {
	res := C.EVP_CIPHER_CTX_ctrl(ctx.ctx, C.int(code), C.int(arg),
		unsafe.Pointer(&value[0]))
	if res != 1 {
		return fmt.Errorf("failed to set code %d with arg %d to %x [result %d]",
			code, arg, value, res)
	}
	return nil
}

func (ctx *cipherCtx) getCtrlInt(code, arg int) (int, error) {
	var returnVal C.int
	res := C.EVP_CIPHER_CTX_ctrl(ctx.ctx, C.int(code), C.int(arg),
		unsafe.Pointer(&returnVal))
	if res != 1 {
		return 0, fmt.Errorf("failed to get code %d with arg %d [result %d]",
			code, arg, res)
	}
	return int(returnVal), nil
}

func (ctx *cipherCtx) getCtrlBytes(code, arg, expectsize int) ([]byte, error) {
	returnVal := make([]byte, expectsize)
	res := C.EVP_CIPHER_CTX_ctrl(ctx.ctx, C.int(code), C.int(arg),
		unsafe.Pointer(&returnVal[0]))
	if res != 1 {
		return nil, fmt.Errorf("failed to get code %d with arg %d [result %d]",
			code, arg, res)
	}
	return returnVal, nil
}

Jeff Wendling's avatar
Jeff Wendling committed
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
type EncryptionCipherCtx interface {
	CipherCtx

	// pass in plaintext, get back ciphertext. can be called
	// multiple times as needed
	EncryptUpdate(input []byte) ([]byte, error)

	// call after all plaintext has been passed in; may return
	// additional ciphertext if needed to finish off a block
	// or extra padding information
	EncryptFinal() ([]byte, error)
}

type DecryptionCipherCtx interface {
	CipherCtx

	// pass in ciphertext, get back plaintext. can be called
	// multiple times as needed
	DecryptUpdate(input []byte) ([]byte, error)

	// call after all ciphertext has been passed in; may return
	// additional plaintext if needed to finish off a block
	DecryptFinal() ([]byte, error)
}

type encryptionCipherCtx struct {
	*cipherCtx
}

type decryptionCipherCtx struct {
	*cipherCtx
}

func newEncryptionCipherCtx(c *Cipher, e *Engine, key, iv []byte) (
	*encryptionCipherCtx, error) {
	if c == nil {
		return nil, errors.New("null cipher not allowed")
	}
	ctx, err := newCipherCtx()
	if err != nil {
		return nil, err
	}
	var eptr *C.ENGINE
	if e != nil {
		eptr = e.e
	}
	if 1 != C.EVP_EncryptInit_ex(ctx.ctx, c.ptr, eptr, nil, nil) {
		return nil, errors.New("failed to initialize cipher context")
	}
	err = ctx.applyKeyAndIV(key, iv)
	if err != nil {
		return nil, err
	}
	return &encryptionCipherCtx{cipherCtx: ctx}, nil
}

func newDecryptionCipherCtx(c *Cipher, e *Engine, key, iv []byte) (
	*decryptionCipherCtx, error) {
	if c == nil {
		return nil, errors.New("null cipher not allowed")
	}
	ctx, err := newCipherCtx()
	if err != nil {
		return nil, err
	}
	var eptr *C.ENGINE
	if e != nil {
		eptr = e.e
	}
	if 1 != C.EVP_DecryptInit_ex(ctx.ctx, c.ptr, eptr, nil, nil) {
		return nil, errors.New("failed to initialize cipher context")
	}
	err = ctx.applyKeyAndIV(key, iv)
	if err != nil {
		return nil, err
	}
	return &decryptionCipherCtx{cipherCtx: ctx}, nil
}

func NewEncryptionCipherCtx(c *Cipher, e *Engine, key, iv []byte) (
	EncryptionCipherCtx, error) {
	return newEncryptionCipherCtx(c, e, key, iv)
}

func NewDecryptionCipherCtx(c *Cipher, e *Engine, key, iv []byte) (
	DecryptionCipherCtx, error) {
	return newDecryptionCipherCtx(c, e, key, iv)
}

289
func (ctx *encryptionCipherCtx) EncryptUpdate(input []byte) ([]byte, error) {
290 291 292
	if len(input) == 0 {
		return nil, nil
	}
293 294 295 296 297 298 299 300 301 302 303
	outbuf := make([]byte, len(input)+ctx.BlockSize())
	outlen := C.int(len(outbuf))
	res := C.EVP_EncryptUpdate(ctx.ctx, (*C.uchar)(&outbuf[0]), &outlen,
		(*C.uchar)(&input[0]), C.int(len(input)))
	if res != 1 {
		return nil, fmt.Errorf("failed to encrypt [result %d]", res)
	}
	return outbuf[:outlen], nil
}

func (ctx *decryptionCipherCtx) DecryptUpdate(input []byte) ([]byte, error) {
304 305 306
	if len(input) == 0 {
		return nil, nil
	}
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
	outbuf := make([]byte, len(input)+ctx.BlockSize())
	outlen := C.int(len(outbuf))
	res := C.EVP_DecryptUpdate(ctx.ctx, (*C.uchar)(&outbuf[0]), &outlen,
		(*C.uchar)(&input[0]), C.int(len(input)))
	if res != 1 {
		return nil, fmt.Errorf("failed to decrypt [result %d]", res)
	}
	return outbuf[:outlen], nil
}

func (ctx *encryptionCipherCtx) EncryptFinal() ([]byte, error) {
	outbuf := make([]byte, ctx.BlockSize())
	var outlen C.int
	if 1 != C.EVP_EncryptFinal_ex(ctx.ctx, (*C.uchar)(&outbuf[0]), &outlen) {
		return nil, errors.New("encryption failed")
	}
	return outbuf[:outlen], nil
}

func (ctx *decryptionCipherCtx) DecryptFinal() ([]byte, error) {
	outbuf := make([]byte, ctx.BlockSize())
	var outlen C.int
	if 1 != C.EVP_DecryptFinal_ex(ctx.ctx, (*C.uchar)(&outbuf[0]), &outlen) {
		// this may mean the tag failed to verify- all previous plaintext
		// returned must be considered faked and invalid
		return nil, errors.New("decryption failed")
	}
	return outbuf[:outlen], nil
}