一、引入pdfbox依赖
<dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>3.0.0</version>
</dependency>
二、生成一个带js脚本的pdf文件
//Creating PDF document object
PDDocument document = new PDDocument();//Creating a blank page
PDPage blankPage = new PDPage();//Adding the blank page to the document
document.addPage(blankPage);String javaScript = "app.alert('欢迎关注cms.centyun.com');";//Creating PDActionJavaScript object
PDActionJavaScript PDAjavascript = new PDActionJavaScript(javaScript);//Embedding java script
document.getDocumentCatalog().setOpenAction(PDAjavascript);//Saving the document
document.save("d:\\centyun.pdf");
System.out.println("PDF created");//Closing the document
document.close();
三、在浏览器中打开pdf文件触发xss攻击
四、防止pdf的xss攻击
判断pdf文件中是否包含打开文档就运行的js脚本
/*** 校验pdf文件是否包含打开文档就执行的js脚本**/
public static boolean containJavaScript(File file) {try {PDDocument document = Loader.loadPDF(file);PDDestinationOrAction openAction = document.getDocumentCatalog().getOpenAction();if (openAction != null) {String str = openAction.getCOSObject().toString().toLowerCase();return str.contains("javascript") || str.contains("cosname{js}");}} catch (Exception e) {log.error(e.getMessage(), e);}return false;
}
本文到此结束。