Esempio n. 1
0
        public void Bug57080()
        {
            // the test file Contains a wrong ole entry size, produced by extenxls
            // the fix limits the available size and tries to read all entries
            FileStream       f    = POIDataSamples.GetPOIFSInstance().GetFile("extenxls_pwd123.xlsx");
            NPOIFSFileSystem fs   = new NPOIFSFileSystem(f, true);
            EncryptionInfo   info = new EncryptionInfo(fs);
            Decryptor        d    = Decryptor.GetInstance(info);

            d.VerifyPassword("pwd123");
            MemoryStream   bos = new MemoryStream();
            ZipInputStream zis = new ZipInputStream(d.GetDataStream(fs));
            ZipEntry       ze;

            while ((ze = zis.GetNextEntry()) != null)
            {
                //bos.Reset();
                bos.Seek(0, SeekOrigin.Begin);
                bos.SetLength(0);
                IOUtils.Copy(zis, bos);
                Assert.AreEqual(ze.Size, bos.Length);
            }

            zis.Close();
            fs.Close();
        }
Esempio n. 2
0
        private void ZipOk(DirectoryNode root, Decryptor d)
        {
            ZipInputStream zin = new ZipInputStream(d.GetDataStream(root));

            while (true)
            {
                ZipEntry entry = zin.GetNextEntry();
                if (entry == null)
                {
                    break;
                }
                // crc32 is Checked within zip-stream
                if (entry.IsDirectory)
                {
                    continue;
                }
                zin.Skip(entry.Size);
                byte[] buf       = new byte[10];
                int    ReadBytes = zin.Read(buf, 0, buf.Length);
                // zin.Available() doesn't work for entries
                Assert.AreEqual(-1, ReadBytes, "size failed for " + entry.Name);
            }

            zin.Close();
        }
Esempio n. 3
0
        public void TestAgileEncryptionModes()
        {
            int maxKeyLen = Cipher.GetMaxAllowedKeyLength(ca.jceId);

            Assume.That(maxKeyLen >= ca.defaultKeySize, "Please install JCE Unlimited Strength Jurisdiction Policy files");

            MemoryStream bos = new MemoryStream();

            POIFSFileSystem fsEnc   = new POIFSFileSystem();
            EncryptionInfo  infoEnc = new EncryptionInfo(EncryptionMode.Agile, ca, ha, -1, -1, cm);
            Encryptor       enc     = infoEnc.Encryptor;

            enc.ConfirmPassword("foobaa");
            Stream os = enc.GetDataStream(fsEnc);

            os.Write(testData, 0, testData.Length);
            os.Close();
            //bos.Reset();
            bos.Seek(0, SeekOrigin.Begin);
            fsEnc.WriteFileSystem(bos);

            POIFSFileSystem fsDec   = new POIFSFileSystem(new MemoryStream(bos.ToArray()));
            EncryptionInfo  infoDec = new EncryptionInfo(fsDec);
            Decryptor       dec     = infoDec.Decryptor;
            bool            passed  = dec.VerifyPassword("foobaa");

            Assert.IsTrue(passed);
            Stream is1 = dec.GetDataStream(fsDec);

            byte[] actualData = IOUtils.ToByteArray(is1);
            is1.Close();
            //assertThat("Failed roundtrip - " + ca + "-" + ha + "-" + cm, testData, EqualTo(actualData));
            Assert.That(testData, Is.EqualTo(actualData), "Failed roundtrip - " + ca + "-" + ha + "-" + cm);
        }
