This commit is contained in:
greeneclipse committed 2026-10-27 14:53:19 +01:00
1 parent c347d2418f
commit 1ad180a052
49 files changed
+6339 -89

No files matched your search

+103
View File
@@ -0,0 +1,103 @@
// Package crypto implements excel encryption algorithms from the
// MS-OFFCRYPTO design specs. Currently only standard/basic RC4
// "obfuscation" is supported.
package crypto
import (
"bytes"
"encoding/binary"
"fmt"
)
// Decryptor describes methods to decrypt an excel sheet.
type Decryptor interface {
// SetPassword for the decryption.
SetPassword(password []byte)
// Read implements the io.Reader interface.
Read(p []byte) (n int, err error)
// Write implements the io.Writer interface.
Write(p []byte) (n int, err error)
// Bytes returns the decrypted data.
Bytes() []byte
// Flush tells the decryptor to decrypt the latest block.
Flush()
// Reset the decryptor, and clear all written and readable data.
Reset()
}
// Algorithms designed based on specs in MS-OFFCRYPTO:
// https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-offcrypto/3c34d72a-1a61-4b52-a893-196f9157f083
// Important notes from MS-XLS section 2.2.10:
// https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-xls/cd03cb5f-ca02-4934-a391-bb674cb8aa06
// When obfuscating or encrypting BIFF records in these streams the record type and
// record size components MUST NOT be obfuscated or encrypted.
// In addition the following records MUST NOT be obfuscated or encrypted:
// BOF (section 2.4.21), FilePass (section 2.4.117), UsrExcl (section 2.4.339),
// FileLock (section 2.4.116), InterfaceHdr (section 2.4.146), RRDInfo (section 2.4.227),
// and RRDHead (section 2.4.226). Additionally, the lbPlyPos field of the BoundSheet8
// record (section 2.4.28) MUST NOT be encrypted.
// For RC4 encryption and RC4 CryptoAPI encryption, the Unicode password string is used
// to generate the encryption key as specified in [MS-OFFCRYPTO] section 2.3.6.2 or
// [MS-OFFCRYPTO] section 2.3.5.2 depending on the RC4 algorithm used. The record data
// is then encrypted by the specific RC4 algorithm in 1024-byte blocks. The block number
// is set to zero at the beginning of every BIFF record stream, and incremented by one
// at each 1024-byte boundary. Bytes to be encrypted are passed into the RC4 encryption
// function and then written to the stream. For unencrypted records and the record
// headers consisting of the record type and record size, a byte buffer of all zeros,
// of the same size as the section of unencrypted bytes, is passed into the RC4
// encryption function. The results are then ignored and the unencrypted bytes are
// written to the stream.
// DefaultXLSPassword is the default encryption password defined by note
// <100> Section 2.4.191: If the value of the wPassword field of the Password record in
// the Globals Substream is not 0x0000, Excel 97, Excel 2000, Excel 2002, Office Excel
// 2003, Office Excel 2007, and Excel 2010 encrypt the document as specified in [MS-OFFCRYPTO],
// section 2.3. If an encryption password is not specified or the workbook or sheet is only
// protected, the document is encrypted with the default password of:
// DefaultXLSPassword is the default Excel encryption password.
var DefaultXLSPassword = "VelvetSweatshop"
/////////////
// 2.3.6.1
type basicRC4Encryption struct {
MajorVersion uint16
MinorVersion uint16
Salt [16]byte
Verifier [16]byte
VerifierHash [16]byte
}
// NewBasicRC4 implements the standard RC4 decryption.
func NewBasicRC4(data []byte) (Decryptor, error) {
h := basicRC4Encryption{}
b := bytes.NewReader(data)
err := binary.Read(b, binary.LittleEndian, &h)
if err != nil {
return nil, err
}
if h.MinorVersion != 1 {
return nil, fmt.Errorf("xls: unknown basic-RC4 minor version %d (%d byte record)",
h.MinorVersion, len(data))
}
if len(data) != 52 {
return nil, fmt.Errorf("xls: data length is invalid (expected 52 bytes, got %d)",
len(data))
}
d := &rc4Writer{
Salt: make([]byte, len(h.Salt)),
}
copy(d.Salt, h.Salt[:])
return d, d.Verify(h.Verifier[:], h.VerifierHash[:])
}
+155
View File
@@ -0,0 +1,155 @@
package crypto
import (
"bytes"
"crypto/md5"
"crypto/rc4"
"encoding/binary"
"fmt"
)
var _ Decryptor = &rc4Writer{}
func (d *rc4Writer) Write(data []byte) (n int, err error) {
x := len(data)
for len(data) > 0 {
n := copy(d.bytes[d.offset:], data)
d.offset += n
if d.offset >= 1024 {
if d.offset != 1024 {
panic("invalid offset from write")
}
d.Flush()
}
data = data[n:]
}
return x, nil
}
func (d *rc4Writer) Read(data []byte) (n int, err error) {
return d.buf.Read(data)
}
// Reset to block 0, and clear all written and readable data.
func (d *rc4Writer) Reset() {
d.block = 0
d.offset = 0
d.buf.Reset()
}
// Flush tells the decryptor to decrypt the latest block.
func (d *rc4Writer) Flush() {
var zeros [1024]byte
endpad := 0
if d.offset < 1024 {
endpad = copy(d.bytes[d.offset:], zeros[:])
d.offset += endpad
}
if d.offset != 1024 {
panic("invalid offset fill")
}
// decrypt and write results to output buffer
d.startBlock()
d.dec.XORKeyStream(d.bytes[:], d.bytes[:])
d.buf.Write(d.bytes[:1024-endpad])
d.offset = 0
d.block++
}
// SetPassword for the decryption.
func (d *rc4Writer) SetPassword(password []byte) {
d.Password = make([]rune, len(password))
for i, p := range password {
d.Password[i] = rune(p)
}
/// compute the first part of the encryption key
result := generateStd97Key(d.Password, d.Salt)
d.encKey = make([]byte, len(result))
copy(d.encKey, result)
}
type rc4Writer struct {
block uint32
offset int
bytes [1024]byte
// records the decrypted data
buf bytes.Buffer
///////
// decrypter for RC4 content streams
dec *rc4.Cipher
cipherKey []byte // H1 per 2.3.6.2
encKey []byte // Hfinal per 2.3.6.2
Salt []byte
Password []rune
}
func (d *rc4Writer) Bytes() []byte {
return d.buf.Bytes()
}
func (d *rc4Writer) Verify(everifier, everifierHash []byte) error {
d.Reset()
d.startBlock()
var temp1 [16]byte
var temp2 [16]byte
d.dec.XORKeyStream(temp1[:], everifier)
d.dec.XORKeyStream(temp2[:], everifierHash)
newhash := md5.Sum(temp1[:])
for i, c := range newhash {
if temp2[i] != c {
return fmt.Errorf("verification failed")
}
}
return nil
}
/////////////////////
func (d *rc4Writer) startBlock() {
if d.encKey == nil {
d.SetPassword([]byte(DefaultXLSPassword))
}
d.cipherKey = make([]byte, 16)
copy(d.cipherKey, d.encKey[:5])
binary.LittleEndian.PutUint32(d.cipherKey[5:], d.block)
mhash := md5.Sum(d.cipherKey[:9])
d.dec, _ = rc4.NewCipher(mhash[:])
}
func generateStd97Key(passData []rune, salt []byte) []byte {
if len(passData) == 0 || len(salt) != 16 {
panic("invalid keygen material")
}
passBytes := make([]byte, len(passData)*2)
for i, c := range passData {
binary.LittleEndian.PutUint16(passBytes[2*i:], uint16(c))
}
// digest the IV then copy back into pKeyData
h0 := md5.Sum(passBytes)
// now do the final set of keygen ops
msum := md5.New()
for i := 0; i < 16; i++ {
msum.Write(h0[:5])
msum.Write(salt)
}
// return H1
temp := make([]byte, 0, 16)
temp = msum.Sum(temp)
return temp
}