ooxml_decrypt 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 84f71ccf2d737f1b14169099dfaae2d12bbc2ab527a97c44b84670d682b598be
4
+ data.tar.gz: 5ed8efac3dffe9e9b2863443c5cf8a2fdb0a58c27f3e1f0156eeab9305bb3f42
5
+ SHA512:
6
+ metadata.gz: 30fe6f7b9acbbaf6237cc34dd4d54730c88a695834f08196a8bcc0f15217c018a5efee7cf596efe2071dc0cd06957dc9262b32e0560e0fe1151800648aeb34d5
7
+ data.tar.gz: a9a54b23a57528592bd41cdcdee322787cf0d45b0a4fbcf46fd8986cc9adda371f3688d8fbc8b52715fb662af695c02d28b806b9efc3c1b357fe960b5d138ff1
data/.gitignore ADDED
@@ -0,0 +1,35 @@
1
+ *.gem
2
+ *.rbc
3
+ /.config
4
+ /coverage/
5
+ /InstalledFiles
6
+ /pkg/
7
+ /spec/reports/
8
+ /test/tmp/
9
+ /test/version_tmp/
10
+ /tmp/
11
+
12
+ ## Specific to RubyMotion:
13
+ .dat*
14
+ .repl_history
15
+ build/
16
+
17
+ ## Documentation cache and generated files:
18
+ /.yardoc/
19
+ /_yardoc/
20
+ /doc/
21
+ /rdoc/
22
+
23
+ ## Environment normalisation:
24
+ /.bundle/
25
+ /vendor/bundle
26
+ /lib/bundler/man/
27
+
28
+ # for a library or gem, you might want to ignore these files since the code is
29
+ # intended to run in multiple environments; otherwise, check them in:
30
+ Gemfile.lock
31
+ .ruby-version
32
+ .ruby-gemset
33
+
34
+ # unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
35
+ .rvmrc
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in ooxml_decrypt.gemspec
4
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
data/README.md ADDED
@@ -0,0 +1,25 @@
1
+ # ooxml_decrypt [![Build Status](https://travis-ci.org/woodbusy/ooxml_decrypt.svg?branch=master)](https://travis-ci.org/woodbusy/ooxml_decrypt)
2
+
3
+ A Ruby library and script for decrypting password-protected Microsoft Office XML files (.docx, .xlsx, etc.), which use the OOXML format. There are many tools available for working with OOXML files without Office, but a password-protected document typically requires an Office installation to decrypt. This pure-Ruby, standalone library and script can decrypt Office files without an Office installation.
4
+
5
+ At present, this only supports documents encrypted (i.e. password-protected) by Office 2010 or later. Office 2007 also uses XML, but the encryption settings are a bit different.
6
+
7
+
8
+ ## Contributing
9
+
10
+ Pull requests welcome! Once you've forked and cloned the project, you can `bundle install` to take care of the dependencies; after that, you're ready to code.
11
+
12
+ You can also create issues for any bugs or feature requests, but they may take longer to get done, of course.
13
+
14
+
15
+ ## TODO
16
+
17
+ - Support for Office 2007 documents
18
+ - Do verification (i.e. detect when password is incorrect)
19
+
20
+
21
+ ## References
22
+
23
+ - Microsoft [MS-OFFCRYPTO](https://msdn.microsoft.com/en-us/library/office/cc313071)
24
+ - http://www.lyquidity.com/devblog/?p=35
25
+ - http://www.lyquidity.com/devblog/?p=85
@@ -0,0 +1,69 @@
1
+ $LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + "/../lib"))
2
+
3
+ require "ooxml_decrypt"
4
+ require "optparse"
5
+
6
+ def program_name
7
+ File.basename(File.expand_path(__FILE__))
8
+ end
9
+
10
+ def parse_args(args=ARGV)
11
+ options = {}
12
+
13
+ @optparser = OptionParser.new(args) do |opts|
14
+ opts.banner = "Usage: #{program_name} [options]"
15
+
16
+ opts.on("-e", "--source <path>", "Path to encrypted file") do |filename|
17
+ options[:enc_filename] = filename
18
+ end
19
+
20
+ opts.on("-d", "--destination <path>", "Path to write decrypted file (if omitted, will append '.decrypted' to source filename") do |filename|
21
+ options[:dec_filename] = filename
22
+ end
23
+
24
+ opts.on("-p", "--password <password>", "Password to decrypt file (if omitted, will prompt)") do |password|
25
+ options[:password] = password
26
+ end
27
+ end
28
+
29
+ begin @optparser.parse! args
30
+ rescue OptionParser::InvalidOption => e
31
+ puts e
32
+ puts optparser
33
+ exit(1)
34
+ end
35
+
36
+ return options
37
+ end
38
+
39
+ def puts_usage
40
+ puts @optparser
41
+ end
42
+
43
+
44
+
45
+
46
+ options = parse_args()
47
+ unless options[:enc_filename]
48
+ warn "Source (encrypted) filename is required"
49
+ puts_usage
50
+ exit(1)
51
+ end
52
+
53
+ unless options[:password]
54
+ require "io/console"
55
+ print "Password: "
56
+ options[:password] = STDIN.noecho(&:gets).chomp
57
+ end
58
+
59
+ unless options[:dec_filename]
60
+ options[:dec_filename] = options[:enc_filename] + ".decrypted"
61
+ end
62
+
63
+ # Ensure password is a binary representation of a UTF-16LE string
64
+ # e.g. 'password' should be represented as "p\0\a\s\0[...]"
65
+ password = options[:password].encode("utf-16le")
66
+ .bytes.pack("c*")
67
+ .encode("binary")
68
+
69
+ OoxmlDecrypt::EncryptedFile.decrypt_to_file( options[:enc_filename], password, options[:dec_filename] )
@@ -0,0 +1,3 @@
1
+ require "ooxml_decrypt/key_data"
2
+ require "ooxml_decrypt/encrypted_key"
3
+ require "ooxml_decrypt/encrypted_file"
@@ -0,0 +1,88 @@
1
+ require "ole/storage"
2
+ require "nokogiri"
3
+
4
+ module OoxmlDecrypt
5
+ class EncryptedFile
6
+ # @param [String] filename Path to the encrypted OOXML file
7
+ def initialize(filename)
8
+ @ole = Ole::Storage.open(filename)
9
+ unless @ole.dir.entries(".").include?("EncryptionInfo") and
10
+ @ole.dir.entries(".").include?("EncryptedPackage")
11
+ raise "File does not appear to be an encrypted Office document"
12
+ end
13
+ end
14
+
15
+ # The EncryptionInfo section of the file, as an XML doc
16
+ # @return [Nokogiri::XML::Document]
17
+ def encryption_info
18
+ if @ei_xml.nil?
19
+ ei_text = @ole.file.read("EncryptionInfo")
20
+ v_major, v_minor, flags = ei_text[0,8].unpack("vvV")
21
+ unless v_major == 4 && v_minor == 4
22
+ raise "Unsupported encryption version"
23
+ end
24
+ unless flags == 0x40
25
+ raise "Unsupported encryption algorithm"
26
+ end
27
+
28
+ @ei_xml = Nokogiri::XML( ei_text[8..-1] )
29
+ end
30
+
31
+ return @ei_xml
32
+ end
33
+ private :encryption_info
34
+
35
+ def key_data
36
+ if @key_data.nil?
37
+ @key_data = KeyData.from_xml(encryption_info)
38
+ end
39
+
40
+ return @key_data
41
+ end
42
+ private :key_data
43
+
44
+ def encrypted_key
45
+ if @encrypted_key.nil?
46
+ @encrypted_key = EncryptedKey.from_xml(encryption_info)
47
+ end
48
+
49
+ return @encrypted_key
50
+ end
51
+ private :encrypted_key
52
+
53
+ def encrypted_package
54
+ @ole.file.read("EncryptedPackage")
55
+ end
56
+ private :encrypted_package
57
+
58
+ # Decrypts this encrypted file using the given password
59
+ # @param [String] password Password as a UTF-16-formatted binary string
60
+ # (e.g. the password 'password' should be passed as "p\0a\0s\0s\0w\0r\0d\0")
61
+ # @return [String] The decrypted file
62
+ def decrypt(password)
63
+ decryption_key = encrypted_key.key(password)
64
+ return key_data.decrypt_encrypted_package_stream( encrypted_package, decryption_key )
65
+ end
66
+
67
+ # Decrypts the given file using the given password
68
+ # @param [String] filename Path to the encrypted OOXML file
69
+ # @param [String] password Password as a UTF-16-formatted binary string
70
+ # (e.g. the password 'password' should be passed as "p\0a\0s\0s\0w\0r\0d\0")
71
+ def self.decrypt(filename, password)
72
+ encrypted_file = EncryptedFile.new(filename)
73
+ return encrypted_file.decrypt(password)
74
+ end
75
+
76
+ # Decrypts the given file using the given password and writes the result to
77
+ # a second file
78
+ # @param [String] enc_filename Path to the encrypted OOXML file
79
+ # @param [String] password Password as a UTF-16-formatted binary string
80
+ # (e.g. the password 'password' should be passed as "p\0a\0s\0s\0w\0r\0d\0")
81
+ # @param [String] dec_filename Path to the decrypted output file. If a file
82
+ # exists at this path, it will be overwritten.
83
+ def self.decrypt_to_file(enc_filename, password, dec_filename)
84
+ plaintext = decrypt(enc_filename, password)
85
+ File.open(dec_filename, "wb") {|file| file.write(plaintext)}
86
+ end
87
+ end
88
+ end
@@ -0,0 +1,53 @@
1
+ require "ooxml_decrypt/key_info_base"
2
+
3
+ module OoxmlDecrypt
4
+ class EncryptedKey < KeyInfoBase
5
+ # Integrity-verification constants (not currently used)
6
+ ENCRYPTED_VERIFIER_HASH_INPUT_BLOCK_KEY = "FEA7D2763B4B9E79".unhexify
7
+ ENCRYPTED_VERIFIER_HASH_VALUE_BLOCK_KEY = "D7AA0F6D3061344E".unhexify
8
+ # Static key used in decrypting the key-encryption key
9
+ ENCRYPTED_KEY_VALUE_BLOCK_KEY = "146E0BE7ABACD0D6".unhexify
10
+
11
+ def initialize(opts)
12
+ @spin_count = opts.delete(:spin_count)
13
+ @encrypted_key = opts.delete(:encrypted_key)
14
+ super(opts)
15
+ end
16
+
17
+ # Extracts key-encryption-key data parameters from the given XML document
18
+ # and populates a new EncryptedKey object.
19
+ # @param [Nokogiri::XML::Document] xml_doc The EncryptionInfo section of
20
+ # the encrypted OOXML document
21
+ def self.from_xml(xml_doc)
22
+ ke_node = xml_doc.at_css("keyEncryptor")
23
+ raise "Expected only one child for keyEncryptor" unless ke_node.children.count == 1
24
+
25
+ ek_node = ke_node.child
26
+ opts = KeyInfoBase.opts_from_xml_node(ek_node)
27
+ opts[:spin_count] = ek_node["spinCount"].to_i
28
+ opts[:encrypted_key] = ek_node["encryptedKeyValue"].base64_decode
29
+
30
+ return self.new(opts)
31
+ end
32
+
33
+ def key_encryption_key( password )
34
+ temp = hash( @salt + password )
35
+ @spin_count.times do |itr|
36
+ temp = hash( [itr].pack("V") + temp )
37
+ end
38
+
39
+ temp = hash(temp + ENCRYPTED_KEY_VALUE_BLOCK_KEY)
40
+ temp.pad_or_trim!( @key_bits/8 )
41
+ end
42
+ private :key_encryption_key
43
+
44
+ # Decrypts the key-encryption key using the given password
45
+ # @param [String] password Password as a UTF-16-formatted binary string
46
+ # (e.g. the password 'password' should be passed as "p\0a\0s\0s\0w\0r\0d\0")
47
+ # @return [String] The key-encryption key
48
+ def key(password)
49
+ decrypt(@encrypted_key, key_encryption_key(password))
50
+ end
51
+ end
52
+ end
53
+
@@ -0,0 +1,46 @@
1
+ require "ooxml_decrypt/key_info_base"
2
+
3
+ module OoxmlDecrypt
4
+ class KeyData < KeyInfoBase
5
+ # Integrity-verification constants (not currently used)
6
+ ENCRYPTED_DATA_INTEGRITY_SALT_BLOCK_KEY = "5FB2AD010CB9E1F6".unhexify
7
+ ENCRYPTED_DATA_INTEGRITY_HMAC_VALUE_BLOCK_KEY = "A0677F02B22C8433".unhexify
8
+
9
+ # Extracts key data parameters from the given XML document and populates a
10
+ # new KeyData object.
11
+ # @param [Nokogiri::XML::Document] xml_doc The EncryptionInfo section of
12
+ # the encrypted document
13
+ def self.from_xml(xml_doc)
14
+ kd_node = xml_doc.at_css("keyData")
15
+ opts = KeyInfoBase.opts_from_xml_node(kd_node)
16
+
17
+ return self.new(opts)
18
+ end
19
+
20
+ # Decrypts the given encrypted package using the given key.
21
+ # @param [String] encrypted_package The EncryptedPackage section of the
22
+ # encrypted document
23
+ # @param [String] key Decryption key
24
+ def decrypt_encrypted_package_stream(encrypted_package, key)
25
+ # Get the length of the real data in the cleartext (which may be shorter
26
+ # than the full decrypted ciphertext)
27
+ final_length = encrypted_package[0,8].unpack("Q<").first
28
+ # The rest of the encrypted package is the ciphertext
29
+ ciphertext = encrypted_package[8..-1]
30
+
31
+ chunk_size = 4096
32
+ ciphertext_chunks = (0..(ciphertext.length-1)/chunk_size).map{|i| ciphertext[i*chunk_size, chunk_size]}
33
+
34
+ plaintext = ""
35
+ ciphertext_chunks.each_with_index do |ciphertext_chunk, index|
36
+ iv = hash(@salt + [index].pack("V"))
37
+ iv.pad_or_trim!(@block_size)
38
+
39
+ plaintext += decrypt(ciphertext_chunk, key, iv)
40
+ end
41
+
42
+ return plaintext[0,final_length]
43
+ end
44
+ end
45
+ end
46
+
@@ -0,0 +1,76 @@
1
+ require "openssl"
2
+ require "ooxml_decrypt/string_helpers"
3
+
4
+ module OoxmlDecrypt
5
+ class KeyInfoBase
6
+ def initialize(opts)
7
+ @block_size = opts.delete(:block_size)
8
+ @hash_algorithm = opts.delete(:hash_algorithm)
9
+ @cipher_algorithm = opts.delete(:cipher_algorithm)
10
+ @key_bits = opts.delete(:key_bits)
11
+ @cipher_chaining = opts.delete(:cipher_chaining)
12
+ @salt = opts.delete(:salt)
13
+
14
+ raise "Unknown opts: #{opts.keys.join(',')}" if opts.any?
15
+ end
16
+
17
+ # Parses options that KeyInfoBase knows about from an XML node. (Helper
18
+ # function to be used by initializers in subclasses).
19
+ # @param [Nokogiri::XML::Node] xml_node
20
+ def self.opts_from_xml_node(xml_node)
21
+ opts = {
22
+ :block_size => xml_node["blockSize"].to_i,
23
+ :hash_algorithm => xml_node["hashAlgorithm"],
24
+ :cipher_algorithm => xml_node["cipherAlgorithm"],
25
+ :key_bits => xml_node["keyBits"].to_i,
26
+ :cipher_chaining => xml_node["cipherChaining"],
27
+ :salt => xml_node["saltValue"].base64_decode,
28
+ }
29
+ end
30
+
31
+ def hash(value)
32
+ case @hash_algorithm
33
+ when "SHA1"
34
+ Digest::SHA1.digest(value)
35
+ when "SHA512"
36
+ Digest::SHA512.digest(value)
37
+ else
38
+ raise "Unsupported hash algorithm: #{@hash_algorithm}"
39
+ end
40
+ end
41
+ protected :hash
42
+
43
+ def cipher(key, iv)
44
+ cipher_string = ""
45
+ case @cipher_algorithm
46
+ when "AES"
47
+ cipher_string += "aes"
48
+ else
49
+ raise "Unsupported cipher algorithm: #{@cipher_algorithm}"
50
+ end
51
+
52
+ cipher_string += "-#{@key_bits}"
53
+
54
+ case @cipher_chaining
55
+ when "ChainingModeCBC"
56
+ cipher_string += "-cbc"
57
+ else
58
+ raise "Unsupported chaining: #{@cipher_chaining}"
59
+ end
60
+
61
+ cipher = OpenSSL::Cipher.new(cipher_string)
62
+ cipher.key = key
63
+ cipher.iv = iv
64
+ cipher.padding = 0
65
+
66
+ return cipher
67
+ end
68
+ protected :cipher
69
+
70
+ def decrypt(ciphertext, key, iv=@salt)
71
+ cipher = cipher(key, iv)
72
+ return cipher.update(ciphertext) + cipher.final
73
+ end
74
+ protected :decrypt
75
+ end
76
+ end
@@ -0,0 +1,40 @@
1
+ module StringHelpers
2
+
3
+ # Convert a string to ASCII hex string
4
+ # (Adapted from the Ruby Black Bag [http://github.com/emonti/rbkb/])
5
+ def hexify()
6
+ out=Array.new
7
+ hexchars = [("0".."9").to_a, ("a".."f").to_a].flatten
8
+
9
+ self.each_byte do |c|
10
+ hc = (hexchars[(c >> 4)] + hexchars[(c & 0xf )])
11
+ out << (hc)
12
+ end
13
+ out.join("")
14
+ end
15
+
16
+ # Convert ASCII hex string to raw.
17
+ # (Adapted from the Ruby Black Bag [http://github.com/emonti/rbkb/])
18
+ # @param [Regex] d (Optional) 'delimiter' between hex bytes (zero+ spaces by default)
19
+ def unhexify(d=/\s*/)
20
+ self.strip.gsub(/([A-Fa-f0-9]{1,2})#{d}?/) { $1.hex.chr }
21
+ end
22
+
23
+ def base64_decode
24
+ return self.unpack("m").first
25
+ end
26
+
27
+ # Makes the string a given length by trimming excess bytes from the endi, or
28
+ # padding with the given padding byte.
29
+ # @param [Integer] final_length
30
+ # @pad_byte [String] pad_byte (Optional) A single-byte string (default is 0x36)
31
+ def pad_or_trim!( final_length, pad_byte="\x36" )
32
+ self.slice!(final_length..-1)
33
+ self << pad_byte * (final_length - self.length)
34
+ return self
35
+ end
36
+ end
37
+
38
+ class String
39
+ include StringHelpers
40
+ end
@@ -0,0 +1,20 @@
1
+ Gem::Specification.new do |spec|
2
+ spec.name = 'ooxml_decrypt'
3
+ spec.version = '0.1.0'
4
+ spec.authors = %w[woodbusy phish]
5
+ spec.summary = 'Ruby library and script for decrypting password-protected ' \
6
+ 'Microsoft Office XML files (.docx, .xlsx, etc.)'
7
+ spec.homepage = 'https://github.com/woodbusy/ooxml_decrypt'
8
+ spec.license = 'Apache-2.0'
9
+
10
+ spec.files = `git ls-files -z`.split("\x0").reject { |s| s =~ %r{^pkg/} }
11
+ spec.files -= %w[.travis.yml] # Not needed in the gem
12
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
13
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
14
+ spec.require_paths = ['lib']
15
+
16
+ spec.add_dependency 'nokogiri'
17
+ spec.add_dependency 'ruby-ole'
18
+
19
+ spec.add_development_dependency 'rspec', '>= 2.11.0', '< 4.0'
20
+ end
@@ -0,0 +1,46 @@
1
+ require "spec_helper"
2
+
3
+ module OoxmlDecrypt
4
+ describe "When testing decryption" do
5
+ let(:encrypted_key) do
6
+ EncryptedKey.new( :spin_count => 100_000,
7
+ :block_size => 16,
8
+ :key_bits => 128,
9
+ :cipher_algorithm => "AES",
10
+ :cipher_chaining => "ChainingModeCBC",
11
+ :hash_algorithm => "SHA1",
12
+ :salt => "oksWUymFqdISO4t7krYTMQ==".base64_decode,
13
+ :encrypted_key => "7fHCMYen4j6VmJtYiuoKdA==".base64_decode,
14
+ )
15
+ end
16
+ let(:key_data) do
17
+ KeyData.new( :block_size => 16,
18
+ :key_bits => 128,
19
+ :cipher_algorithm => "AES",
20
+ :cipher_chaining => "ChainingModeCBC",
21
+ :hash_algorithm => "SHA1",
22
+ :salt => "O/HT8XgDoXnw+k9ts0Esxw==".base64_decode,
23
+ )
24
+ end
25
+ let(:password) { "p\0a\0s\0s\0w\0o\0r\0d\0" }
26
+
27
+ # it "should generate a key-decryption key" do
28
+ # key_encryption_key = encrypted_key.key_encryption_key(password)
29
+ # expect( key_encryption_key.hexify ).to eql("1a1f6755f5a4f216023707fa3c986502")
30
+ # end
31
+
32
+ it "should decrypt a symmetric key" do
33
+ expect( encrypted_key.key(password).hexify ).to eql("c965e405bc4183399e038d3784d26f93")
34
+ end
35
+
36
+ it "should decrypt an entire encrypted package stream" do
37
+ encrypted_package = File.read("spec/examples/password.encrypted_package", :encoding => 'binary')
38
+ plaintext = key_data.decrypt_encrypted_package_stream( encrypted_package, encrypted_key.key(password) )
39
+ expect(plaintext[0,16].hexify).to eql("504b0304140006000800000021009745")
40
+ expect(plaintext[-16,16].hexify).to eql("0000090009003e020000731b00000000")
41
+
42
+ expected_plaintext = File.read("spec/examples/password.xlsx_decrypted", :encoding => "binary")
43
+ expect(plaintext.hexify).to eql(expected_plaintext.hexify)
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,17 @@
1
+ require "spec_helper"
2
+
3
+ module OoxmlDecrypt
4
+ describe EncryptedFile do
5
+ it "should decrypt an encrypted XLSX" do
6
+ password = "p\0a\0s\0s\0w\0o\0r\0d\0"
7
+ filename = "spec/examples/password.xlsx"
8
+ plaintext = EncryptedFile.decrypt(filename, password)
9
+
10
+ expect(plaintext[0,16].hexify).to eql("504b0304140006000800000021009745")
11
+ expect(plaintext[-16,16].hexify).to eql("0000090009003e020000731b00000000")
12
+
13
+ expected_plaintext = File.read("spec/examples/password.xlsx_decrypted", :encoding => "binary")
14
+ expect(plaintext.hexify).to eql(expected_plaintext.hexify)
15
+ end
16
+ end
17
+ end
Binary file
Binary file
@@ -0,0 +1,2 @@
1
+ require "ooxml_decrypt"
2
+ require "ooxml_decrypt/string_helpers"
metadata ADDED
@@ -0,0 +1,121 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ooxml_decrypt
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - woodbusy
8
+ - phish
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2019-05-07 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: nokogiri
16
+ requirement: !ruby/object:Gem::Requirement
17
+ requirements:
18
+ - - ">="
19
+ - !ruby/object:Gem::Version
20
+ version: '0'
21
+ type: :runtime
22
+ prerelease: false
23
+ version_requirements: !ruby/object:Gem::Requirement
24
+ requirements:
25
+ - - ">="
26
+ - !ruby/object:Gem::Version
27
+ version: '0'
28
+ - !ruby/object:Gem::Dependency
29
+ name: ruby-ole
30
+ requirement: !ruby/object:Gem::Requirement
31
+ requirements:
32
+ - - ">="
33
+ - !ruby/object:Gem::Version
34
+ version: '0'
35
+ type: :runtime
36
+ prerelease: false
37
+ version_requirements: !ruby/object:Gem::Requirement
38
+ requirements:
39
+ - - ">="
40
+ - !ruby/object:Gem::Version
41
+ version: '0'
42
+ - !ruby/object:Gem::Dependency
43
+ name: rspec
44
+ requirement: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - ">="
47
+ - !ruby/object:Gem::Version
48
+ version: 2.11.0
49
+ - - "<"
50
+ - !ruby/object:Gem::Version
51
+ version: '4.0'
52
+ type: :development
53
+ prerelease: false
54
+ version_requirements: !ruby/object:Gem::Requirement
55
+ requirements:
56
+ - - ">="
57
+ - !ruby/object:Gem::Version
58
+ version: 2.11.0
59
+ - - "<"
60
+ - !ruby/object:Gem::Version
61
+ version: '4.0'
62
+ description:
63
+ email:
64
+ executables:
65
+ - decrypt_ooxml.rb
66
+ extensions: []
67
+ extra_rdoc_files: []
68
+ files:
69
+ - ".gitignore"
70
+ - Gemfile
71
+ - LICENSE
72
+ - README.md
73
+ - bin/decrypt_ooxml.rb
74
+ - lib/ooxml_decrypt.rb
75
+ - lib/ooxml_decrypt/encrypted_file.rb
76
+ - lib/ooxml_decrypt/encrypted_key.rb
77
+ - lib/ooxml_decrypt/key_data.rb
78
+ - lib/ooxml_decrypt/key_info_base.rb
79
+ - lib/ooxml_decrypt/string_helpers.rb
80
+ - ooxml_decrypt.gemspec
81
+ - spec/crypto_spec.rb
82
+ - spec/encrypted_file_spec.rb
83
+ - spec/examples/1qaz2wsx.xlsx
84
+ - spec/examples/password.encrypted_package
85
+ - spec/examples/password.encryption_info
86
+ - spec/examples/password.xlsx
87
+ - spec/examples/password.xlsx_decrypted
88
+ - spec/spec_helper.rb
89
+ homepage: https://github.com/woodbusy/ooxml_decrypt
90
+ licenses:
91
+ - Apache-2.0
92
+ metadata: {}
93
+ post_install_message:
94
+ rdoc_options: []
95
+ require_paths:
96
+ - lib
97
+ required_ruby_version: !ruby/object:Gem::Requirement
98
+ requirements:
99
+ - - ">="
100
+ - !ruby/object:Gem::Version
101
+ version: '0'
102
+ required_rubygems_version: !ruby/object:Gem::Requirement
103
+ requirements:
104
+ - - ">="
105
+ - !ruby/object:Gem::Version
106
+ version: '0'
107
+ requirements: []
108
+ rubygems_version: 3.0.3
109
+ signing_key:
110
+ specification_version: 4
111
+ summary: Ruby library and script for decrypting password-protected Microsoft Office
112
+ XML files (.docx, .xlsx, etc.)
113
+ test_files:
114
+ - spec/crypto_spec.rb
115
+ - spec/encrypted_file_spec.rb
116
+ - spec/examples/1qaz2wsx.xlsx
117
+ - spec/examples/password.encrypted_package
118
+ - spec/examples/password.encryption_info
119
+ - spec/examples/password.xlsx
120
+ - spec/examples/password.xlsx_decrypted
121
+ - spec/spec_helper.rb