Esempio n. 4
0
        public void InPlaceReWrite()
        {
            FileInfo f = TempFile.CreateTempFile("protected_agile", ".docx");
            // File f = new File("protected_agile.docx");
            FileStream fos = f.Create();
            Stream     fis = POIDataSamples.GetPOIFSInstance().OpenResourceAsStream("protected_agile.docx");

            IOUtils.Copy(fis, fos);
            fis.Close();
            fos.Close();

            NPOIFSFileSystem fs = new NPOIFSFileSystem(f, false);

            // decrypt the protected file - in this case it was encrypted with the default password
            EncryptionInfo encInfo = new EncryptionInfo(fs);
            Decryptor      d       = encInfo.Decryptor;
            bool           b       = d.VerifyPassword(Decryptor.DEFAULT_PASSWORD);

            Assert.IsTrue(b);

            // do some strange things with it ;)
            XWPFDocument docx = new XWPFDocument(d.GetDataStream(fs));

            docx.GetParagraphArray(0).InsertNewRun(0).SetText("POI was here! All your base are belong to us!");
            docx.GetParagraphArray(0).InsertNewRun(1).AddBreak();

            // and encrypt it again
            Encryptor e = encInfo.Encryptor;

            e.ConfirmPassword("AYBABTU");
            docx.Write(e.GetDataStream(fs));

            fs.Close();
        }
Esempio n. 5
0
        public void Test58616()
        {
            POIFSFileSystem pfs  = new POIFSFileSystem(XSSFTestDataSamples.GetSampleFile("58616.xlsx").Create());
            EncryptionInfo  info = new EncryptionInfo(pfs);
            Decryptor       dec  = Decryptor.GetInstance(info);

            //dec.VerifyPassword(null);
            dec.GetDataStream(pfs);
        }
Esempio n. 6
0
 protected ChunkedCipherInputStream(
     InputStream stream,
     long size,
     int chunkSize,
     IEncryptionInfoBuilder builder,
     Decryptor decryptor)
     : this(stream, size, chunkSize, 0, builder, decryptor)
 {
 }
Esempio n. 7
0
        public void PasswordVerification()
        {
            POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.GetPOIFSInstance().OpenResourceAsStream("protect.xlsx"));

            EncryptionInfo info = new EncryptionInfo(fs);

            Decryptor d = Decryptor.GetInstance(info);

            Assert.IsTrue(d.VerifyPassword(Decryptor.DEFAULT_PASSWORD));
        }
Esempio n. 8
0
        public static Decryptor GetInstance(EncryptionInfo info)
        {
            Decryptor d = info.Decryptor;

            if (d == null)
            {
                throw new EncryptedDocumentException("Unsupported version");
            }
            return(d);
        }
Esempio n. 9
0
        public void Decrypt()
        {
            POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.GetPOIFSInstance().OpenResourceAsStream("protect.xlsx"));

            EncryptionInfo info = new EncryptionInfo(fs);

            Decryptor d = Decryptor.GetInstance(info);

            d.VerifyPassword(Decryptor.DEFAULT_PASSWORD);

            ZipOk(fs.Root, d);
        }
Esempio n. 10
0
 public ChunkedCipherInputStream(ILittleEndianInput stream, long size, int chunkSize
                                 , IEncryptionInfoBuilder builder, Decryptor decryptor)
     : base((Stream)stream)
 {
     _size          = size;
     this.chunkSize = chunkSize;
     chunkMask      = chunkSize - 1;
     chunkBits      = Number.BitCount(chunkMask);
     this.builder   = builder;
     this.decryptor = decryptor;
     _cipher        = InitCipherForBlock(null, 0);
 }
