diff --git a/crypt/file.go b/crypt/file.go index 8b38aaf..e29d206 100644 --- a/crypt/file.go +++ b/crypt/file.go @@ -113,14 +113,23 @@ func (f *EncryptedFile) WriteDecryptedFileToDisk(filePath string) error { } func (f *EncryptedFile) unpackFileAndDecrypt(packedFile []byte) error { + keyLen := f.privateKey.Size() + + minReqLen := aes.BlockSize + keyLen + len(hmacKey) + + if len(packedFile) < minReqLen { + return fmt.Errorf("packed file is too short to be valid") + } + if bytes.Contains(packedFile, []byte(hmacKey)) { parts := bytes.SplitN(packedFile, []byte(hmacKey), 2) packedFile, f.hmac = parts[0], parts[1] } - keyLen := f.privateKey.Size() - lenWithoutKey := len(packedFile) - keyLen + if lenWithoutKey < aes.BlockSize { + return fmt.Errorf("packed file is too short to contain valid nonce and ciphertext") + } packedFile, f.symmetricKeyEnc = packedFile[0:lenWithoutKey], packedFile[lenWithoutKey:] diff --git a/crypt/keys.go b/crypt/keys.go index c424c4c..2f0242f 100644 --- a/crypt/keys.go +++ b/crypt/keys.go @@ -7,6 +7,7 @@ import ( "crypto/sha512" "crypto/x509" "encoding/pem" + "fmt" "os" ) @@ -85,6 +86,10 @@ func (f *EncryptedFile) GenerateSymmetricKey() error { func (f *EncryptedFile) ParsePublicPem() error { pemKeyBin, _ := pem.Decode(f.PublicPem) + if pemKeyBin == nil { + return fmt.Errorf("failed to parse PEM block containing the public key") + } + if bytes.Contains(f.PublicPem, []byte("-----BEGIN PUBLIC KEY-----")) { key, err := x509.ParsePKIXPublicKey(pemKeyBin.Bytes) if err != nil { @@ -109,6 +114,10 @@ func (f *EncryptedFile) ParsePublicPem() error { func (f *EncryptedFile) ParsePrivatePem() error { pemKeyBin, _ := pem.Decode(f.privatePem) + if pemKeyBin == nil { + return fmt.Errorf("failed to parse PEM block containing the private key") + } + if bytes.Contains(f.privatePem, []byte("-----BEGIN PRIVATE KEY-----")) { key, err := x509.ParsePKCS8PrivateKey(pemKeyBin.Bytes) if err != nil {