rw.go 6.2 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3
package secio

import (
Jeromy's avatar
Jeromy committed
4
	"context"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
5
	"crypto/cipher"
Jeromy's avatar
Jeromy committed
6
	"crypto/hmac"
7
	"encoding/binary"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8 9 10 11 12
	"errors"
	"fmt"
	"io"
	"sync"

Lars Gierth's avatar
Lars Gierth committed
13 14 15
	proto "github.com/gogo/protobuf/proto"
	msgio "github.com/jbenet/go-msgio"
	mpool "github.com/jbenet/go-msgio/mpool"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
16 17 18 19 20 21 22 23 24 25 26
)

// ErrMACInvalid signals that a MAC verification failed
var ErrMACInvalid = errors.New("MAC verification failed")

// bufPool is a ByteSlicePool for messages. we need buffers because (sadly)
// we cannot encrypt in place-- the user needs their buffer back.
var bufPool = mpool.ByteSlicePool

type etmWriter struct {
	// params
27 28 29 30
	pool mpool.Pool    // for the buffers with encrypted data
	str  cipher.Stream // the stream cipher to encrypt with
	mac  HMAC          // the mac to authenticate data with
	w    io.Writer
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
31 32 33 34 35 36

	sync.Mutex
}

// NewETMWriter Encrypt-Then-MAC
func NewETMWriter(w io.Writer, s cipher.Stream, mac HMAC) msgio.WriteCloser {
37
	return &etmWriter{w: w, str: s, mac: mac, pool: bufPool}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
}

// Write writes passed in buffer as a single message.
func (w *etmWriter) Write(b []byte) (int, error) {
	if err := w.WriteMsg(b); err != nil {
		return 0, err
	}
	return len(b), nil
}

// WriteMsg writes the msg in the passed in buffer.
func (w *etmWriter) WriteMsg(b []byte) error {
	w.Lock()
	defer w.Unlock()

53
	bufsize := uint32(4 + len(b) + w.mac.Size())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
54
	// encrypt.
55 56
	buf := w.pool.Get(bufsize).([]byte)
	data := buf[4 : 4+len(b)] // the pool's buffer may be larger
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
57 58 59 60 61 62 63 64 65 66 67 68 69
	w.str.XORKeyStream(data, b)

	// log.Debugf("ENC plaintext (%d): %s %v", len(b), b, b)
	// log.Debugf("ENC ciphertext (%d): %s %v", len(data), data, data)

	// then, mac.
	if _, err := w.mac.Write(data); err != nil {
		return err
	}

	// Sum appends.
	data = w.mac.Sum(data)
	w.mac.Reset()
70
	binary.BigEndian.PutUint32(buf[:4], uint32(len(data)))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
71

72 73 74
	_, err := w.w.Write(buf[:bufsize])
	w.pool.Put(bufsize, buf)
	return err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
75 76 77
}

func (w *etmWriter) Close() error {
78 79 80 81
	if c, ok := w.w.(io.Closer); ok {
		return c.Close()
	}
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
82 83 84 85 86 87
}

type etmReader struct {
	msgio.Reader
	io.Closer

88
	// internal buffer returned from the msgio
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
89 90
	buf []byte

91 92 93 94
	// low and high watermark for the buffered data
	lowat int
	hiwat int

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
	// params
	msg msgio.ReadCloser // msgio for knowing where boundaries lie
	str cipher.Stream    // the stream cipher to encrypt with
	mac HMAC             // the mac to authenticate data with

	sync.Mutex
}

// NewETMReader Encrypt-Then-MAC
func NewETMReader(r io.Reader, s cipher.Stream, mac HMAC) msgio.ReadCloser {
	return &etmReader{msg: msgio.NewReader(r), str: s, mac: mac}
}

func (r *etmReader) NextMsgLen() (int, error) {
	return r.msg.NextMsgLen()
}