Esempio n. 11
0
        public void ProtectedTempZip()
        {
            FileInfo        tmpFile  = TempFile.CreateTempFile("protectedXlsx", ".zip");
            FileInfo        tikaProt = XSSFTestDataSamples.GetSampleFile("protected_passtika.xlsx");
            FileInputStream fis      = new FileInputStream(tikaProt.Open(FileMode.Open));
            POIFSFileSystem poifs    = new POIFSFileSystem(fis);
            EncryptionInfo  ei       = new EncryptionInfo(poifs);
            Decryptor       dec      = ei.Decryptor;
            bool            passOk   = dec.VerifyPassword("tika");

            Assert.IsTrue(passOk);

            // generate session key
            SecureRandom sr = new SecureRandom();

            byte[] ivBytes = new byte[16], keyBytes = new byte[16];
            sr.NextBytes(ivBytes);
            sr.NextBytes(keyBytes);

            // extract encrypted ooxml file and write to custom encrypted zip file
            InputStream is1 = dec.GetDataStream(poifs);

            CopyToFile(is1, tmpFile, CipherAlgorithm.aes128, keyBytes, ivBytes);
            is1.Close();

            // provide ZipEntrySource to poi which decrypts on the fly
            ZipEntrySource source = fileToSource(tmpFile, CipherAlgorithm.aes128, keyBytes, ivBytes);

            // test the source
            OPCPackage opc      = OPCPackage.Open(source);
            String     expected = "This is an Encrypted Excel spreadsheet.";

            //XSSFEventBasedExcelExtractor extractor = new XSSFEventBasedExcelExtractor(opc);
            //extractor.IncludeSheetNames = (/*setter*/false);
            //String txt = extractor.Text;
            //Assert.AreEqual(expected, txt.Trim());

            //XSSFWorkbook wb = new XSSFWorkbook(opc);
            //txt = wb.GetSheetAt(0).GetRow(0).GetCell(0).StringCellValue;
            //Assert.AreEqual(expected, txt);

            //extractor.Close();

            //wb.Close();
            opc.Close();
            source.Close();
            poifs.Close();
            fis.Close();
            tmpFile.Delete();

            throw new NotImplementedException();
        }
Esempio n. 12
0
        public void Agile()
        {
            POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.GetPOIFSInstance().OpenResourceAsStream("protected_agile.docx"));

            EncryptionInfo info = new EncryptionInfo(fs);

            Assert.IsTrue(info.VersionMajor == 4 && info.VersionMinor == 4);

            Decryptor d = Decryptor.GetInstance(info);

            Assert.IsTrue(d.VerifyPassword(Decryptor.DEFAULT_PASSWORD));

            ZipOk(fs.Root, d);
        }
Esempio n. 13
0
        private void ZipOk(POIFSFileSystem fs, Decryptor d)
        {
            ZipInputStream zin = new ZipInputStream(d.GetDataStream(fs));
            while (true)
            {
                ZipEntry entry = zin.GetNextEntry();
                if (entry == null)
                {
                    break;
                }

                while (zin.Available > 0)
                {
                    zin.Skip(zin.Available);
                }
            }
        }
Esempio n. 14
0
        public void EncryptPackageWithoutCoreProperties()
        {
            // Open our file without core properties
            FileStream inp = POIDataSamples.GetOpenXML4JInstance().GetFile("OPCCompliance_NoCoreProperties.xlsx");
            OPCPackage pkg = OPCPackage.Open(inp.Name);

            // It doesn't have any core properties yet
            Assert.AreEqual(0, pkg.GetPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).Count);
            Assert.IsNotNull(pkg.GetPackageProperties());
            Assert.IsNotNull(pkg.GetPackageProperties().GetLanguageProperty());
            //Assert.IsNull(pkg.GetPackageProperties().GetLanguageProperty().GetValue());

            // Encrypt it
            EncryptionInfo   info = new EncryptionInfo(EncryptionMode.Agile);
            NPOIFSFileSystem fs   = new NPOIFSFileSystem();

            Encryptor enc = info.Encryptor;

            enc.ConfirmPassword("password");
            OutputStream os = enc.GetDataStream(fs);

            pkg.Save(os);
            pkg.Revert();

            // Save the resulting OLE2 document, and re-open it
            MemoryStream baos = new MemoryStream();

            fs.WriteFileSystem(baos);

            MemoryStream     bais  = new MemoryStream(baos.ToArray());
            NPOIFSFileSystem inpFS = new NPOIFSFileSystem(bais);

            // Check we can decrypt it
            info = new EncryptionInfo(inpFS);
            Decryptor d = Decryptor.GetInstance(info);

            Assert.AreEqual(true, d.VerifyPassword("password"));

            OPCPackage inpPkg = OPCPackage.Open(d.GetDataStream(inpFS));

            // Check it now has empty core properties
            Assert.AreEqual(1, inpPkg.GetPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).Count);
            Assert.IsNotNull(inpPkg.GetPackageProperties());
            Assert.IsNotNull(inpPkg.GetPackageProperties().GetLanguageProperty());
            //Assert.IsNull(inpPkg.PackageProperties.LanguageProperty.Value);
        }
