Java Code Examples for org.apache.poi.poifs.filesystem.Entry#getName()

The following examples show how to use org.apache.poi.poifs.filesystem.Entry#getName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SummaryInformationSanitiser.java    From DocBleach with MIT License 6 votes vote down vote up
@Override
public boolean test(Entry entry) {
  String entryName = entry.getName();

  if (!SummaryInformation.DEFAULT_STREAM_NAME.equals(entryName)) {
    return true;
  }

  if (!(entry instanceof DocumentEntry)) {
    return true;
  }

  DocumentEntry dsiEntry = (DocumentEntry) entry;
  sanitizeSummaryInformation(session, dsiEntry);

  return true;
}
 
Example 2
Source File: POIFSDump.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static void dump(DirectoryEntry root, File parent) throws IOException {
    for(Iterator<Entry> it = root.getEntries(); it.hasNext();){
        Entry entry = it.next();
        if(entry instanceof DocumentNode){
            DocumentNode node = (DocumentNode)entry;
            DocumentInputStream is = new DocumentInputStream(node);
            byte[] bytes = IOUtils.toByteArray(is);
            is.close();

            OutputStream out = new FileOutputStream(new File(parent, node.getName().trim()));
            try {
            	out.write(bytes);
            } finally {
            	out.close();
            }
        } else if (entry instanceof DirectoryEntry){
            DirectoryEntry dir = (DirectoryEntry)entry;
            File file = new File(parent, entry.getName());
            if(!file.exists() && !file.mkdirs()) {
                throw new IOException("Could not create directory " + file);
            }
            dump(dir, file);
        } else {
            System.err.println("Skipping unsupported POIFS entry: " + entry);
        }
    }
}
 
Example 3
Source File: ObjectRemover.java    From DocBleach with MIT License 5 votes vote down vote up
@Override
public boolean test(Entry entry) {
  String entryName = entry.getName();

  if (!isObject(entryName)) {
    return true;
  }

  LOGGER.info("Found Compound Objects, removing them.");
  StringBuilder infos = new StringBuilder();
  if (entry instanceof DirectoryEntry) {
    Set<String> entryNames = ((DirectoryEntry) entry).getEntryNames();
    LOGGER.trace("Compound Objects' entries: {}", entryNames);
    infos.append("Entries: ").append(entryNames);
  } else if (entry instanceof DocumentEntry) {
    int size = ((DocumentEntry) entry).getSize();
    infos.append("Size: ").append(size);
  }

  Threat threat = Threat.builder()
      .type(ThreatType.EXTERNAL_CONTENT)
      .severity(ThreatSeverity.HIGH)
      .action(ThreatAction.REMOVE)
      .location(entryName)
      .details(infos.toString())
      .build();

  session.recordThreat(threat);

  return false;
}
 
Example 4
Source File: MacroRemover.java    From DocBleach with MIT License 5 votes vote down vote up
@Override
public boolean test(Entry entry) {
  String entryName = entry.getName();

  // Matches _VBA_PROJECT_CUR, VBA, ... :)
  if (!isMacro(entryName)) {
    return true;
  }

  LOGGER.info("Found Macros, removing them.");
  StringBuilder infos = new StringBuilder();
  if (entry instanceof DirectoryEntry) {
    Set<String> entryNames = ((DirectoryEntry) entry).getEntryNames();
    LOGGER.trace("Macros' entries: {}", entryNames);
    infos.append("Entries: ").append(entryNames);
  } else if (entry instanceof DocumentEntry) {
    int size = ((DocumentEntry) entry).getSize();
    infos.append("Size: ").append(size);
  }

  Threat threat = Threat.builder()
      .type(ThreatType.ACTIVE_CONTENT)
      .severity(ThreatSeverity.EXTREME)
      .action(ThreatAction.REMOVE)
      .location(entryName)
      .details(infos.toString())
      .build();

  session.recordThreat(threat);

  return false;
}
 
