crypt.go 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  1. // Copyright 2016 - 2023 The excelize Authors. All rights reserved. Use of
  2. // this source code is governed by a BSD-style license that can be found in
  3. // the LICENSE file.
  4. //
  5. // Package excelize providing a set of functions that allow you to write to and
  6. // read from XLAM / XLSM / XLSX / XLTM / XLTX files. Supports reading and
  7. // writing spreadsheet documents generated by Microsoft Excel™ 2007 and later.
  8. // Supports complex components by high compatibility, and provided streaming
  9. // API for generating or reading data from a worksheet with huge amounts of
  10. // data. This library needs Go version 1.16 or later.
  11. package excelize
  12. import (
  13. "bytes"
  14. "crypto/aes"
  15. "crypto/cipher"
  16. "crypto/md5"
  17. "crypto/rand"
  18. "crypto/sha1"
  19. "crypto/sha256"
  20. "crypto/sha512"
  21. "encoding/base64"
  22. "encoding/binary"
  23. "encoding/xml"
  24. "hash"
  25. "math"
  26. "path/filepath"
  27. "reflect"
  28. "sort"
  29. "strings"
  30. "github.com/richardlehane/mscfb"
  31. "golang.org/x/crypto/md4"
  32. "golang.org/x/crypto/ripemd160"
  33. "golang.org/x/text/encoding/unicode"
  34. )
  35. var (
  36. blockKey = []byte{0x14, 0x6e, 0x0b, 0xe7, 0xab, 0xac, 0xd0, 0xd6} // Block keys used for encryption
  37. oleIdentifier = []byte{0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1}
  38. headerCLSID = make([]byte, 16)
  39. difSect = -4
  40. endOfChain = -2
  41. fatSect = -3
  42. iterCount = 50000
  43. packageEncryptionChunkSize = 4096
  44. packageOffset = 8 // First 8 bytes are the size of the stream
  45. sheetProtectionSpinCount = 1e5
  46. workbookProtectionSpinCount = 1e5
  47. )
  48. // Encryption specifies the encryption structure, streams, and storages are
  49. // required when encrypting ECMA-376 documents.
  50. type Encryption struct {
  51. XMLName xml.Name `xml:"encryption"`
  52. KeyData KeyData `xml:"keyData"`
  53. DataIntegrity DataIntegrity `xml:"dataIntegrity"`
  54. KeyEncryptors KeyEncryptors `xml:"keyEncryptors"`
  55. }
  56. // KeyData specifies the cryptographic attributes used to encrypt the data.
  57. type KeyData struct {
  58. SaltSize int `xml:"saltSize,attr"`
  59. BlockSize int `xml:"blockSize,attr"`
  60. KeyBits int `xml:"keyBits,attr"`
  61. HashSize int `xml:"hashSize,attr"`
  62. CipherAlgorithm string `xml:"cipherAlgorithm,attr"`
  63. CipherChaining string `xml:"cipherChaining,attr"`
  64. HashAlgorithm string `xml:"hashAlgorithm,attr"`
  65. SaltValue string `xml:"saltValue,attr"`
  66. }
  67. // DataIntegrity specifies the encrypted copies of the salt and hash values
  68. // used to help ensure that the integrity of the encrypted data has not been
  69. // compromised.
  70. type DataIntegrity struct {
  71. EncryptedHmacKey string `xml:"encryptedHmacKey,attr"`
  72. EncryptedHmacValue string `xml:"encryptedHmacValue,attr"`
  73. }
  74. // KeyEncryptors specifies the key encryptors used to encrypt the data.
  75. type KeyEncryptors struct {
  76. KeyEncryptor []KeyEncryptor `xml:"keyEncryptor"`
  77. }
  78. // KeyEncryptor specifies that the schema used by this encryptor is the schema
  79. // specified for password-based encryptors.
  80. type KeyEncryptor struct {
  81. XMLName xml.Name `xml:"keyEncryptor"`
  82. URI string `xml:"uri,attr"`
  83. EncryptedKey EncryptedKey `xml:"encryptedKey"`
  84. }
  85. // EncryptedKey used to generate the encrypting key.
  86. type EncryptedKey struct {
  87. XMLName xml.Name `xml:"http://schemas.microsoft.com/office/2006/keyEncryptor/password encryptedKey"`
  88. SpinCount int `xml:"spinCount,attr"`
  89. EncryptedVerifierHashInput string `xml:"encryptedVerifierHashInput,attr"`
  90. EncryptedVerifierHashValue string `xml:"encryptedVerifierHashValue,attr"`
  91. EncryptedKeyValue string `xml:"encryptedKeyValue,attr"`
  92. KeyData
  93. }
  94. // StandardEncryptionHeader structure is used by ECMA-376 document encryption
  95. // [ECMA-376] and Office binary document RC4 CryptoAPI encryption, to specify
  96. // encryption properties for an encrypted stream.
  97. type StandardEncryptionHeader struct {
  98. Flags uint32
  99. SizeExtra uint32
  100. AlgID uint32
  101. AlgIDHash uint32
  102. KeySize uint32
  103. ProviderType uint32
  104. Reserved1 uint32
  105. Reserved2 uint32
  106. CspName string
  107. }
  108. // StandardEncryptionVerifier structure is used by Office Binary Document RC4
  109. // CryptoAPI Encryption and ECMA-376 Document Encryption. Every usage of this
  110. // structure MUST specify the hashing algorithm and encryption algorithm used
  111. // in the EncryptionVerifier structure.
  112. type StandardEncryptionVerifier struct {
  113. SaltSize uint32
  114. Salt []byte
  115. EncryptedVerifier []byte
  116. VerifierHashSize uint32
  117. EncryptedVerifierHash []byte
  118. }
  119. // encryptionInfo structure is used for standard encryption with SHA1
  120. // cryptographic algorithm.
  121. type encryption struct {
  122. BlockSize, SaltSize int
  123. EncryptedKeyValue, EncryptedVerifierHashInput, EncryptedVerifierHashValue, SaltValue []byte
  124. KeyBits uint32
  125. }
  126. // Decrypt API decrypts the CFB file format with ECMA-376 agile encryption and
  127. // standard encryption. Support cryptographic algorithm: MD4, MD5, RIPEMD-160,
  128. // SHA1, SHA256, SHA384 and SHA512 currently.
  129. func Decrypt(raw []byte, opts *Options) (packageBuf []byte, err error) {
  130. doc, err := mscfb.New(bytes.NewReader(raw))
  131. if err != nil {
  132. return
  133. }
  134. encryptionInfoBuf, encryptedPackageBuf := extractPart(doc)
  135. mechanism, err := encryptionMechanism(encryptionInfoBuf)
  136. if err != nil || mechanism == "extensible" {
  137. return
  138. }
  139. if mechanism == "agile" {
  140. return agileDecrypt(encryptionInfoBuf, encryptedPackageBuf, opts)
  141. }
  142. return standardDecrypt(encryptionInfoBuf, encryptedPackageBuf, opts)
  143. }
  144. // Encrypt API encrypt data with the password.
  145. func Encrypt(raw []byte, opts *Options) ([]byte, error) {
  146. encryptor := encryption{
  147. EncryptedVerifierHashInput: make([]byte, 16),
  148. EncryptedVerifierHashValue: make([]byte, 32),
  149. SaltValue: make([]byte, 16),
  150. BlockSize: 16,
  151. KeyBits: 128,
  152. SaltSize: 16,
  153. }
  154. // Key Encryption
  155. encryptionInfoBuffer, err := encryptor.standardKeyEncryption(opts.Password)
  156. if err != nil {
  157. return nil, err
  158. }
  159. // Package Encryption
  160. encryptedPackage := make([]byte, 8)
  161. binary.LittleEndian.PutUint64(encryptedPackage, uint64(len(raw)))
  162. encryptedPackage = append(encryptedPackage, encryptor.encrypt(raw)...)
  163. // Create a new CFB
  164. compoundFile := &cfb{
  165. paths: []string{"Root Entry/"},
  166. sectors: []sector{{name: "Root Entry", typeID: 5}},
  167. }
  168. compoundFile.put("EncryptionInfo", encryptionInfoBuffer)
  169. compoundFile.put("EncryptedPackage", encryptedPackage)
  170. return compoundFile.write(), nil
  171. }
  172. // extractPart extract data from storage by specified part name.
  173. func extractPart(doc *mscfb.Reader) (encryptionInfoBuf, encryptedPackageBuf []byte) {
  174. for entry, err := doc.Next(); err == nil; entry, err = doc.Next() {
  175. switch entry.Name {
  176. case "EncryptionInfo":
  177. buf := make([]byte, entry.Size)
  178. i, _ := doc.Read(buf)
  179. if i > 0 {
  180. encryptionInfoBuf = buf
  181. }
  182. case "EncryptedPackage":
  183. buf := make([]byte, entry.Size)
  184. i, _ := doc.Read(buf)
  185. if i > 0 {
  186. encryptedPackageBuf = buf
  187. }
  188. }
  189. }
  190. return
  191. }
  192. // encryptionMechanism parse password-protected documents created mechanism.
  193. func encryptionMechanism(buffer []byte) (mechanism string, err error) {
  194. if len(buffer) < 4 {
  195. err = ErrUnknownEncryptMechanism
  196. return
  197. }
  198. versionMajor, versionMinor := binary.LittleEndian.Uint16(buffer[:2]), binary.LittleEndian.Uint16(buffer[2:4])
  199. if versionMajor == 4 && versionMinor == 4 {
  200. mechanism = "agile"
  201. return
  202. } else if (2 <= versionMajor && versionMajor <= 4) && versionMinor == 2 {
  203. mechanism = "standard"
  204. return
  205. } else if (versionMajor == 3 || versionMajor == 4) && versionMinor == 3 {
  206. mechanism = "extensible"
  207. }
  208. err = ErrUnsupportedEncryptMechanism
  209. return
  210. }
  211. // ECMA-376 Standard Encryption
  212. // standardDecrypt decrypt the CFB file format with ECMA-376 standard encryption.
  213. func standardDecrypt(encryptionInfoBuf, encryptedPackageBuf []byte, opts *Options) ([]byte, error) {
  214. encryptionHeaderSize := binary.LittleEndian.Uint32(encryptionInfoBuf[8:12])
  215. block := encryptionInfoBuf[12 : 12+encryptionHeaderSize]
  216. header := StandardEncryptionHeader{
  217. Flags: binary.LittleEndian.Uint32(block[:4]),
  218. SizeExtra: binary.LittleEndian.Uint32(block[4:8]),
  219. AlgID: binary.LittleEndian.Uint32(block[8:12]),
  220. AlgIDHash: binary.LittleEndian.Uint32(block[12:16]),
  221. KeySize: binary.LittleEndian.Uint32(block[16:20]),
  222. ProviderType: binary.LittleEndian.Uint32(block[20:24]),
  223. Reserved1: binary.LittleEndian.Uint32(block[24:28]),
  224. Reserved2: binary.LittleEndian.Uint32(block[28:32]),
  225. CspName: string(block[32:]),
  226. }
  227. block = encryptionInfoBuf[12+encryptionHeaderSize:]
  228. algIDMap := map[uint32]string{
  229. 0x0000660E: "AES-128",
  230. 0x0000660F: "AES-192",
  231. 0x00006610: "AES-256",
  232. }
  233. algorithm := "AES"
  234. _, ok := algIDMap[header.AlgID]
  235. if !ok {
  236. algorithm = "RC4"
  237. }
  238. verifier := standardEncryptionVerifier(algorithm, block)
  239. secretKey, err := standardConvertPasswdToKey(header, verifier, opts)
  240. if err != nil {
  241. return nil, err
  242. }
  243. // decrypted data
  244. x := encryptedPackageBuf[8:]
  245. blob, err := aes.NewCipher(secretKey)
  246. if err != nil {
  247. return nil, err
  248. }
  249. decrypted := make([]byte, len(x))
  250. size := 16
  251. for bs, be := 0, size; bs < len(x); bs, be = bs+size, be+size {
  252. blob.Decrypt(decrypted[bs:be], x[bs:be])
  253. }
  254. return decrypted, err
  255. }
  256. // standardEncryptionVerifier extract ECMA-376 standard encryption verifier.
  257. func standardEncryptionVerifier(algorithm string, blob []byte) StandardEncryptionVerifier {
  258. verifier := StandardEncryptionVerifier{
  259. SaltSize: binary.LittleEndian.Uint32(blob[:4]),
  260. Salt: blob[4:20],
  261. EncryptedVerifier: blob[20:36],
  262. VerifierHashSize: binary.LittleEndian.Uint32(blob[36:40]),
  263. }
  264. if algorithm == "RC4" {
  265. verifier.EncryptedVerifierHash = blob[40:60]
  266. } else if algorithm == "AES" {
  267. verifier.EncryptedVerifierHash = blob[40:72]
  268. }
  269. return verifier
  270. }
  271. // standardConvertPasswdToKey generate intermediate key from given password.
  272. func standardConvertPasswdToKey(header StandardEncryptionHeader, verifier StandardEncryptionVerifier, opts *Options) ([]byte, error) {
  273. encoder := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM).NewEncoder()
  274. passwordBuffer, err := encoder.Bytes([]byte(opts.Password))
  275. if err != nil {
  276. return nil, err
  277. }
  278. key := hashing("sha1", verifier.Salt, passwordBuffer)
  279. for i := 0; i < iterCount; i++ {
  280. iterator := createUInt32LEBuffer(i, 4)
  281. key = hashing("sha1", iterator, key)
  282. }
  283. var block int
  284. hFinal := hashing("sha1", key, createUInt32LEBuffer(block, 4))
  285. cbRequiredKeyLength := int(header.KeySize) / 8
  286. cbHash := sha1.Size
  287. buf1 := bytes.Repeat([]byte{0x36}, 64)
  288. buf1 = append(standardXORBytes(hFinal, buf1[:cbHash]), buf1[cbHash:]...)
  289. x1 := hashing("sha1", buf1)
  290. buf2 := bytes.Repeat([]byte{0x5c}, 64)
  291. buf2 = append(standardXORBytes(hFinal, buf2[:cbHash]), buf2[cbHash:]...)
  292. x2 := hashing("sha1", buf2)
  293. x3 := append(x1, x2...)
  294. keyDerived := x3[:cbRequiredKeyLength]
  295. return keyDerived, err
  296. }
  297. // standardXORBytes perform XOR operations for two bytes slice.
  298. func standardXORBytes(a, b []byte) []byte {
  299. r := make([][2]byte, len(a))
  300. for i, e := range a {
  301. r[i] = [2]byte{e, b[i]}
  302. }
  303. buf := make([]byte, len(a))
  304. for p, q := range r {
  305. buf[p] = q[0] ^ q[1]
  306. }
  307. return buf
  308. }
  309. // encrypt provides a function to encrypt given value with AES cryptographic
  310. // algorithm.
  311. func (e *encryption) encrypt(input []byte) []byte {
  312. inputBytes := len(input)
  313. if pad := inputBytes % e.BlockSize; pad != 0 {
  314. inputBytes += e.BlockSize - pad
  315. }
  316. var output, chunk []byte
  317. encryptedChunk := make([]byte, e.BlockSize)
  318. for i := 0; i < inputBytes; i += e.BlockSize {
  319. if i+e.BlockSize <= len(input) {
  320. chunk = input[i : i+e.BlockSize]
  321. } else {
  322. chunk = input[i:]
  323. }
  324. chunk = append(chunk, make([]byte, e.BlockSize-len(chunk))...)
  325. c, _ := aes.NewCipher(e.EncryptedKeyValue)
  326. c.Encrypt(encryptedChunk, chunk)
  327. output = append(output, encryptedChunk...)
  328. }
  329. return output
  330. }
  331. // standardKeyEncryption encrypt convert the password to an encryption key.
  332. func (e *encryption) standardKeyEncryption(password string) ([]byte, error) {
  333. if len(password) == 0 || len(password) > MaxFieldLength {
  334. return nil, ErrPasswordLengthInvalid
  335. }
  336. var storage cfb
  337. storage.writeUint16(0x0003)
  338. storage.writeUint16(0x0002)
  339. storage.writeUint32(0x24)
  340. storage.writeUint32(0xA4)
  341. storage.writeUint32(0x24)
  342. storage.writeUint32(0x00)
  343. storage.writeUint32(0x660E)
  344. storage.writeUint32(0x8004)
  345. storage.writeUint32(0x80)
  346. storage.writeUint32(0x18)
  347. storage.writeUint64(0x00)
  348. providerName := "Microsoft Enhanced RSA and AES Cryptographic Provider (Prototype)"
  349. storage.writeStrings(providerName)
  350. storage.writeUint16(0x00)
  351. storage.writeUint32(0x10)
  352. keyDataSaltValue, _ := randomBytes(16)
  353. verifierHashInput, _ := randomBytes(16)
  354. e.SaltValue = keyDataSaltValue
  355. e.EncryptedKeyValue, _ = standardConvertPasswdToKey(
  356. StandardEncryptionHeader{KeySize: e.KeyBits},
  357. StandardEncryptionVerifier{Salt: e.SaltValue},
  358. &Options{Password: password})
  359. verifierHashInputKey := hashing("sha1", verifierHashInput)
  360. e.EncryptedVerifierHashInput = e.encrypt(verifierHashInput)
  361. e.EncryptedVerifierHashValue = e.encrypt(verifierHashInputKey)
  362. storage.writeBytes(e.SaltValue)
  363. storage.writeBytes(e.EncryptedVerifierHashInput)
  364. storage.writeUint32(0x14)
  365. storage.writeBytes(e.EncryptedVerifierHashValue)
  366. storage.position = 0
  367. return storage.stream, nil
  368. }
  369. // ECMA-376 Agile Encryption
  370. // agileDecrypt decrypt the CFB file format with ECMA-376 agile encryption.
  371. // Support cryptographic algorithm: MD4, MD5, RIPEMD-160, SHA1, SHA256,
  372. // SHA384 and SHA512.
  373. func agileDecrypt(encryptionInfoBuf, encryptedPackageBuf []byte, opts *Options) (packageBuf []byte, err error) {
  374. var encryptionInfo Encryption
  375. if encryptionInfo, err = parseEncryptionInfo(encryptionInfoBuf[8:]); err != nil {
  376. return
  377. }
  378. // Convert the password into an encryption key.
  379. key, err := convertPasswdToKey(opts.Password, blockKey, encryptionInfo)
  380. if err != nil {
  381. return
  382. }
  383. // Use the key to decrypt the package key.
  384. encryptedKey := encryptionInfo.KeyEncryptors.KeyEncryptor[0].EncryptedKey
  385. saltValue, err := base64.StdEncoding.DecodeString(encryptedKey.SaltValue)
  386. if err != nil {
  387. return
  388. }
  389. encryptedKeyValue, err := base64.StdEncoding.DecodeString(encryptedKey.EncryptedKeyValue)
  390. if err != nil {
  391. return
  392. }
  393. packageKey, _ := decrypt(key, saltValue, encryptedKeyValue)
  394. // Use the package key to decrypt the package.
  395. return decryptPackage(packageKey, encryptedPackageBuf, encryptionInfo)
  396. }
  397. // convertPasswdToKey convert the password into an encryption key.
  398. func convertPasswdToKey(passwd string, blockKey []byte, encryption Encryption) (key []byte, err error) {
  399. var b bytes.Buffer
  400. saltValue, err := base64.StdEncoding.DecodeString(encryption.KeyEncryptors.KeyEncryptor[0].EncryptedKey.SaltValue)
  401. if err != nil {
  402. return
  403. }
  404. b.Write(saltValue)
  405. encoder := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM).NewEncoder()
  406. passwordBuffer, err := encoder.Bytes([]byte(passwd))
  407. if err != nil {
  408. return
  409. }
  410. b.Write(passwordBuffer)
  411. // Generate the initial hash.
  412. key = hashing(encryption.KeyData.HashAlgorithm, b.Bytes())
  413. // Now regenerate until spin count.
  414. for i := 0; i < encryption.KeyEncryptors.KeyEncryptor[0].EncryptedKey.SpinCount; i++ {
  415. iterator := createUInt32LEBuffer(i, 4)
  416. key = hashing(encryption.KeyData.HashAlgorithm, iterator, key)
  417. }
  418. // Now generate the final hash.
  419. key = hashing(encryption.KeyData.HashAlgorithm, key, blockKey)
  420. // Truncate or pad as needed to get to length of keyBits.
  421. keyBytes := encryption.KeyEncryptors.KeyEncryptor[0].EncryptedKey.KeyBits / 8
  422. if len(key) < keyBytes {
  423. tmp := make([]byte, 0x36)
  424. key = append(key, tmp...)
  425. } else if len(key) > keyBytes {
  426. key = key[:keyBytes]
  427. }
  428. return
  429. }
  430. // hashing data by specified hash algorithm.
  431. func hashing(hashAlgorithm string, buffer ...[]byte) (key []byte) {
  432. hashMap := map[string]hash.Hash{
  433. "md4": md4.New(),
  434. "md5": md5.New(),
  435. "ripemd-160": ripemd160.New(),
  436. "sha1": sha1.New(),
  437. "sha256": sha256.New(),
  438. "sha384": sha512.New384(),
  439. "sha512": sha512.New(),
  440. }
  441. handler, ok := hashMap[strings.ToLower(hashAlgorithm)]
  442. if !ok {
  443. return key
  444. }
  445. for _, buf := range buffer {
  446. _, _ = handler.Write(buf)
  447. }
  448. key = handler.Sum(nil)
  449. return key
  450. }
  451. // createUInt32LEBuffer create buffer with little endian 32-bit unsigned
  452. // integer.
  453. func createUInt32LEBuffer(value int, bufferSize int) []byte {
  454. buf := make([]byte, bufferSize)
  455. binary.LittleEndian.PutUint32(buf, uint32(value))
  456. return buf
  457. }
  458. // parseEncryptionInfo parse the encryption info XML into an object.
  459. func parseEncryptionInfo(encryptionInfo []byte) (encryption Encryption, err error) {
  460. err = xml.Unmarshal(encryptionInfo, &encryption)
  461. return
  462. }
  463. // decrypt provides a function to decrypt input by given cipher algorithm,
  464. // cipher chaining, key and initialization vector.
  465. func decrypt(key, iv, input []byte) (packageKey []byte, err error) {
  466. block, err := aes.NewCipher(key)
  467. if err != nil {
  468. return input, err
  469. }
  470. cipher.NewCBCDecrypter(block, iv).CryptBlocks(input, input)
  471. return input, nil
  472. }
  473. // decryptPackage decrypt package by given packageKey and encryption
  474. // info.
  475. func decryptPackage(packageKey, input []byte, encryption Encryption) (outputChunks []byte, err error) {
  476. encryptedKey, offset := encryption.KeyData, packageOffset
  477. var i, start, end int
  478. var iv, outputChunk []byte
  479. for end < len(input) {
  480. start = end
  481. end = start + packageEncryptionChunkSize
  482. if end > len(input) {
  483. end = len(input)
  484. }
  485. // Grab the next chunk
  486. var inputChunk []byte
  487. if (end + offset) < len(input) {
  488. inputChunk = input[start+offset : end+offset]
  489. } else {
  490. inputChunk = input[start+offset : end]
  491. }
  492. // Pad the chunk if it is not an integer multiple of the block size
  493. remainder := len(inputChunk) % encryptedKey.BlockSize
  494. if remainder != 0 {
  495. inputChunk = append(inputChunk, make([]byte, encryptedKey.BlockSize-remainder)...)
  496. }
  497. // Create the initialization vector
  498. iv, err = createIV(i, encryption)
  499. if err != nil {
  500. return
  501. }
  502. // Decrypt the chunk and add it to the array
  503. outputChunk, err = decrypt(packageKey, iv, inputChunk)
  504. if err != nil {
  505. return
  506. }
  507. outputChunks = append(outputChunks, outputChunk...)
  508. i++
  509. }
  510. return
  511. }
  512. // createIV create an initialization vector (IV).
  513. func createIV(blockKey interface{}, encryption Encryption) ([]byte, error) {
  514. encryptedKey := encryption.KeyData
  515. // Create the block key from the current index
  516. var blockKeyBuf []byte
  517. if reflect.TypeOf(blockKey).Kind() == reflect.Int {
  518. blockKeyBuf = createUInt32LEBuffer(blockKey.(int), 4)
  519. } else {
  520. blockKeyBuf = blockKey.([]byte)
  521. }
  522. saltValue, err := base64.StdEncoding.DecodeString(encryptedKey.SaltValue)
  523. if err != nil {
  524. return nil, err
  525. }
  526. // Create the initialization vector by hashing the salt with the block key.
  527. // Truncate or pad as needed to meet the block size.
  528. iv := hashing(encryptedKey.HashAlgorithm, append(saltValue, blockKeyBuf...))
  529. if len(iv) < encryptedKey.BlockSize {
  530. tmp := make([]byte, 0x36)
  531. iv = append(iv, tmp...)
  532. } else if len(iv) > encryptedKey.BlockSize {
  533. iv = iv[:encryptedKey.BlockSize]
  534. }
  535. return iv, nil
  536. }
  537. // randomBytes returns securely generated random bytes. It will return an
  538. // error if the system's secure random number generator fails to function
  539. // correctly, in which case the caller should not continue.
  540. func randomBytes(n int) ([]byte, error) {
  541. b := make([]byte, n)
  542. _, err := rand.Read(b)
  543. return b, err
  544. }
  545. // ISO Write Protection Method
  546. // genISOPasswdHash implements the ISO password hashing algorithm by given
  547. // plaintext password, name of the cryptographic hash algorithm, salt value
  548. // and spin count.
  549. func genISOPasswdHash(passwd, hashAlgorithm, salt string, spinCount int) (hashValue, saltValue string, err error) {
  550. if len(passwd) < 1 || len(passwd) > MaxFieldLength {
  551. err = ErrPasswordLengthInvalid
  552. return
  553. }
  554. algorithmName, ok := map[string]string{
  555. "MD4": "md4",
  556. "MD5": "md5",
  557. "SHA-1": "sha1",
  558. "SHA-256": "sha256",
  559. "SHA-384": "sha384",
  560. "SHA-512": "sha512",
  561. }[hashAlgorithm]
  562. if !ok {
  563. err = ErrUnsupportedHashAlgorithm
  564. return
  565. }
  566. var b bytes.Buffer
  567. s, _ := randomBytes(16)
  568. if salt != "" {
  569. if s, err = base64.StdEncoding.DecodeString(salt); err != nil {
  570. return
  571. }
  572. }
  573. b.Write(s)
  574. encoder := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM).NewEncoder()
  575. passwordBuffer, _ := encoder.Bytes([]byte(passwd))
  576. b.Write(passwordBuffer)
  577. // Generate the initial hash.
  578. key := hashing(algorithmName, b.Bytes())
  579. // Now regenerate until spin count.
  580. for i := 0; i < spinCount; i++ {
  581. iterator := createUInt32LEBuffer(i, 4)
  582. key = hashing(algorithmName, key, iterator)
  583. }
  584. hashValue, saltValue = base64.StdEncoding.EncodeToString(key), base64.StdEncoding.EncodeToString(s)
  585. return
  586. }
  587. // Compound File Binary Implements
  588. // cfb structure is used for the compound file binary (CFB) file format writer.
  589. type cfb struct {
  590. stream []byte
  591. position int
  592. paths []string
  593. sectors []sector
  594. }
  595. // sector structure used for FAT, directory, miniFAT, and miniStream sectors.
  596. type sector struct {
  597. clsID, content []byte
  598. name string
  599. C, L, R, color, size, start, state, typeID int
  600. }
  601. // writeBytes write bytes in the stream by a given value with an offset.
  602. func (c *cfb) writeBytes(value []byte) {
  603. pos := c.position
  604. for i := 0; i < len(value); i++ {
  605. for j := len(c.stream); j <= i+pos; j++ {
  606. c.stream = append(c.stream, 0)
  607. }
  608. c.stream[i+pos] = value[i]
  609. }
  610. c.position = pos + len(value)
  611. }
  612. // writeUint16 write an uint16 data type bytes in the stream by a given value
  613. // with an offset.
  614. func (c *cfb) writeUint16(value int) {
  615. buf := make([]byte, 2)
  616. binary.LittleEndian.PutUint16(buf, uint16(value))
  617. c.writeBytes(buf)
  618. }
  619. // writeUint32 write an uint32 data type bytes in the stream by a given value
  620. // with an offset.
  621. func (c *cfb) writeUint32(value int) {
  622. buf := make([]byte, 4)
  623. binary.LittleEndian.PutUint32(buf, uint32(value))
  624. c.writeBytes(buf)
  625. }
  626. // writeUint64 write an uint64 data type bytes in the stream by a given value
  627. // with an offset.
  628. func (c *cfb) writeUint64(value int) {
  629. buf := make([]byte, 8)
  630. binary.LittleEndian.PutUint64(buf, uint64(value))
  631. c.writeBytes(buf)
  632. }
  633. // writeBytes write strings in the stream by a given value with an offset.
  634. func (c *cfb) writeStrings(value string) {
  635. encoder := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM).NewEncoder()
  636. buffer, err := encoder.Bytes([]byte(value))
  637. if err != nil {
  638. return
  639. }
  640. c.writeBytes(buffer)
  641. }
  642. // put provides a function to add an entry to compound file by given entry name
  643. // and raw bytes.
  644. func (c *cfb) put(name string, content []byte) {
  645. path := c.paths[0]
  646. if len(path) <= len(name) && name[:len(path)] == path {
  647. path = name
  648. } else {
  649. if len(path) > 0 && string(path[len(path)-1]) != "/" {
  650. path += "/"
  651. }
  652. path = strings.ReplaceAll(path+name, "//", "/")
  653. }
  654. file := sector{name: path, typeID: 2, content: content, size: len(content)}
  655. c.sectors = append(c.sectors, file)
  656. c.paths = append(c.paths, path)
  657. }
  658. // compare provides a function to compare object path, each set of sibling
  659. // objects in one level of the containment hierarchy (all child objects under
  660. // a storage object) is represented as a red-black tree. The parent object of
  661. // this set of siblings will have a pointer to the top of this tree.
  662. func (c *cfb) compare(left, right string) int {
  663. L, R, i, j := strings.Split(left, "/"), strings.Split(right, "/"), 0, 0
  664. for Z := int(math.Min(float64(len(L)), float64(len(R)))); i < Z; i++ {
  665. if j = len(L[i]) - len(R[i]); j != 0 {
  666. return j
  667. }
  668. if L[i] != R[i] {
  669. if L[i] < R[i] {
  670. return -1
  671. }
  672. return 1
  673. }
  674. }
  675. return len(L) - len(R)
  676. }
  677. // prepare provides a function to prepare object before write stream.
  678. func (c *cfb) prepare() {
  679. type object struct {
  680. path string
  681. sector sector
  682. }
  683. var objects []object
  684. for i := 0; i < len(c.paths); i++ {
  685. if c.sectors[i].typeID == 0 {
  686. continue
  687. }
  688. objects = append(objects, object{path: c.paths[i], sector: c.sectors[i]})
  689. }
  690. sort.Slice(objects, func(i, j int) bool {
  691. return c.compare(objects[i].path, objects[j].path) == 0
  692. })
  693. c.paths, c.sectors = []string{}, []sector{}
  694. for i := 0; i < len(objects); i++ {
  695. c.paths = append(c.paths, objects[i].path)
  696. c.sectors = append(c.sectors, objects[i].sector)
  697. }
  698. for i := 0; i < len(objects); i++ {
  699. sector, path := &c.sectors[i], c.paths[i]
  700. sector.name, sector.color = filepath.Base(path), 1
  701. sector.L, sector.R, sector.C = -1, -1, -1
  702. sector.size, sector.start = len(sector.content), 0
  703. if len(sector.clsID) == 0 {
  704. sector.clsID = headerCLSID
  705. }
  706. if i == 0 {
  707. sector.C = -1
  708. if len(objects) > 1 {
  709. sector.C = 1
  710. }
  711. sector.size, sector.typeID = 0, 5
  712. } else {
  713. if len(c.paths) > i+1 && filepath.Dir(c.paths[i+1]) == filepath.Dir(path) {
  714. sector.R = i + 1
  715. }
  716. sector.typeID = 2
  717. }
  718. }
  719. }
  720. // locate provides a function to locate sectors location and size of the
  721. // compound file.
  722. func (c *cfb) locate() []int {
  723. var miniStreamSectorSize, FATSectorSize int
  724. for i := 0; i < len(c.sectors); i++ {
  725. sector := c.sectors[i]
  726. if len(sector.content) == 0 {
  727. continue
  728. }
  729. size := len(sector.content)
  730. if size > 0 {
  731. if size < 0x1000 {
  732. miniStreamSectorSize += (size + 0x3F) >> 6
  733. } else {
  734. FATSectorSize += (size + 0x01FF) >> 9
  735. }
  736. }
  737. }
  738. directorySectors := (len(c.paths) + 3) >> 2
  739. miniStreamSectors := (miniStreamSectorSize + 7) >> 3
  740. miniFATSectors := (miniStreamSectorSize + 0x7F) >> 7
  741. sectors := miniStreamSectors + FATSectorSize + directorySectors + miniFATSectors
  742. FATSectors := (sectors + 0x7F) >> 7
  743. DIFATSectors := 0
  744. if FATSectors > 109 {
  745. DIFATSectors = int(math.Ceil((float64(FATSectors) - 109) / 0x7F))
  746. }
  747. for ((sectors + FATSectors + DIFATSectors + 0x7F) >> 7) > FATSectors {
  748. FATSectors++
  749. if FATSectors <= 109 {
  750. DIFATSectors = 0
  751. } else {
  752. DIFATSectors = int(math.Ceil((float64(FATSectors) - 109) / 0x7F))
  753. }
  754. }
  755. location := []int{1, DIFATSectors, FATSectors, miniFATSectors, directorySectors, FATSectorSize, miniStreamSectorSize, 0}
  756. c.sectors[0].size = miniStreamSectorSize << 6
  757. c.sectors[0].start = location[0] + location[1] + location[2] + location[3] + location[4] + location[5]
  758. location[7] = c.sectors[0].start + ((location[6] + 7) >> 3)
  759. return location
  760. }
  761. // writeMSAT provides a function to write compound file master sector allocation
  762. // table.
  763. func (c *cfb) writeMSAT(location []int) {
  764. var i, offset int
  765. for i = 0; i < 109; i++ {
  766. if i < location[2] {
  767. c.writeUint32(location[1] + i)
  768. } else {
  769. c.writeUint32(-1)
  770. }
  771. }
  772. if location[1] != 0 {
  773. for offset = 0; offset < location[1]; offset++ {
  774. for ; i < 236+offset*127; i++ {
  775. if i < location[2] {
  776. c.writeUint32(location[1] + i)
  777. } else {
  778. c.writeUint32(-1)
  779. }
  780. }
  781. if offset == location[1]-1 {
  782. c.writeUint32(endOfChain)
  783. } else {
  784. c.writeUint32(offset + 1)
  785. }
  786. }
  787. }
  788. }
  789. // writeDirectoryEntry provides a function to write compound file directory
  790. // entries. The directory entry array is an array of directory entries that
  791. // are grouped into a directory sector. Each storage object or stream object
  792. // within a compound file is represented by a single directory entry. The
  793. // space for the directory sectors that are holding the array is allocated
  794. // from the FAT.
  795. func (c *cfb) writeDirectoryEntry(location []int) {
  796. var sector sector
  797. var j, sectorSize int
  798. for i := 0; i < location[4]<<2; i++ {
  799. var path string
  800. if i < len(c.paths) {
  801. path = c.paths[i]
  802. }
  803. if i >= len(c.paths) || len(path) == 0 {
  804. for j = 0; j < 17; j++ {
  805. c.writeUint32(0)
  806. }
  807. for j = 0; j < 3; j++ {
  808. c.writeUint32(-1)
  809. }
  810. for j = 0; j < 12; j++ {
  811. c.writeUint32(0)
  812. }
  813. continue
  814. }
  815. sector = c.sectors[i]
  816. if i == 0 {
  817. if sector.size > 0 {
  818. sector.start = sector.start - 1
  819. } else {
  820. sector.start = endOfChain
  821. }
  822. }
  823. name := sector.name
  824. sectorSize = 2 * (len(name) + 1)
  825. c.writeStrings(name)
  826. c.position += 64 - 2*(len(name))
  827. c.writeUint16(sectorSize)
  828. c.writeBytes([]byte(string(rune(sector.typeID))))
  829. c.writeBytes([]byte(string(rune(sector.color))))
  830. c.writeUint32(sector.L)
  831. c.writeUint32(sector.R)
  832. c.writeUint32(sector.C)
  833. if len(sector.clsID) == 0 {
  834. for j = 0; j < 4; j++ {
  835. c.writeUint32(0)
  836. }
  837. } else {
  838. c.writeBytes(sector.clsID)
  839. }
  840. c.writeUint32(sector.state)
  841. c.writeUint32(0)
  842. c.writeUint32(0)
  843. c.writeUint32(0)
  844. c.writeUint32(0)
  845. c.writeUint32(sector.start)
  846. c.writeUint32(sector.size)
  847. c.writeUint32(0)
  848. }
  849. }
  850. // writeSectorChains provides a function to write compound file sector chains.
  851. func (c *cfb) writeSectorChains(location []int) sector {
  852. var i, j, offset, sectorSize int
  853. writeSectorChain := func(head, offset int) int {
  854. for offset += head; i < offset-1; i++ {
  855. c.writeUint32(i + 1)
  856. }
  857. if head != 0 {
  858. i++
  859. c.writeUint32(endOfChain)
  860. }
  861. return offset
  862. }
  863. for offset += location[1]; i < offset; i++ {
  864. c.writeUint32(difSect)
  865. }
  866. for offset += location[2]; i < offset; i++ {
  867. c.writeUint32(fatSect)
  868. }
  869. offset = writeSectorChain(location[3], offset)
  870. offset = writeSectorChain(location[4], offset)
  871. sector := c.sectors[0]
  872. for ; j < len(c.sectors); j++ {
  873. if sector = c.sectors[j]; len(sector.content) == 0 {
  874. continue
  875. }
  876. if sectorSize = len(sector.content); sectorSize < 0x1000 {
  877. continue
  878. }
  879. c.sectors[j].start = offset
  880. offset = writeSectorChain((sectorSize+0x01FF)>>9, offset)
  881. }
  882. writeSectorChain((location[6]+7)>>3, offset)
  883. for c.position&0x1FF != 0 {
  884. c.writeUint32(endOfChain)
  885. }
  886. i, offset = 0, 0
  887. for j = 0; j < len(c.sectors); j++ {
  888. if sector = c.sectors[j]; len(sector.content) == 0 {
  889. continue
  890. }
  891. if sectorSize = len(sector.content); sectorSize == 0 || sectorSize >= 0x1000 {
  892. continue
  893. }
  894. sector.start = offset
  895. offset = writeSectorChain((sectorSize+0x3F)>>6, offset)
  896. }
  897. for c.position&0x1FF != 0 {
  898. c.writeUint32(endOfChain)
  899. }
  900. return sector
  901. }
  902. // write provides a function to create compound file package stream.
  903. func (c *cfb) write() []byte {
  904. c.prepare()
  905. location := c.locate()
  906. c.stream = make([]byte, location[7]<<9)
  907. var i, j int
  908. for i = 0; i < 8; i++ {
  909. c.writeBytes([]byte{oleIdentifier[i]})
  910. }
  911. c.writeBytes(make([]byte, 16))
  912. c.writeUint16(0x003E)
  913. c.writeUint16(0x0003)
  914. c.writeUint16(0xFFFE)
  915. c.writeUint16(0x0009)
  916. c.writeUint16(0x0006)
  917. c.writeBytes(make([]byte, 10))
  918. c.writeUint32(location[2])
  919. c.writeUint32(location[0] + location[1] + location[2] + location[3] - 1)
  920. c.writeUint32(0)
  921. c.writeUint32(1 << 12)
  922. if location[3] != 0 {
  923. c.writeUint32(location[0] + location[1] + location[2] - 1)
  924. } else {
  925. c.writeUint32(endOfChain)
  926. }
  927. c.writeUint32(location[3])
  928. if location[1] != 0 {
  929. c.writeUint32(location[0] - 1)
  930. } else {
  931. c.writeUint32(endOfChain)
  932. }
  933. c.writeUint32(location[1])
  934. c.writeMSAT(location)
  935. sector := c.writeSectorChains(location)
  936. c.writeDirectoryEntry(location)
  937. for i = 1; i < len(c.sectors); i++ {
  938. sector = c.sectors[i]
  939. if sector.size >= 0x1000 {
  940. c.position = (sector.start + 1) << 9
  941. for j = 0; j < sector.size; j++ {
  942. c.writeBytes([]byte{sector.content[j]})
  943. }
  944. for ; j&0x1FF != 0; j++ {
  945. c.writeBytes([]byte{0})
  946. }
  947. }
  948. }
  949. for i = 1; i < len(c.sectors); i++ {
  950. sector = c.sectors[i]
  951. if sector.size > 0 && sector.size < 0x1000 {
  952. for j = 0; j < sector.size; j++ {
  953. c.writeBytes([]byte{sector.content[j]})
  954. }
  955. for ; j&0x3F != 0; j++ {
  956. c.writeBytes([]byte{0})
  957. }
  958. }
  959. }
  960. for c.position < len(c.stream) {
  961. c.writeBytes([]byte{0})
  962. }
  963. return c.stream
  964. }