Esempio n. 15
0
        public void BinaryRC4Encryption()
        {
            // please contribute a real sample file, which is binary rc4 encrypted
            // ... at least the output can be opened in Excel Viewer
            String password = "******";

            Stream       is1             = POIDataSamples.GetSpreadSheetInstance().OpenResourceAsStream("SimpleMultiCell.xlsx");
            MemoryStream payloadExpected = new MemoryStream();

            IOUtils.Copy(is1, payloadExpected);
            is1.Close();

            POIFSFileSystem fs  = new POIFSFileSystem();
            EncryptionInfo  ei  = new EncryptionInfo(EncryptionMode.BinaryRC4);
            Encryptor       enc = ei.Encryptor;

            enc.ConfirmPassword(password);

            Stream os = enc.GetDataStream(fs.Root);

            payloadExpected.WriteTo(os);
            os.Close();

            MemoryStream bos = new MemoryStream();

            fs.WriteFileSystem(bos);

            fs = new POIFSFileSystem(new MemoryStream(bos.ToArray()));
            ei = new EncryptionInfo(fs);
            Decryptor dec = ei.Decryptor;
            bool      b   = dec.VerifyPassword(password);

            Assert.IsTrue(b);

            MemoryStream payloadActual = new MemoryStream();

            is1 = dec.GetDataStream(fs.Root);
            IOUtils.Copy(is1, payloadActual);
            is1.Close();

            Assert.IsTrue(Arrays.Equals(payloadExpected.ToArray(), payloadActual.ToArray()));
            //assertArrayEquals(payloadExpected.ToArray(), payloadActual.ToArray());
        }
Esempio n. 16
0
        private void ZipOk(POIFSFileSystem fs, Decryptor d)
        {
            ZipInputStream zin = new ZipInputStream(d.GetDataStream(fs));
            while (true)
            {
                int pos = zin.ReadByte();
                if (pos == -1)
                    break;
            //    ZipEntry entry = zin.GetNextEntry();
            //    if (entry == null)
            //    {
            //        break;
            //    }

                //while (zin.available() > 0)
                //{
                //    zin.skip(zin.available());
                //}
            }
        }
Esempio n. 17
0
        protected ChunkedCipherInputStream(
            InputStream stream,
            long size,
            int chunkSize,
            int initialPos,
            IEncryptionInfoBuilder builder,
            Decryptor decryptor)
            : base(stream)
        {
            this._size      = size;
            this._pos       = initialPos;
            this._chunkSize = chunkSize;

            this.builder   = builder;
            this.decryptor = decryptor;

            var cs = chunkSize == -1 ? 4096 : chunkSize;

            this._chunk     = IOUtils.SafelyAllocate(cs, CryptoFunctions.MAX_RECORD_LENGTH);
            this._plain     = IOUtils.SafelyAllocate(cs, CryptoFunctions.MAX_RECORD_LENGTH);
            this._chunkBits = Number.BitCount(_chunk.Length - 1);
            this._lastIndex = (int)(_pos >> _chunkBits);
            this._cipher    = InitCipherForBlock(null, _lastIndex);
        }
Esempio n. 18
0
        public void DataLength()
        {
            POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.GetPOIFSInstance().OpenResourceAsStream("protected_agile.docx"));

            EncryptionInfo info = new EncryptionInfo(fs);

            Decryptor d = Decryptor.GetInstance(info);

            d.VerifyPassword(Decryptor.DEFAULT_PASSWORD);

            Stream is1 = d.GetDataStream(fs);

            long len = d.GetLength();

            Assert.AreEqual(12810, len);

            byte[] buf = new byte[(int)len];

            is1.Read(buf, 0, buf.Length);

            ZipInputStream zin = new ZipInputStream(new MemoryStream(buf));

            while (true)
            {
                ZipEntry entry = zin.GetNextEntry();
                if (entry == null)
                {
                    break;
                }

                while (zin.Available > 0)
                {
                    zin.Skip(zin.Available);
                }
            }
        }
