| 1 | // Copyright 2019 The age Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // Package stream implements a variant of the STREAM chunked encryption scheme. |
| 6 | package stream |
| 7 | |
| 8 | import ( |
| 9 | "bytes" |
| 10 | "crypto/cipher" |
| 11 | "encoding/binary" |
| 12 | "errors" |
| 13 | "fmt" |
| 14 | "io" |
| 15 | "math" |
| 16 | "sync/atomic" |
| 17 | |
| 18 | "golang.org/x/crypto/chacha20poly1305" |
| 19 | ) |
| 20 | |
| 21 | const ChunkSize = 64 * 1024 |
| 22 | |
| 23 | func EncryptedChunkCount(encryptedSize int64) (int64, error) { |
| 24 | if encryptedSize < 0 || encryptedSize > math.MaxInt64-encChunkSize+1 { |
| 25 | return 0, fmt.Errorf("invalid encrypted payload size: %d", encryptedSize) |
| 26 | } |
| 27 | chunks := (encryptedSize + encChunkSize - 1) / encChunkSize |
| 28 | |
| 29 | plaintextSize := encryptedSize - chunks*chacha20poly1305.Overhead |
| 30 | expChunks := (plaintextSize + ChunkSize - 1) / ChunkSize |
| 31 | // Empty plaintext, the only case that allows (and requires) an empty chunk. |
| 32 | if plaintextSize == 0 { |
| 33 | expChunks = 1 |
| 34 | } |
| 35 | if expChunks != chunks { |
| 36 | return 0, fmt.Errorf("invalid encrypted payload size: %d", encryptedSize) |
| 37 | } |
| 38 | |
| 39 | return chunks, nil |
| 40 | } |
| 41 | |
| 42 | func PlaintextSize(encryptedSize int64) (int64, error) { |
| 43 | chunks, err := EncryptedChunkCount(encryptedSize) |
| 44 | if err != nil { |
| 45 | return 0, err |
| 46 | } |
| 47 | plaintextSize := encryptedSize - chunks*chacha20poly1305.Overhead |
| 48 | return plaintextSize, nil |
| 49 | } |
| 50 | |
| 51 | type DecryptReader struct { |
| 52 | a cipher.AEAD |
| 53 | src io.Reader |
| 54 | |
| 55 | unread []byte // decrypted but unread data, backed by buf |
| 56 | buf [encChunkSize]byte |
| 57 | |
| 58 | err error |
| 59 | nonce [chacha20poly1305.NonceSize]byte |
| 60 | } |
| 61 | |
| 62 | const ( |
| 63 | encChunkSize = ChunkSize + chacha20poly1305.Overhead |
| 64 | lastChunkFlag = 0x01 |
| 65 | ) |
| 66 | |
| 67 | func NewDecryptReader(key []byte, src io.Reader) (*DecryptReader, error) { |
| 68 | aead, err := chacha20poly1305.New(key) |
| 69 | if err != nil { |
| 70 | return nil, err |
| 71 | } |
| 72 | return &DecryptReader{a: aead, src: src}, nil |
| 73 | } |
| 74 | |
| 75 | func (r *DecryptReader) Read(p []byte) (int, error) { |
| 76 | if len(r.unread) > 0 { |
| 77 | n := copy(p, r.unread) |
| 78 | r.unread = r.unread[n:] |
| 79 | return n, nil |
| 80 | } |
| 81 | if r.err != nil { |
| 82 | return 0, r.err |
| 83 | } |
| 84 | if len(p) == 0 { |
| 85 | return 0, nil |
| 86 | } |
| 87 | |
| 88 | last, err := r.readChunk() |
| 89 | if err != nil { |
| 90 | r.err = err |
| 91 | return 0, err |
| 92 | } |
| 93 | |
| 94 | n := copy(p, r.unread) |
| 95 | r.unread = r.unread[n:] |
| 96 | |
| 97 | if last { |
| 98 | // Ensure there is an EOF after the last chunk as expected. In other |
| 99 | // words, check for trailing data after a full-length final chunk. |
| 100 | // Hopefully, the underlying reader supports returning EOF even if it |
| 101 | // had previously returned an EOF to ReadFull. |
| 102 | if _, err := io.ReadFull(r.src, make([]byte, 1)); err == nil { |
| 103 | r.err = errors.New("trailing data after end of encrypted file") |
| 104 | } else if err != io.EOF { |
| 105 | r.err = fmt.Errorf("non-EOF error reading after end of encrypted file: %w", err) |
| 106 | } else { |
| 107 | r.err = io.EOF |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | return n, nil |
| 112 | } |
| 113 | |
| 114 | // readChunk reads the next chunk of ciphertext from r.src and makes it available |
| 115 | // in r.unread. last is true if the chunk was marked as the end of the message. |
| 116 | // readChunk must not be called again after returning a last chunk or an error. |
| 117 | func (r *DecryptReader) readChunk() (last bool, err error) { |
| 118 | if len(r.unread) != 0 { |
| 119 | panic("stream: internal error: readChunk called with dirty buffer") |
| 120 | } |
| 121 | |
| 122 | in := r.buf[:] |
| 123 | n, err := io.ReadFull(r.src, in) |
| 124 | switch { |
| 125 | case err == io.EOF: |
| 126 | // A message can't end without a marked chunk. This message is truncated. |
| 127 | return false, io.ErrUnexpectedEOF |
| 128 | case err == io.ErrUnexpectedEOF: |
| 129 | // The last chunk can be short, but not empty unless it's the first and |
| 130 | // only chunk. |
| 131 | if !nonceIsZero(&r.nonce) && n == r.a.Overhead() { |
| 132 | return false, errors.New("last chunk is empty, try age v1.0.0, and please consider reporting this") |
| 133 | } |
| 134 | in = in[:n] |
| 135 | last = true |
| 136 | setLastChunkFlag(&r.nonce) |
| 137 | case err != nil: |
| 138 | return false, err |
| 139 | } |
| 140 | |
| 141 | outBuf := make([]byte, 0, ChunkSize) |
| 142 | out, err := r.a.Open(outBuf, r.nonce[:], in, nil) |
| 143 | if err != nil && !last { |
| 144 | // Check if this was a full-length final chunk. |
| 145 | last = true |
| 146 | setLastChunkFlag(&r.nonce) |
| 147 | out, err = r.a.Open(outBuf, r.nonce[:], in, nil) |
| 148 | } |
| 149 | if err != nil { |
| 150 | return false, errors.New("failed to decrypt and authenticate payload chunk, file may be corrupted or tampered with") |
| 151 | } |
| 152 | |
| 153 | incNonce(&r.nonce) |
| 154 | r.unread = r.buf[:copy(r.buf[:], out)] |
| 155 | return last, nil |
| 156 | } |
| 157 | |
| 158 | func incNonce(nonce *[chacha20poly1305.NonceSize]byte) { |
| 159 | for i := len(nonce) - 2; i >= 0; i-- { |
| 160 | nonce[i]++ |
| 161 | if nonce[i] != 0 { |
| 162 | return |
| 163 | } |
| 164 | } |
| 165 | // The counter is 88 bits, this is unreachable. |
| 166 | panic("stream: chunk counter wrapped around") |
| 167 | } |
| 168 | |
| 169 | func nonceForChunk(chunkIndex int64) *[chacha20poly1305.NonceSize]byte { |
| 170 | var nonce [chacha20poly1305.NonceSize]byte |
| 171 | binary.BigEndian.PutUint64(nonce[3:11], uint64(chunkIndex)) |
| 172 | return &nonce |
| 173 | } |
| 174 | |
| 175 | func setLastChunkFlag(nonce *[chacha20poly1305.NonceSize]byte) { |
| 176 | nonce[len(nonce)-1] = lastChunkFlag |
| 177 | } |
| 178 | |
| 179 | func nonceIsZero(nonce *[chacha20poly1305.NonceSize]byte) bool { |
| 180 | return *nonce == [chacha20poly1305.NonceSize]byte{} |
| 181 | } |
| 182 | |
| 183 | type EncryptWriter struct { |
| 184 | a cipher.AEAD |
| 185 | dst io.Writer |
| 186 | buf bytes.Buffer |
| 187 | nonce [chacha20poly1305.NonceSize]byte |
| 188 | err error |
| 189 | } |
| 190 | |
| 191 | func NewEncryptWriter(key []byte, dst io.Writer) (*EncryptWriter, error) { |
| 192 | aead, err := chacha20poly1305.New(key) |
| 193 | if err != nil { |
| 194 | return nil, err |
| 195 | } |
| 196 | return &EncryptWriter{a: aead, dst: dst}, nil |
| 197 | } |
| 198 | |
| 199 | func (w *EncryptWriter) Write(p []byte) (n int, err error) { |
| 200 | if w.err != nil { |
| 201 | return 0, w.err |
| 202 | } |
| 203 | if len(p) == 0 { |
| 204 | return 0, nil |
| 205 | } |
| 206 | |
| 207 | total := len(p) |
| 208 | for len(p) > 0 { |
| 209 | n := min(len(p), ChunkSize-w.buf.Len()) |
| 210 | w.buf.Write(p[:n]) |
| 211 | p = p[n:] |
| 212 | |
| 213 | // Only flush if there's a full chunk with bytes still to write, or we |
| 214 | // can't know if this is the last chunk yet. |
| 215 | if w.buf.Len() == ChunkSize && len(p) > 0 { |
| 216 | if err := w.flushChunk(notLastChunk); err != nil { |
| 217 | w.err = err |
| 218 | return 0, err |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | return total, nil |
| 223 | } |
| 224 | |
| 225 | // Close flushes the last chunk. It does not close the underlying Writer. |
| 226 | func (w *EncryptWriter) Close() error { |
| 227 | if w.err != nil { |
| 228 | return w.err |
| 229 | } |
| 230 | |
| 231 | w.err = w.flushChunk(lastChunk) |
| 232 | if w.err != nil { |
| 233 | return w.err |
| 234 | } |
| 235 | |
| 236 | w.err = errors.New("stream.Writer is already closed") |
| 237 | return nil |
| 238 | } |
| 239 | |
| 240 | const ( |
| 241 | lastChunk = true |
| 242 | notLastChunk = false |
| 243 | ) |
| 244 | |
| 245 | func (w *EncryptWriter) flushChunk(last bool) error { |
| 246 | if !last && w.buf.Len() != ChunkSize { |
| 247 | panic("stream: internal error: flush called with partial chunk") |
| 248 | } |
| 249 | |
| 250 | if last { |
| 251 | setLastChunkFlag(&w.nonce) |
| 252 | } |
| 253 | w.buf.Grow(chacha20poly1305.Overhead) |
| 254 | ciphertext := w.a.Seal(w.buf.Bytes()[:0], w.nonce[:], w.buf.Bytes(), nil) |
| 255 | _, err := w.dst.Write(ciphertext) |
| 256 | incNonce(&w.nonce) |
| 257 | w.buf.Reset() |
| 258 | return err |
| 259 | } |
| 260 | |
| 261 | type EncryptReader struct { |
| 262 | a cipher.AEAD |
| 263 | src io.Reader |
| 264 | |
| 265 | // The first ready bytes of buf are already encrypted. This may be less than |
| 266 | // buf.Len(), because we need to over-read to know if a chunk is the last. |
| 267 | ready int |
| 268 | buf bytes.Buffer |
| 269 | |
| 270 | nonce [chacha20poly1305.NonceSize]byte |
| 271 | err error |
| 272 | } |
| 273 | |
| 274 | func NewEncryptReader(key []byte, src io.Reader) (*EncryptReader, error) { |
| 275 | aead, err := chacha20poly1305.New(key) |
| 276 | if err != nil { |
| 277 | return nil, err |
| 278 | } |
| 279 | return &EncryptReader{a: aead, src: src}, nil |
| 280 | } |
| 281 | |
| 282 | func (r *EncryptReader) Read(p []byte) (int, error) { |
| 283 | if r.ready > 0 { |
| 284 | n, err := r.buf.Read(p[:min(len(p), r.ready)]) |
| 285 | r.ready -= n |
| 286 | return n, err |
| 287 | } |
| 288 | if r.err != nil { |
| 289 | return 0, r.err |
| 290 | } |
| 291 | if len(p) == 0 { |
| 292 | return 0, nil |
| 293 | } |
| 294 | |
| 295 | if err := r.feedBuffer(); err != nil { |
| 296 | r.err = err |
| 297 | return 0, err |
| 298 | } |
| 299 | |
| 300 | n, err := r.buf.Read(p[:min(len(p), r.ready)]) |
| 301 | r.ready -= n |
| 302 | return n, err |
| 303 | } |
| 304 | |
| 305 | // feedBuffer reads and encrypts the next chunk from r.src and appends it to |
| 306 | // r.buf. It sets r.ready to the number of newly available bytes in r.buf. |
| 307 | func (r *EncryptReader) feedBuffer() error { |
| 308 | if r.ready > 0 { |
| 309 | panic("stream: internal error: feedBuffer called with dirty buffer") |
| 310 | } |
| 311 | |
| 312 | // CopyN will use r.buf.ReadFrom/WriteTo to fill the buffer directly. |
| 313 | // We need ChunkSize + 1 bytes to determine if this is the last chunk. |
| 314 | _, err := io.CopyN(&r.buf, r.src, int64(ChunkSize-r.buf.Len()+1)) |
| 315 | if err != nil && err != io.EOF { |
| 316 | return err |
| 317 | } |
| 318 | |
| 319 | if last := r.buf.Len() <= ChunkSize; last { |
| 320 | setLastChunkFlag(&r.nonce) |
| 321 | |
| 322 | // After Grow, we know r.buf.Bytes() has enough capacity for the |
| 323 | // overhead. We encrypt in place and then do a Write to include the |
| 324 | // overhead in the buffer. |
| 325 | r.buf.Grow(chacha20poly1305.Overhead) |
| 326 | plaintext := r.buf.Bytes() |
| 327 | r.a.Seal(plaintext[:0], r.nonce[:], plaintext, nil) |
| 328 | incNonce(&r.nonce) |
| 329 | r.buf.Write(plaintext[len(plaintext) : len(plaintext)+chacha20poly1305.Overhead]) |
| 330 | r.ready = r.buf.Len() |
| 331 | |
| 332 | r.err = io.EOF |
| 333 | return nil |
| 334 | } |
| 335 | |
| 336 | // Same, but accounting for the tail byte which will remain unencrypted and |
| 337 | // needs to be shifted past the overhead. |
| 338 | if r.buf.Len() != ChunkSize+1 { |
| 339 | panic("stream: internal error: unexpected buffer length") |
| 340 | } |
| 341 | tailByte := r.buf.Bytes()[ChunkSize] |
| 342 | r.buf.Grow(chacha20poly1305.Overhead) |
| 343 | plaintext := r.buf.Bytes()[:ChunkSize] |
| 344 | r.a.Seal(plaintext[:0], r.nonce[:], plaintext, nil) |
| 345 | incNonce(&r.nonce) |
| 346 | r.buf.Write(plaintext[len(plaintext)+1 : len(plaintext)+chacha20poly1305.Overhead]) |
| 347 | r.buf.WriteByte(tailByte) |
| 348 | r.ready = ChunkSize + chacha20poly1305.Overhead |
| 349 | |
| 350 | return nil |
| 351 | } |
| 352 | |
| 353 | type DecryptReaderAt struct { |
| 354 | a cipher.AEAD |
| 355 | src io.ReaderAt |
| 356 | size int64 |
| 357 | chunks int64 |
| 358 | cache atomic.Pointer[cachedChunk] |
| 359 | } |
| 360 | |
| 361 | type cachedChunk struct { |
| 362 | off int64 |
| 363 | data []byte |
| 364 | } |
| 365 | |
| 366 | func readFullAt(r io.ReaderAt, p []byte, off int64) error { |
| 367 | n, err := r.ReadAt(p, off) |
| 368 | switch { |
| 369 | case n == len(p) && errors.Is(err, io.EOF): |
| 370 | // io.ReaderAt implementations are allowed to return io.EOF when the |
| 371 | // read reaches the end of the source. |
| 372 | err = nil |
| 373 | case n < len(p) && (err == nil || errors.Is(err, io.EOF)): |
| 374 | // Incorrect io.ReaderAt implementation, or the source is short. |
| 375 | err = io.ErrUnexpectedEOF |
| 376 | } |
| 377 | return err |
| 378 | } |
| 379 | |
| 380 | func NewDecryptReaderAt(key []byte, src io.ReaderAt, size int64) (*DecryptReaderAt, error) { |
| 381 | aead, err := chacha20poly1305.New(key) |
| 382 | if err != nil { |
| 383 | return nil, err |
| 384 | } |
| 385 | |
| 386 | // Check that size is valid by decrypting the final chunk. |
| 387 | chunks, err := EncryptedChunkCount(size) |
| 388 | if err != nil { |
| 389 | return nil, err |
| 390 | } |
| 391 | finalChunkIndex := chunks - 1 |
| 392 | finalChunkOff := finalChunkIndex * encChunkSize |
| 393 | finalChunkSize := size - finalChunkOff |
| 394 | finalChunk := make([]byte, finalChunkSize) |
| 395 | if err := readFullAt(src, finalChunk, finalChunkOff); err != nil { |
| 396 | return nil, fmt.Errorf("failed to read final chunk: %w", err) |
| 397 | } |
| 398 | nonce := nonceForChunk(finalChunkIndex) |
| 399 | setLastChunkFlag(nonce) |
| 400 | plaintext, err := aead.Open(finalChunk[:0], nonce[:], finalChunk, nil) |
| 401 | if err != nil { |
| 402 | return nil, fmt.Errorf("failed to decrypt and authenticate final chunk: %w", err) |
| 403 | } |
| 404 | cache := &cachedChunk{off: finalChunkOff, data: plaintext} |
| 405 | |
| 406 | plaintextSize := size - chunks*chacha20poly1305.Overhead |
| 407 | r := &DecryptReaderAt{a: aead, src: src, size: plaintextSize, chunks: chunks} |
| 408 | r.cache.Store(cache) |
| 409 | return r, nil |
| 410 | } |
| 411 | |
| 412 | func (r *DecryptReaderAt) ReadAt(p []byte, off int64) (n int, err error) { |
| 413 | if off < 0 || off > r.size { |
| 414 | return 0, fmt.Errorf("offset out of range [0:%d]: %d", r.size, off) |
| 415 | } |
| 416 | if len(p) == 0 { |
| 417 | return 0, nil |
| 418 | } |
| 419 | var cacheUpdate *cachedChunk |
| 420 | chunk := make([]byte, encChunkSize) |
| 421 | for len(p) > 0 && off < r.size { |
| 422 | chunkIndex := off / ChunkSize |
| 423 | chunkOff := chunkIndex * encChunkSize |
| 424 | encSize := r.size + r.chunks*chacha20poly1305.Overhead |
| 425 | chunkSize := min(encSize-chunkOff, encChunkSize) |
| 426 | |
| 427 | cached := r.cache.Load() |
| 428 | var plaintext []byte |
| 429 | if cached != nil && cached.off == chunkOff { |
| 430 | plaintext = cached.data |
| 431 | cacheUpdate = nil |
| 432 | } else { |
| 433 | if err := readFullAt(r.src, chunk[:chunkSize], chunkOff); err != nil { |
| 434 | return n, fmt.Errorf("failed to read chunk at offset %d: %w", chunkOff, err) |
| 435 | } |
| 436 | nonce := nonceForChunk(chunkIndex) |
| 437 | if chunkIndex == r.chunks-1 { |
| 438 | setLastChunkFlag(nonce) |
| 439 | } |
| 440 | var err error |
| 441 | plaintext, err = r.a.Open(chunk[:0], nonce[:], chunk[:chunkSize], nil) |
| 442 | if err != nil { |
| 443 | return n, fmt.Errorf("failed to decrypt and authenticate chunk at offset %d: %w", chunkOff, err) |
| 444 | } |
| 445 | cacheUpdate = &cachedChunk{off: chunkOff, data: plaintext} |
| 446 | } |
| 447 | |
| 448 | plainChunkOff := int(off - chunkIndex*ChunkSize) |
| 449 | copySize := min(len(plaintext)-plainChunkOff, len(p)) |
| 450 | copy(p, plaintext[plainChunkOff:plainChunkOff+copySize]) |
| 451 | p = p[copySize:] |
| 452 | off += int64(copySize) |
| 453 | n += copySize |
| 454 | } |
| 455 | if cacheUpdate != nil { |
| 456 | r.cache.Store(cacheUpdate) |
| 457 | } |
| 458 | if off == r.size { |
| 459 | return n, io.EOF |
| 460 | } |
| 461 | return n, nil |
| 462 | } |