You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ChunkedCipherOutputStream.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.poifs.crypt;
  16. import static org.apache.poi.poifs.crypt.Decryptor.DEFAULT_POIFS_ENTRY;
  17. import java.io.File;
  18. import java.io.FileInputStream;
  19. import java.io.FileOutputStream;
  20. import java.io.FilterOutputStream;
  21. import java.io.IOException;
  22. import java.io.OutputStream;
  23. import java.security.GeneralSecurityException;
  24. import javax.crypto.Cipher;
  25. import com.zaxxer.sparsebits.SparseBitSet;
  26. import org.apache.logging.log4j.LogManager;
  27. import org.apache.logging.log4j.Logger;
  28. import org.apache.poi.EncryptedDocumentException;
  29. import org.apache.poi.poifs.filesystem.DirectoryNode;
  30. import org.apache.poi.poifs.filesystem.POIFSWriterEvent;
  31. import org.apache.poi.util.IOUtils;
  32. import org.apache.poi.util.Internal;
  33. import org.apache.poi.util.LittleEndian;
  34. import org.apache.poi.util.LittleEndianConsts;
  35. import org.apache.poi.util.TempFile;
  36. @Internal
  37. public abstract class ChunkedCipherOutputStream extends FilterOutputStream {
  38. private static final Logger LOG = LogManager.getLogger(ChunkedCipherOutputStream.class);
  39. private static final int STREAMING = -1;
  40. private final int chunkSize;
  41. private final int chunkBits;
  42. private final byte[] chunk;
  43. private final SparseBitSet plainByteFlags;
  44. private final File fileOut;
  45. private final DirectoryNode dir;
  46. private long pos;
  47. private long totalPos;
  48. private long written;
  49. // the cipher can't be final, because for the last chunk we change the padding
  50. // and therefore need to change the cipher too
  51. private Cipher cipher;
  52. private boolean isClosed;
  53. public ChunkedCipherOutputStream(DirectoryNode dir, int chunkSize) throws IOException, GeneralSecurityException {
  54. super(null);
  55. this.chunkSize = chunkSize;
  56. int cs = chunkSize == STREAMING ? 4096 : chunkSize;
  57. this.chunk = IOUtils.safelyAllocate(cs, CryptoFunctions.MAX_RECORD_LENGTH);
  58. this.plainByteFlags = new SparseBitSet(cs);
  59. this.chunkBits = Integer.bitCount(cs-1);
  60. this.fileOut = TempFile.createTempFile("encrypted_package", "crypt");
  61. this.out = new FileOutputStream(fileOut);
  62. this.dir = dir;
  63. this.cipher = initCipherForBlock(null, 0, false);
  64. }
  65. public ChunkedCipherOutputStream(OutputStream stream, int chunkSize) throws IOException, GeneralSecurityException {
  66. super(stream);
  67. this.chunkSize = chunkSize;
  68. int cs = chunkSize == STREAMING ? 4096 : chunkSize;
  69. this.chunk = IOUtils.safelyAllocate(cs, CryptoFunctions.MAX_RECORD_LENGTH);
  70. this.plainByteFlags = new SparseBitSet(cs);
  71. this.chunkBits = Integer.bitCount(cs-1);
  72. this.fileOut = null;
  73. this.dir = null;
  74. this.cipher = initCipherForBlock(null, 0, false);
  75. }
  76. public final Cipher initCipherForBlock(int block, boolean lastChunk) throws IOException, GeneralSecurityException {
  77. return initCipherForBlock(cipher, block, lastChunk);
  78. }
  79. // helper method to break a recursion loop introduced because of an IBMJCE bug, i.e. not resetting on Cipher.doFinal()
  80. @Internal
  81. protected Cipher initCipherForBlockNoFlush(Cipher existing, int block, boolean lastChunk)
  82. throws IOException, GeneralSecurityException {
  83. return initCipherForBlock(cipher, block, lastChunk);
  84. }
  85. protected abstract Cipher initCipherForBlock(Cipher existing, int block, boolean lastChunk)
  86. throws IOException, GeneralSecurityException;
  87. protected abstract void calculateChecksum(File fileOut, int oleStreamSize)
  88. throws GeneralSecurityException, IOException;
  89. protected abstract void createEncryptionInfoEntry(DirectoryNode dir, File tmpFile)
  90. throws IOException, GeneralSecurityException;
  91. @Override
  92. public void write(int b) throws IOException {
  93. write(new byte[]{(byte)b});
  94. }
  95. @Override
  96. public void write(byte[] b) throws IOException {
  97. write(b, 0, b.length);
  98. }
  99. @Override
  100. public void write(byte[] b, int off, int len) throws IOException {
  101. write(b, off, len, false);
  102. }
  103. public void writePlain(byte[] b, int off, int len) throws IOException {
  104. write(b, off, len, true);
  105. }
  106. protected void write(byte[] b, int off, int len, boolean writePlain) throws IOException {
  107. if (len == 0) {
  108. return;
  109. }
  110. if (len < 0 || b.length < off+len) {
  111. throw new IOException("not enough bytes in your input buffer");
  112. }
  113. final int chunkMask = getChunkMask();
  114. while (len > 0) {
  115. int posInChunk = (int)(pos & chunkMask);
  116. int nextLen = Math.min(chunk.length-posInChunk, len);
  117. System.arraycopy(b, off, chunk, posInChunk, nextLen);
  118. if (writePlain) {
  119. plainByteFlags.set(posInChunk, posInChunk+nextLen);
  120. }
  121. pos += nextLen;
  122. totalPos += nextLen;
  123. off += nextLen;
  124. len -= nextLen;
  125. if ((pos & chunkMask) == 0) {
  126. writeChunk(len > 0);
  127. }
  128. }
  129. }
  130. protected int getChunkMask() {
  131. return chunk.length-1;
  132. }
  133. protected void writeChunk(boolean continued) throws IOException {
  134. if (pos == 0 || totalPos == written) {
  135. return;
  136. }
  137. int posInChunk = (int)(pos & getChunkMask());
  138. // normally posInChunk is 0, i.e. on the next chunk (-> index-1)
  139. // but if called on close(), posInChunk is somewhere within the chunk data
  140. int index = (int)(pos >> chunkBits);
  141. boolean lastChunk;
  142. if (posInChunk==0) {
  143. index--;
  144. posInChunk = chunk.length;
  145. lastChunk = false;
  146. } else {
  147. // pad the last chunk
  148. lastChunk = true;
  149. }
  150. int ciLen;
  151. try {
  152. boolean doFinal = true;
  153. long oldPos = pos;
  154. // reset stream (not only) in case we were interrupted by plain stream parts
  155. // this also needs to be set to prevent an endless loop
  156. pos = 0;
  157. if (chunkSize == STREAMING) {
  158. if (continued) {
  159. doFinal = false;
  160. }
  161. } else {
  162. cipher = initCipherForBlock(cipher, index, lastChunk);
  163. // restore pos - only streaming chunks will be reset
  164. pos = oldPos;
  165. }
  166. ciLen = invokeCipher(posInChunk, doFinal);
  167. } catch (GeneralSecurityException e) {
  168. throw new IOException("can't re-/initialize cipher", e);
  169. }
  170. out.write(chunk, 0, ciLen);
  171. plainByteFlags.clear();
  172. written += ciLen;
  173. }
  174. /**
  175. * Helper function for overriding the cipher invocation, i.e. XOR doesn't use a cipher
  176. * and uses its own implementation
  177. */
  178. protected int invokeCipher(int posInChunk, boolean doFinal) throws GeneralSecurityException, IOException {
  179. byte[] plain = (plainByteFlags.isEmpty()) ? null : chunk.clone();
  180. int ciLen = (doFinal)
  181. ? cipher.doFinal(chunk, 0, posInChunk, chunk)
  182. : cipher.update(chunk, 0, posInChunk, chunk);
  183. if (doFinal && "IBMJCE".equals(cipher.getProvider().getName()) && "RC4".equals(cipher.getAlgorithm())) {
  184. // workaround for IBMs cipher not resetting on doFinal
  185. int index = (int)(pos >> chunkBits);
  186. boolean lastChunk;
  187. if (posInChunk==0) {
  188. index--;
  189. posInChunk = chunk.length;
  190. lastChunk = false;
  191. } else {
  192. // pad the last chunk
  193. lastChunk = true;
  194. }
  195. cipher = initCipherForBlockNoFlush(cipher, index, lastChunk);
  196. }
  197. if (plain != null) {
  198. int i = plainByteFlags.nextSetBit(0);
  199. while (i >= 0 && i < posInChunk) {
  200. chunk[i] = plain[i];
  201. i = plainByteFlags.nextSetBit(i+1);
  202. }
  203. }
  204. return ciLen;
  205. }
  206. @Override
  207. public void close() throws IOException {
  208. if (isClosed) {
  209. LOG.atDebug().log("ChunkedCipherOutputStream was already closed - ignoring");
  210. return;
  211. }
  212. isClosed = true;
  213. try {
  214. writeChunk(false);
  215. super.close();
  216. if (fileOut != null) {
  217. int oleStreamSize = (int)(fileOut.length()+LittleEndianConsts.LONG_SIZE);
  218. calculateChecksum(fileOut, (int)pos);
  219. dir.createDocument(DEFAULT_POIFS_ENTRY, oleStreamSize, this::processPOIFSWriterEvent);
  220. createEncryptionInfoEntry(dir, fileOut);
  221. }
  222. } catch (GeneralSecurityException e) {
  223. throw new IOException(e);
  224. } finally {
  225. if (fileOut != null) {
  226. if (!fileOut.delete()) {
  227. //ignore
  228. }
  229. }
  230. }
  231. }
  232. protected byte[] getChunk() {
  233. return chunk;
  234. }
  235. protected SparseBitSet getPlainByteFlags() {
  236. return plainByteFlags;
  237. }
  238. protected long getPos() {
  239. return pos;
  240. }
  241. protected long getTotalPos() {
  242. return totalPos;
  243. }
  244. /**
  245. * Some ciphers (actually just XOR) are based on the record size,
  246. * which needs to be set before encryption
  247. *
  248. * @param recordSize the size of the next record
  249. * @param isPlain {@code true} if the record is unencrypted
  250. */
  251. public void setNextRecordSize(int recordSize, boolean isPlain) {
  252. }
  253. private void processPOIFSWriterEvent(POIFSWriterEvent event) {
  254. try {
  255. try (OutputStream os = event.getStream();
  256. FileInputStream fis = new FileInputStream(fileOut)) {
  257. // StreamSize (8 bytes): An unsigned integer that specifies the number of bytes used by data
  258. // encrypted within the EncryptedData field, not including the size of the StreamSize field.
  259. // Note that the actual size of the \EncryptedPackage stream (1) can be larger than this
  260. // value, depending on the block size of the chosen encryption algorithm
  261. byte[] buf = new byte[LittleEndianConsts.LONG_SIZE];
  262. LittleEndian.putLong(buf, 0, pos);
  263. os.write(buf);
  264. IOUtils.copy(fis, os);
  265. }
  266. if (!fileOut.delete()) {
  267. LOG.atError().log("Can't delete temporary encryption file: {}", fileOut);
  268. }
  269. } catch (IOException e) {
  270. throw new EncryptedDocumentException(e);
  271. }
  272. }
  273. }