Esempio n. 19
0
        public void StandardEncryption()
        {
            FileStream file = POIDataSamples.GetDocumentInstance().GetFile("bug53475-password-is-solrcell.docx");
            String     pass = "******";

            NPOIFSFileSystem nfs = new NPOIFSFileSystem(file);

            // Check the encryption details
            EncryptionInfo infoExpected = new EncryptionInfo(nfs);
            Decryptor      d            = Decryptor.GetInstance(infoExpected);
            bool           passed       = d.VerifyPassword(pass);

            Assert.IsTrue(passed, "Unable to Process: document is encrypted");

            // extract the payload
            MemoryStream bos = new MemoryStream();
            Stream       is1 = d.GetDataStream(nfs);

            IOUtils.Copy(is1, bos);
            is1.Close();
            nfs.Close();
            byte[] payloadExpected = bos.ToArray();

            // check that same verifier/salt lead to same hashes
            byte[] verifierSaltExpected = infoExpected.Verifier.Salt;
            byte[] verifierExpected     = d.GetVerifier();
            byte[] keySpec = d.GetSecretKey().GetEncoded();
            byte[] keySalt = infoExpected.Header.KeySalt;


            EncryptionInfo infoActual = new EncryptionInfo(
                EncryptionMode.Standard
                , infoExpected.Verifier.CipherAlgorithm
                , infoExpected.Verifier.HashAlgorithm
                , infoExpected.Header.KeySize
                , infoExpected.Header.BlockSize
                , infoExpected.Verifier.ChainingMode
                );

            Encryptor e = Encryptor.GetInstance(infoActual);

            e.ConfirmPassword(pass, keySpec, keySalt, verifierExpected, verifierSaltExpected, null);

            CollectionAssert.AreEqual(infoExpected.Verifier.EncryptedVerifier, infoActual.Verifier.EncryptedVerifier);
            CollectionAssert.AreEqual(infoExpected.Verifier.EncryptedVerifierHash, infoActual.Verifier.EncryptedVerifierHash);

            // now we use a newly generated salt/verifier and check
            // if the file content is still the same

            infoActual = new EncryptionInfo(
                EncryptionMode.Standard
                , infoExpected.Verifier.CipherAlgorithm
                , infoExpected.Verifier.HashAlgorithm
                , infoExpected.Header.KeySize
                , infoExpected.Header.BlockSize
                , infoExpected.Verifier.ChainingMode
                );

            e = Encryptor.GetInstance(infoActual);
            e.ConfirmPassword(pass);

            POIFSFileSystem fs = new POIFSFileSystem();
            Stream          os = e.GetDataStream(fs);

            IOUtils.Copy(new MemoryStream(payloadExpected), os);
            os.Close();

            bos.Seek(0, SeekOrigin.Begin); //bos.Reset();
            fs.WriteFileSystem(bos);

            ByteArrayInputStream bis = new ByteArrayInputStream(bos.ToArray());

            // FileOutputStream fos = new FileOutputStream("encrypted.docx");
            // IOUtils.Copy(bis, fos);
            // fos.Close();
            // bis.Reset();

            nfs          = new NPOIFSFileSystem(bis);
            infoExpected = new EncryptionInfo(nfs);
            d            = Decryptor.GetInstance(infoExpected);
            passed       = d.VerifyPassword(pass);
            Assert.IsTrue(passed, "Unable to Process: document is encrypted");

            bos.Seek(0, SeekOrigin.Begin); //bos.Reset();
            is1 = d.GetDataStream(nfs);
            IOUtils.Copy(is1, bos);
            is1.Close();
            nfs.Close();
            byte[] payloadActual = bos.ToArray();

            CollectionAssert.AreEqual(payloadExpected, payloadActual);
            //assertArrayEquals(payloadExpected, payloadActual);
        }
