SPB Git

Repository Public

crypt.go 4.8 KB 203 lines go

1// Package backup produces and restores encrypted PostgreSQL dumps.2//3// Stream format (version 1):4//5//	magic "MCCBK1\n" | 4-byte random nonce prefix | chunks…6//	chunk = 4-byte big-endian ciphertext length | AES-256-GCM(ciphertext+tag)7//8// Each chunk is sealed with nonce = prefix || 8-byte counter and additional9// data "more" or "last". The final chunk is always marked "last" (it may be10// empty), so truncation, reordering, duplication or removal of chunks is11// detected on read. The key is 32 random bytes kept in the secrets12// directory; a copy must be stored off the host or backups are useless13// after a disk loss.14package backup1516import (17	"bufio"18	"crypto/aes"19	"crypto/cipher"20	"crypto/rand"21	"encoding/binary"22	"errors"23	"fmt"24	"io"25)2627const (28	magic     = "MCCBK1\n"29	chunkSize = 64 << 1030)3132var (33	ErrFormat    = errors.New("backup: not an MCC backup file")34	ErrCorrupt   = errors.New("backup: authentication failed (wrong key, or corrupted/tampered file)")35	ErrTruncated = errors.New("backup: file is truncated")36)3738func newGCM(key []byte) (cipher.AEAD, error) {39	if len(key) != 32 {40		return nil, fmt.Errorf("backup: key must be 32 bytes, got %d", len(key))41	}42	block, err := aes.NewCipher(key)43	if err != nil {44		return nil, err45	}46	return cipher.NewGCM(block)47}4849type encWriter struct {50	w      *bufio.Writer51	aead   cipher.AEAD52	prefix [4]byte53	ctr    uint6454	buf    []byte55	closed bool56}5758// NewEncrypter returns a WriteCloser that encrypts to w. Close MUST be59// called: it writes the final authenticated chunk.60func NewEncrypter(w io.Writer, key []byte) (io.WriteCloser, error) {61	aead, err := newGCM(key)62	if err != nil {63		return nil, err64	}65	e := &encWriter{w: bufio.NewWriterSize(w, 1<<20), aead: aead, buf: make([]byte, 0, chunkSize)}66	if _, err := rand.Read(e.prefix[:]); err != nil {67		return nil, err68	}69	if _, err := e.w.WriteString(magic); err != nil {70		return nil, err71	}72	if _, err := e.w.Write(e.prefix[:]); err != nil {73		return nil, err74	}75	return e, nil76}7778func (e *encWriter) nonce() []byte {79	n := make([]byte, 12)80	copy(n, e.prefix[:])81	binary.BigEndian.PutUint64(n[4:], e.ctr)82	e.ctr++83	return n84}8586func (e *encWriter) seal(last bool) error {87	ad := []byte("more")88	if last {89		ad = []byte("last")90	}91	ct := e.aead.Seal(nil, e.nonce(), e.buf, ad)92	var l [4]byte93	binary.BigEndian.PutUint32(l[:], uint32(len(ct)))94	if _, err := e.w.Write(l[:]); err != nil {95		return err96	}97	_, err := e.w.Write(ct)98	e.buf = e.buf[:0]99	return err100}101102func (e *encWriter) Write(p []byte) (int, error) {103	if e.closed {104		return 0, errors.New("backup: write after close")105	}106	n := len(p)107	for len(p) > 0 {108		room := chunkSize - len(e.buf)109		if room > len(p) {110			room = len(p)111		}112		e.buf = append(e.buf, p[:room]...)113		p = p[room:]114		if len(e.buf) == chunkSize {115			if err := e.seal(false); err != nil {116				return 0, err117			}118		}119	}120	return n, nil121}122123func (e *encWriter) Close() error {124	if e.closed {125		return nil126	}127	e.closed = true128	if err := e.seal(true); err != nil {129		return err130	}131	return e.w.Flush()132}133134type decReader struct {135	r      *bufio.Reader136	aead   cipher.AEAD137	prefix [4]byte138	ctr    uint64139	plain  []byte140	done   bool141}142143// NewDecrypter returns a Reader of the plaintext. It returns ErrCorrupt or144// ErrTruncated instead of io.EOF if the stream is not complete and authentic.145func NewDecrypter(r io.Reader, key []byte) (io.Reader, error) {146	aead, err := newGCM(key)147	if err != nil {148		return nil, err149	}150	d := &decReader{r: bufio.NewReaderSize(r, 1<<20), aead: aead}151	head := make([]byte, len(magic)+4)152	if _, err := io.ReadFull(d.r, head); err != nil || string(head[:len(magic)]) != magic {153		return nil, ErrFormat154	}155	copy(d.prefix[:], head[len(magic):])156	return d, nil157}158159func (d *decReader) Read(p []byte) (int, error) {160	for len(d.plain) == 0 {161		if d.done {162			return 0, io.EOF163		}164		var l [4]byte165		if _, err := io.ReadFull(d.r, l[:]); err != nil {166			return 0, ErrTruncated167		}168		n := binary.BigEndian.Uint32(l[:])169		if n < uint32(d.aead.Overhead()) || n > chunkSize+uint32(d.aead.Overhead()) {170			return 0, ErrCorrupt171		}172		ct := make([]byte, n)173		if _, err := io.ReadFull(d.r, ct); err != nil {174			return 0, ErrTruncated175		}176		nonce := make([]byte, 12)177		copy(nonce, d.prefix[:])178		binary.BigEndian.PutUint64(nonce[4:], d.ctr)179		d.ctr++180		// A chunk is "last" exactly when nothing follows it.181		_, peekErr := d.r.Peek(1)182		ad := []byte("more")183		if peekErr == io.EOF {184			ad = []byte("last")185		}186		pt, err := d.aead.Open(nil, nonce, ct, ad)187		if err != nil {188			if peekErr == io.EOF {189				// Either tampering, or the real last chunk was cut off and this "more" chunk is now at the end.190				if _, e2 := d.aead.Open(nil, nonce, ct, []byte("more")); e2 == nil {191					return 0, ErrTruncated192				}193			}194			return 0, ErrCorrupt195		}196		d.plain = pt197		d.done = peekErr == io.EOF198	}199	n := copy(p, d.plain)200	d.plain = d.plain[n:]201	return n, nil202}203
Files main
Menu

Theme