Example 5
Source File: VBAMacroReader.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Reads VBA Project modules from a VBA Project directory located at
 * <tt>macroDir</tt> into <tt>modules</tt>.
 *
 * @since 3.15-beta2
 */    
protected void readMacros(DirectoryNode macroDir, ModuleMap modules) throws IOException {
    for (Entry entry : macroDir) {
        if (! (entry instanceof DocumentNode)) { continue; }
        
        String name = entry.getName();
        DocumentNode document = (DocumentNode)entry;
        DocumentInputStream dis = new DocumentInputStream(document);
        try {
            if ("dir".equalsIgnoreCase(name)) {
                // process DIR
                RLEDecompressingInputStream in = new RLEDecompressingInputStream(dis);
                String streamName = null;
                int recordId = 0;
                try {
                    while (true) {
                        recordId = in.readShort();
                        if (EOF == recordId
                                || VERSION_INDEPENDENT_TERMINATOR == recordId) {
                            break;
                        }
                        int recordLength = in.readInt();
                        switch (recordId) {
                        case PROJECTVERSION:
                            trySkip(in, 6);
                            break;
                        case PROJECTCODEPAGE:
                            int codepage = in.readShort();
                            modules.charset = Charset.forName(CodePageUtil.codepageToEncoding(codepage, true));
                            break;
                        case STREAMNAME:
                            streamName = readString(in, recordLength, modules.charset);
                            int reserved = in.readShort();
                            if (reserved != STREAMNAME_RESERVED) {
                                throw new IOException("Expected x0032 after stream name before Unicode stream name, but found: "+
                                        Integer.toHexString(reserved));
                            }
                            int unicodeNameRecordLength = in.readInt();
                            readUnicodeString(in, unicodeNameRecordLength);
                            // do something with this at some point
                            break;
                        case MODULEOFFSET:
                            readModule(in, streamName, modules);
                            break;
                        default:
                            trySkip(in, recordLength);
                            break;
                        }
                    }
                } catch (final IOException e) {
                    throw new IOException(
                            "Error occurred while reading macros at section id "
                            + recordId + " (" + HexDump.shortToHex(recordId) + ")", e);
                }
                finally {
                    in.close();
                }
            } else if (!startsWithIgnoreCase(name, "__SRP")
                    && !startsWithIgnoreCase(name, "_VBA_PROJECT")) {
                // process module, skip __SRP and _VBA_PROJECT since these do not contain macros
                readModule(dis, name, modules);
            }
        }
        finally {
            dis.close();
        }
    }
}
 
Example 6
Source File: CryptoAPIEncryptor.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Encrypt the Document-/SummaryInformation and other optionally streams.
 * Opposed to other crypto modes, cryptoapi is record based and can't be used
 * to stream-encrypt a whole file
 * 
 * @see <a href="http://msdn.microsoft.com/en-us/library/dd943321(v=office.12).aspx">2.3.5.4 RC4 CryptoAPI Encrypted Summary Stream</a>
 */