Esempio n. 20
0
        public void AgileEncryption()
        {
            int maxKeyLen = Cipher.GetMaxAllowedKeyLength("AES");

            Assume.That(maxKeyLen == 2147483647, "Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256");

            FileStream       file = POIDataSamples.GetDocumentInstance().GetFile("bug53475-password-is-pass.docx");
            String           pass = "******";
            NPOIFSFileSystem nfs  = new NPOIFSFileSystem(file);

            // Check the encryption details
            EncryptionInfo infoExpected = new EncryptionInfo(nfs);
            Decryptor      decExpected  = Decryptor.GetInstance(infoExpected);
            bool           passed       = decExpected.VerifyPassword(pass);

            Assert.IsTrue(passed, "Unable to Process: document is encrypted");

            // extract the payload
            Stream is1 = decExpected.GetDataStream(nfs);

            byte[] payloadExpected = IOUtils.ToByteArray(is1);
            is1.Close();

            long decPackLenExpected = decExpected.GetLength();

            Assert.AreEqual(decPackLenExpected, payloadExpected.Length);

            is1 = nfs.Root.CreateDocumentInputStream(Decryptor.DEFAULT_POIFS_ENTRY);
            ///is1 = new BoundedInputStream(is1, is1.Available() - 16); // ignore pAdding block
            ///throw new NotImplementedException(BoundedInputStream);
            byte[] encPackExpected = IOUtils.ToByteArray(is1);
            is1.Close();

            // listDir(nfs.Root, "orig", "");

            nfs.Close();

            // check that same verifier/salt lead to same hashes
            byte[] verifierSaltExpected = infoExpected.Verifier.Salt;
            byte[] verifierExpected     = decExpected.GetVerifier();
            byte[] keySalt       = infoExpected.Header.KeySalt;
            byte[] keySpec       = decExpected.GetSecretKey().GetEncoded();
            byte[] integritySalt = decExpected.GetIntegrityHmacKey();
            // the hmacs of the file always differ, as we use PKCS5-pAdding to pad the bytes
            // whereas office just uses random bytes
            // byte integrityHash[] = d.IntegrityHmacValue;

            POIFSFileSystem fs         = new POIFSFileSystem();
            EncryptionInfo  infoActual = new EncryptionInfo(
                EncryptionMode.Agile
                , infoExpected.Verifier.CipherAlgorithm
                , infoExpected.Verifier.HashAlgorithm
                , infoExpected.Header.KeySize
                , infoExpected.Header.BlockSize
                , infoExpected.Verifier.ChainingMode
                );

            Encryptor e = Encryptor.GetInstance(infoActual);

            e.ConfirmPassword(pass, keySpec, keySalt, verifierExpected, verifierSaltExpected, integritySalt);

            Stream os = e.GetDataStream(fs);

            IOUtils.Copy(new MemoryStream(payloadExpected), os);
            os.Close();

            MemoryStream bos = new MemoryStream();

            fs.WriteFileSystem(bos);

            nfs        = new NPOIFSFileSystem(new MemoryStream(bos.ToArray()));
            infoActual = new EncryptionInfo(nfs.Root);
            Decryptor decActual = Decryptor.GetInstance(infoActual);

            passed = decActual.VerifyPassword(pass);
            Assert.IsTrue(passed, "Unable to Process: document is encrypted");

            // extract the payload
            is1 = decActual.GetDataStream(nfs);
            byte[] payloadActual = IOUtils.ToByteArray(is1);
            is1.Close();

            long decPackLenActual = decActual.GetLength();

            is1 = nfs.Root.CreateDocumentInputStream(Decryptor.DEFAULT_POIFS_ENTRY);
            ///is1 = new BoundedInputStream(is1, is1.Available() - 16); // ignore pAdding block
            ///throw new NotImplementedException(BoundedInputStream);
            byte[] encPackActual = IOUtils.ToByteArray(is1);
            is1.Close();

            // listDir(nfs.Root, "copy", "");

            nfs.Close();

            AgileEncryptionHeader aehExpected = (AgileEncryptionHeader)infoExpected.Header;
            AgileEncryptionHeader aehActual   = (AgileEncryptionHeader)infoActual.Header;

            CollectionAssert.AreEqual(aehExpected.GetEncryptedHmacKey(), aehActual.GetEncryptedHmacKey());
            Assert.AreEqual(decPackLenExpected, decPackLenActual);
            CollectionAssert.AreEqual(payloadExpected, payloadActual);
            CollectionAssert.AreEqual(encPackExpected, encPackActual);
        }