Skip to content

Commit

Permalink
fix: make sure the size calculation in Xchacha20 does not overflow
Browse files Browse the repository at this point in the history
  • Loading branch information
alnr committed Sep 9, 2024
1 parent 03478f9 commit 03470ca
Showing 1 changed file with 6 additions and 0 deletions.
6 changes: 6 additions & 0 deletions cipher/chacha20.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"crypto/rand"
"encoding/hex"
"io"
"math"

"github.com/pkg/errors"
"golang.org/x/crypto/chacha20poly1305"
Expand Down Expand Up @@ -43,6 +44,11 @@ func (c *XChaCha20Poly1305) Encrypt(ctx context.Context, message []byte) (string
return "", herodot.ErrInternalServerError.WithWrap(err).WithReason("Unable to generate key")
}

// Make sure the size calculation does not overflow.
if len(message) > math.MaxInt-aead.NonceSize()-aead.Overhead() {
return "", errors.WithStack(herodot.ErrInternalServerError.WithReason("plaintext too large"))
}

nonce := make([]byte, aead.NonceSize(), aead.NonceSize()+len(message)+aead.Overhead())
_, err = io.ReadFull(rand.Reader, nonce)
if err != nil {
Expand Down

0 comments on commit 03470ca

Please sign in to comment.