public void setSummaryEntries(DirectoryNode dir, String encryptedStream, NPOIFSFileSystem entries)
throws IOException, GeneralSecurityException {
    CryptoAPIDocumentOutputStream bos = new CryptoAPIDocumentOutputStream(this); // NOSONAR
    byte buf[] = new byte[8];
    
    bos.write(buf, 0, 8); // skip header
    List<StreamDescriptorEntry> descList = new ArrayList<StreamDescriptorEntry>();

    int block = 0;
    for (Entry entry : entries.getRoot()) {
        if (entry.isDirectoryEntry()) {
            continue;
        }
        StreamDescriptorEntry descEntry = new StreamDescriptorEntry();
        descEntry.block = block;
        descEntry.streamOffset = bos.size();
        descEntry.streamName = entry.getName();
        descEntry.flags = StreamDescriptorEntry.flagStream.setValue(0, 1);
        descEntry.reserved2 = 0;
        
        bos.setBlock(block);
        DocumentInputStream dis = dir.createDocumentInputStream(entry);
        IOUtils.copy(dis, bos);
        dis.close();
        
        descEntry.streamSize = bos.size() - descEntry.streamOffset;
        descList.add(descEntry);
        
        block++;
    }
    
    int streamDescriptorArrayOffset = bos.size();
    
    bos.setBlock(0);
    LittleEndian.putUInt(buf, 0, descList.size());
    bos.write(buf, 0, 4);
    
    for (StreamDescriptorEntry sde : descList) {
        LittleEndian.putUInt(buf, 0, sde.streamOffset);
        bos.write(buf, 0, 4);
        LittleEndian.putUInt(buf, 0, sde.streamSize);
        bos.write(buf, 0, 4);
        LittleEndian.putUShort(buf, 0, sde.block);
        bos.write(buf, 0, 2);
        LittleEndian.putUByte(buf, 0, (short)sde.streamName.length());
        bos.write(buf, 0, 1);
        LittleEndian.putUByte(buf, 0, (short)sde.flags);
        bos.write(buf, 0, 1);
        LittleEndian.putUInt(buf, 0, sde.reserved2);
        bos.write(buf, 0, 4);
        byte nameBytes[] = StringUtil.getToUnicodeLE(sde.streamName);
        bos.write(nameBytes, 0, nameBytes.length);
        LittleEndian.putShort(buf, 0, (short)0); // null-termination
        bos.write(buf, 0, 2);
    }
    
    int savedSize = bos.size();
    int streamDescriptorArraySize = savedSize - streamDescriptorArrayOffset;
    LittleEndian.putUInt(buf, 0, streamDescriptorArrayOffset);
    LittleEndian.putUInt(buf, 4, streamDescriptorArraySize);

    bos.reset();
    bos.setBlock(0);
    bos.write(buf, 0, 8);
    bos.setSize(savedSize);
    
    dir.createDocument(encryptedStream, new ByteArrayInputStream(bos.getBuf(), 0, savedSize));
}
 
Example 7
Source File: MppDump.java    From mpxj with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * This method recursively descends the directory structure, dumping
 * details of any files it finds to the output file.
 *
 * @param pw Output PrintWriter
 * @param dir DirectoryEntry to dump
 * @param prefix prefix used to identify path to this object
 * @param showData flag indicating if data is dumped, or just structure
 * @param hex set to true if hex output is required
 * @param indent indent used if displaying structure only
 * @throws Exception Thrown on file read errors
 */
private static void dumpTree(PrintWriter pw, DirectoryEntry dir, String prefix, boolean showData, boolean hex, String indent) throws Exception
{
   long byteCount;

   for (Iterator<Entry> iter = dir.getEntries(); iter.hasNext();)
   {
      Entry entry = iter.next();
      if (entry instanceof DirectoryEntry)
      {
         String childIndent = indent;
         if (childIndent != null)
         {
            childIndent += " ";
         }

         String childPrefix = prefix + "[" + entry.getName() + "].";
         pw.println("start dir: " + prefix + entry.getName());
         dumpTree(pw, (DirectoryEntry) entry, childPrefix, showData, hex, childIndent);
         pw.println("end dir: " + prefix + entry.getName());
      }
      else
         if (entry instanceof DocumentEntry)
         {
            if (showData)
            {
               pw.println("start doc: " + prefix + entry.getName());
               if (hex == true)
               {
                  byteCount = hexdump(new DocumentInputStream((DocumentEntry) entry), pw);
               }
               else
               {
                  byteCount = asciidump(new DocumentInputStream((DocumentEntry) entry), pw);
               }
               pw.println("end doc: " + prefix + entry.getName() + " (" + byteCount + " bytes read)");
            }
            else
            {
               if (indent != null)
               {
                  pw.print(indent);
               }
               pw.println("doc: " + prefix + entry.getName());
            }
         }
         else
         {
            pw.println("found unknown: " + prefix + entry.getName());
         }
   }
}