Question

I have posted my code below for an Excel exporting class (most of it anyway). The issue I am incurring is that this export is not safe when it comes to injection attacks. I was easily able to mask the initial command with parameters, however, when I passed the parameterized command to the Export(string) method, it loses the values previously set within the parameters; it only passes the literal string (i.e. SELECT * FROM TABLE WHERE COLUMN_NAME = @Parameter1). What I am trying to figure out is a way to prevent this code from being unsafe. I really need this functionality. It has been fine in the past because of the desired audience of the applications, but I cannot use this specific code considering it will be customer facing and more less open to public use. :/ Any suggestions of how I can achieve this goal?

public static void Export(string CrossoverStatement = "SELECT * FROM TABLE")
{
    // @@Parameters
    //
    // CrossoverStatement string :
    //     This is the string representation of the procedure executed to obtain the desired crossover query results.

    //Create our database connection as well as the excel reference and workbook/worksheet we are using to export the data
    string ODBCConnection = "SERVER INFO";

    Application xls = new Application();
    xls.SheetsInNewWorkbook = 1;
    // Create our new excel application and add our workbooks/worksheets
    Workbook Workbook = xls.Workbooks.Add();
    Worksheet CrossoverPartsWorksheet = xls.Worksheets[1];
    // Hide our excel object if it's visible.
    xls.Visible = false;
    // Turn off screen updating so our export will process more quickly.
    xls.ScreenUpdating = false;

    CrossoverPartsWorksheet.Name = "Crossover";
    if (CrossoverStatement != string.Empty)
    {
        CrossoverPartsWorksheet.Select();
        var xlsheet = CrossoverPartsWorksheet.ListObjects.AddEx(SourceType: XlListObjectSourceType.xlSrcExternal,
                                                                Source: ODBCConnection,
                                                                Destination: xls.Range["$A$1"]).QueryTable;
        xlsheet.CommandText = CrossoverStatement;
        xlsheet.RowNumbers = false;
        xlsheet.FillAdjacentFormulas = false;
        xlsheet.PreserveColumnInfo = true;
        xlsheet.PreserveFormatting = true;
        xlsheet.RefreshOnFileOpen = false;
        xlsheet.BackgroundQuery = false;
        xlsheet.SavePassword = false;
        xlsheet.AdjustColumnWidth = true;
        xlsheet.RefreshPeriod = 0;
        xlsheet.RefreshStyle = XlCellInsertionMode.xlInsertEntireRows;
        xlsheet.Refresh(false);
        xlsheet.ListObject.ShowAutoFilter = false;
        xlsheet.ListObject.TableStyle = "TableStyleMedium16";
        // Unlink our table from the server and convert to a range.
        xlsheet.ListObject.Unlink();
        // Freeze our column headers.
        xls.Application.Rows["2:2"].Select();
        xls.ActiveWindow.FreezePanes = true;
        xls.ActiveWindow.DisplayGridlines = false;
        // Autofit our rows and columns.
        xls.Application.Cells.EntireColumn.AutoFit();
        xls.Application.Cells.EntireRow.AutoFit();
        // Select the first cell in the worksheet.
        xls.Application.Range["$A$2"].Select();
        // Turn off alerts to prevent asking for 'overwrite existing' and 'save changes' messages.
        xls.DisplayAlerts = false;
    }

    // Make our excel application visible
    xls.Visible = true;

    // Release our resources.
    Marshal.ReleaseComObject(Workbook);
    Marshal.ReleaseComObject(CrossoverPartsWorksheet);
    Marshal.ReleaseComObject(xls);
}
Was it helpful?

Solution

Here is the best way to complete this request that I could come up with. Perform a parameterized query and pass the resulting data to a table which you can use when calling Export(datatable).

Problem resolved.

public static void Export(System.Data.DataTable CrossoverDataTable)
{
    // @@Parameters
    //
    // CrossoverDataTable DataTable :
    //     This is a data table containing information to be exported to our excel application.
    //     Requested as a way to circumvent sql injection opposed to the initial overload accepting only a string .commandtext.

    Application xls = new Application();
    xls.SheetsInNewWorkbook = 1;

    // Create our new excel application and add our workbooks/worksheets
    Workbook Workbook = xls.Workbooks.Add();
    Worksheet CrossoverPartsWorksheet = xls.Worksheets[1];

    // Hide our excel object if it's visible.
    xls.Visible = false;

    // Turn off screen updating so our export will process more quickly.
    xls.ScreenUpdating = false;

    // Turn off calculations if set to automatic; this can help prevent memory leaks.
    xls.Calculation = xls.Calculation == XlCalculation.xlCalculationAutomatic ? XlCalculation.xlCalculationManual : XlCalculation.xlCalculationManual;

    // Create an excel table and fill it will our query table.
    CrossoverPartsWorksheet.Name = "Crossover Data";
    CrossoverPartsWorksheet.Select();
    {

        // Create a row with our column headers.
        for (int column = 0; column < CrossoverDataTable.Columns.Count; column++)
        {
            CrossoverPartsWorksheet.Cells[1, column + 1] = CrossoverDataTable.Columns[column].ColumnName;
        }

        // Export our datatable information to excel.
        for (int row = 0; row < CrossoverDataTable.Rows.Count; row++)
        {
            for (int column = 0; column < CrossoverDataTable.Columns.Count; column++)
            {
                CrossoverPartsWorksheet.Cells[row + 2, column + 1] = (CrossoverDataTable.Rows[row][column].ToString());
            }
        }
    }

    // Freeze our column headers.
    xls.Application.Rows["2:2"].Select();
    xls.ActiveWindow.FreezePanes = true;
    xls.ActiveWindow.DisplayGridlines = false;

    // Autofit our rows and columns.
    xls.Application.Cells.EntireColumn.AutoFit();
    xls.Application.Cells.EntireRow.AutoFit();

    // Select the first cell in the worksheet.
    xls.Application.Range["$A$2"].Select();

    // Turn off alerts to prevent asking for 'overwrite existing' and 'save changes' messages.
    xls.DisplayAlerts = false;

    // ******************************************************************************************************************
    // This section is commented out for now but can be enabled later to have excel sheets show on screen after creation.
    // ******************************************************************************************************************
    // Make our excel application visible
    xls.Visible = true;

    // Turn screen updating back on
    xls.ScreenUpdating = true;

    // Turn automatic calulation back on
    xls.Calculation = XlCalculation.xlCalculationAutomatic;

    // Release our resources.
    Marshal.ReleaseComObject(Workbook);
    Marshal.ReleaseComObject(CrossoverPartsWorksheet);
    Marshal.ReleaseComObject(xls);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top