112 113 114
func (r *etmReader) drain(buf []byte) int {
	// Return zero if there is no data remaining in the internal buffer.
	if r.lowat == r.hiwat {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
115 116 117
		return 0
	}

118 119 120 121 122 123 124 125 126 127 128 129 130 131
	// Copy data to the output buffer.
	n := copy(buf, r.buf[r.lowat:r.hiwat])

	// Update the low watermark.
	r.lowat += n

	// Release the buffer and reset the watermarks if it has been fully read.
	if r.lowat == r.hiwat {
		r.msg.ReleaseMsg(r.buf)
		r.buf = nil
		r.lowat = 0
		r.hiwat = 0
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
132 133 134
	return n
}

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
func (r *etmReader) fill() error {
	// Read a message from the underlying msgio.
	msg, err := r.msg.ReadMsg()
	if err != nil {
		return err
	}

	// Check the MAC.
	n, err := r.macCheckThenDecrypt(msg)
	if err != nil {
		r.msg.ReleaseMsg(msg)
		return err
	}

	// Retain the buffer so it can be drained from and later released.
	r.buf = msg
	r.lowat = 0
	r.hiwat = n

	return nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
157 158 159 160
func (r *etmReader) Read(buf []byte) (int, error) {
	r.Lock()
	defer r.Unlock()

161 162
	// Return buffered data without reading more, if possible.
	copied := r.drain(buf)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
163 164 165 166
	if copied > 0 {
		return copied, nil
	}

167
	// Check the length of the next message.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
168 169 170 171 172
	fullLen, err := r.msg.NextMsgLen()
	if err != nil {
		return 0, err
	}

173 174
	// If the destination buffer is too short, fill an internal buffer and then
	// drain as much of that into the output buffer as will fit.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
175
	if cap(buf) < fullLen {
176 177 178 179 180 181 182
		err := r.fill()
		if err != nil {
			return 0, err
		}

		copied := r.drain(buf)
		return copied, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
183 184
	}

185 186
	// Otherwise, read directly into the destination buffer.
	n, err := io.ReadFull(r.msg, buf[:fullLen])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
187
	if err != nil {
188
		return 0, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
189 190
	}

191
	m, err := r.macCheckThenDecrypt(buf[:n])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
192 193 194 195
	if err != nil {
		return 0, err
	}

196
	return m, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
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
}

func (r *etmReader) ReadMsg() ([]byte, error) {
	r.Lock()
	defer r.Unlock()

	msg, err := r.msg.ReadMsg()
	if err != nil {
		return nil, err
	}

	n, err := r.macCheckThenDecrypt(msg)
	if err != nil {
		return nil, err
	}
	return msg[:n], nil
}

func (r *etmReader) macCheckThenDecrypt(m []byte) (int, error) {
	l := len(m)
	if l < r.mac.size {
		return 0, fmt.Errorf("buffer (%d) shorter than MAC size (%d)", l, r.mac.size)
	}

	mark := l - r.mac.size
	data := m[:mark]
	macd := m[mark:]

	r.mac.Write(data)
	expected := r.mac.Sum(nil)
	r.mac.Reset()

	// check mac. if failed, return error.
	if !hmac.Equal(macd, expected) {
		log.Debug("MAC Invalid:", expected, "!=", macd)
		return 0, ErrMACInvalid
	}

	// ok seems good. decrypt. (can decrypt in place, yay!)
	// log.Debugf("DEC ciphertext (%d): %s %v", len(data), data, data)
	r.str.XORKeyStream(data, data)
	// log.Debugf("DEC plaintext (%d): %s %v", len(data), data, data)

	return mark, nil
}

243 244
func (r *etmReader) Close() error {
	return r.msg.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
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
}

// ReleaseMsg signals a buffer can be reused.
func (r *etmReader) ReleaseMsg(b []byte) {
	r.msg.ReleaseMsg(b)
}

// writeMsgCtx is used by the
func writeMsgCtx(ctx context.Context, w msgio.Writer, msg proto.Message) ([]byte, error) {
	enc, err := proto.Marshal(msg)
	if err != nil {
		return nil, err
	}

	// write in a goroutine so we can exit when our context is cancelled.
	done := make(chan error)
	go func(m []byte) {
		err := w.WriteMsg(m)
		select {
		case done <- err:
		case <-ctx.Done():
		}
	}(enc)

	select {
	case <-ctx.Done():
		return nil, ctx.Err()
	case e := <-done:
		return enc, e
	}
}

func readMsgCtx(ctx context.Context, r msgio.Reader, p proto.Message) ([]byte, error) {
	var msg []byte

	// read in a goroutine so we can exit when our context is cancelled.
	done := make(chan error)
	go func() {
		var err error
		msg, err = r.ReadMsg()
		select {
		case done <- err:
		case <-ctx.Done():
		}
	}()

	select {
	case <-ctx.Done():
		return nil, ctx.Err()
	case e := <-done:
		if e != nil {
			return nil, e
		}
	}

	return msg, proto.Unmarshal(msg, p)
}