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 12KB

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