我正在尝试为C#中的Excel文件实现OWASP - Protect FileUpload Against Malicious File。
我正在努力寻找有关如何获取每个Macro / Vba / OLE_Object的任何文档。
这是我当前的代码:
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using System;
using System.IO;
namespace Utils.FileSecurity
{
public static class ExcelDocumentDetector
{
public static bool IsSafe(byte[] fileBytes)
{
try
{
using (var document = SpreadsheetDocument.Open(new MemoryStream(fileBytes), true))
{
if (document.DocumentType == SpreadsheetDocumentType.MacroEnabledWorkbook
|| document.DocumentType == SpreadsheetDocumentType.MacroEnabledTemplate)
return false;
foreach (var sheet in document.WorkbookPart.Workbook.Sheets)
{
// ???
}
}
}
catch (Exception e)
{
return false;
}
return true;
}
}
}
你们对此有任何提示/文档吗? 谢谢
答案 0 :(得分:-1)
[HttpPost]
public ActionResult UploadExcel( HttpPostedFileBase postedFile)
{
string filePath = string.Empty;
if (postedFile != null)
{
string path = Server.MapPath("~/UploadFiles/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
filePath = path + Path.GetFileName(postedFile.FileName);
string extension = Path.GetExtension(postedFile.FileName);
postedFile.SaveAs(filePath);
string conString = string.Empty;
switch (extension)
{
case ".xls": //Excel 97-03.
conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07 and above.
conString = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
break;
}
DataTable dt = new DataTable();
conString = string.Format(conString, filePath);
using (OleDbConnection connExcel = new OleDbConnection(conString))
{
using (OleDbCommand cmdExcel = new OleDbCommand())
{
using (OleDbDataAdapter odaExcel = new OleDbDataAdapter())
{
cmdExcel.Connection = connExcel;
//Get the name of First Sheet.
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
connExcel.Close();
//Read Data from First Sheet.
connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + sheetName + "]";
odaExcel.SelectCommand = cmdExcel;
odaExcel.Fill(dt);
connExcel.Close();
}
}
}
string output="";
for (int i = 0; i < dt.Rows.Count; i++)
{
output = output + dt.Rows[i]["Email"].ToString();
output += (i < dt.Rows.Count) ? "," : string.Empty;
}
output = output.Remove(output.Length - 1);
}
return View();
}