Framework/Managers/AzSDKPDFExtension.ps1

Set-StrictMode -Version Latest

class AzSDKPDFExtension
{
    static [void] GeneratePDF([string] $reportFolderPath, [PSObject] $subscriptionObject, [PSObject] $dataObject, [bool] $isLandscape)
    {
        # Get Context Info
        $executedBy = (Get-AzureRmContext).Account

        # Verify whether word is installed on machine

        If (test-path HKLM:SOFTWARE\Classes\Word.Application)
        {
            # Initialize word file
            try
            {
                $Word = New-Object -ComObject word.application
                $Word.Visible = $false;
                $AzSDKReportDoc = $Word.Documents.Add();
                if($isLandscape)
                {
                    $AzSDKReportDoc.PageSetup.Orientation = 1
                }
                else
                {
                    $AzSDKReportDoc.PageSetup.Orientation = 0
                }

                $pdfPath = "$reportFolderPath\SecurityReport.pdf"
                $margin = 36 # 1.26 cm
                $AzSDKReportDoc.PageSetup.LeftMargin = $margin
                $AzSDKReportDoc.PageSetup.RightMargin = $margin
                #$AzSDKReportDoc.PageSetup.TopMargin = $margin
                $AzSDKReportDoc.PageSetup.BottomMargin = $margin

                $isSubscriptionCore = $false

                $selection = $Word.Selection
                $selection.WholeStory
                $selection.Style = "No Spacing"

                # Region Front Page
                [AzSDKPDFExtension]::WriteText($selection, 'Secure DevOps Kit for Azure (AzSDK)','Title', $true, $true, $false)
                [AzSDKPDFExtension]::WriteText($selection, 'Security Report','TOC Heading', $true, $true, $false)
                $selection.InsertBreak(6)
                $selection.InsertBreak(6)
                $selection.InsertBreak(6)
                $selection.InsertBreak(6)
                $selection.InsertBreak(6)

                $TitleTableRange = $selection.Range();
                $AzSDKReportDoc.Tables.Add($TitleTableRange,11,2) | Out-Null
                $AzSDKTitleTable = $AzSDKReportDoc.Tables.item(1)
                [AzSDKPDFExtension]::WriteHeaderTableCell($AzSDKTitleTable, 1, 'Subscription Name', $subscriptionObject.SubscriptionName)
                [AzSDKPDFExtension]::WriteHeaderTableCell($AzSDKTitleTable, 2, 'SubscriptionId', $subscriptionObject.SubscriptionId)
                [AzSDKPDFExtension]::WriteHeaderTableCell($AzSDKTitleTable, 3, 'AzSDK Version', $dataObject.MyCommand.Version.ToString())
                [AzSDKPDFExtension]::WriteHeaderTableCell($AzSDKTitleTable, 4, 'Generated by', 'AzSDK')
                [AzSDKPDFExtension]::WriteHeaderTableCell($AzSDKTitleTable, 5, 'Generated on', (get-date).ToUniversalTime().ToString("MMMM dd, yyyy HH:mm") + " (UTC)")
                [AzSDKPDFExtension]::WriteHeaderTableCell($AzSDKTitleTable, 6, 'Requested by', $executedBy.Id.ToString() + " (" + $executedBy.Type.ToString() + ")")
                [AzSDKPDFExtension]::WriteHeaderTableCell($AzSDKTitleTable, 7, 'Command Executed', $dataObject.Line.Trim())
                [AzSDKPDFExtension]::WriteHeaderTableCell($AzSDKTitleTable, 8, 'Documentation', 'http://aka.ms/azsdkdocs')
                [AzSDKPDFExtension]::WriteHeaderTableCell($AzSDKTitleTable, 9, 'FAQ', 'http://aka.ms/azsdkdocs/faq')
                [AzSDKPDFExtension]::WriteHeaderTableCell($AzSDKTitleTable, 10, 'Support DL', 'mailto:isrmazsdksup@microsoft.com')

                $AzSDKTitleTable.Borders.OutsideLineStyle = 1
                $AzSDKTitleTable.Style = 'Table Grid Light'
                $AzSDKTitleTable.Borders.OutsideLineStyle = 1
                $AzSDKTitleTable.Borders.InsideLineStyle = 0
                $AzSDKTitleTable.Columns.AutoFit()

                $Word.Selection.Start= $AzSDKReportDoc.Content.End

                $selection.InsertBreak(7)
                #end region

                # Region TOC
                [AzSDKPDFExtension]::WriteText($selection, 'Contents','TOC Heading', $false, $true, $false)
                $range = $Selection.Range
                $toc = $AzSDKReportDoc.TablesOfContents.Add($range)
                $selection.TypeParagraph()
                $selection.InsertBreak(7)

                # End region TOC

                # Region Headers/Footers

                #$Section = $AzSDKReportDoc.Sections.Item(1)
                #$Header = $Section.Footers.Item(1)
                #$Header.Range.Text = (get-date).ToUniversalTime().ToString("HH:mm MMMM dd, yyyy") + "(UTC)"
                #$Header.Range.Font.Size = 9
                #$Header.Range.ParagraphFormat.Alignment = 2
                $AzSDKReportDoc.Sections(1).Footers(1).PageNumbers.Add(2)

                # End region Headers/Footers

                #region -> Add the CSV report
                $selection.TypeText("Security Report Summary");
                $selection.Style = 'Heading 1'
                $selection.TypeParagraph()
                $selection.Style = 'No Spacing'
                $selection.InsertBreak(6)

                $ReportRange = $selection.Range();

                $reportCSVFilePath = @();
                $reportCSVFilePath += Get-ChildItem -Path $reportFolderPath -Filter "*.CSV" -Recurse
                if($reportCSVFilePath.Length -le 0)
                {
                    [AzSDKPDFExtension]::WriteText($selection, 'Unable to find the required security report under the report folder.','No Spacing', $false, $true, $false)
                    [AzSDKPDFExtension]::WriteText($selection, 'Or','No Spacing', $true, $true, $false)
                    [AzSDKPDFExtension]::WriteText($selection, 'No controls have been found to evaluate for the Subscription.','No Spacing', $false, $true, $false)
                    #throw "Didn't find the required security report under the report folder.";
                }
                else
                {
                    $controls = Import-Csv -Path $reportCSVFilePath[0].FullName
                    $isAttestedResult = $false
                    if(($controls | Measure-Object).Count -gt 0)
                    {
                        $Number_Of_Controls = (($controls | Measure-Object).Count +1)
                        if($controls[0] | Get-Member -Name "AttestedSubStatus")
                        {
                            $isAttestedResult = $true
                        }

                        if($isAttestedResult)
                        {
                            $Number_Of_Columns = 7 # ControlID, Status, RG, ResourceName, Control Severity
                        }
                        else
                        {
                            $Number_Of_Columns = 6
                        }

                        $x = 2

                        $AzSDKReportDoc.Tables.Add($ReportRange,$Number_Of_Controls,$Number_Of_Columns) | Out-Null
                        $AzSDKReportTable = $AzSDKReportDoc.Tables.item(2)

                        $AzSDKReportTable.Cell(1,1).Range.Text = "ControlId"
                        $AzSDKReportTable.Cell(1,2).Range.Text = "Status"
                        $AzSDKReportTable.Cell(1,3).Range.Text = "ResourceGroup"
                        $AzSDKReportTable.Cell(1,4).Range.Text = "Resource"
                        $AzSDKReportTable.Cell(1,5).Range.Text = "Severity"
                        $AzSDKReportTable.Cell(1,6).Range.Text = "Description"
                        if($isAttestedResult)
                        {
                            $AzSDKReportTable.Cell(1,7).Range.Text = "Attestation Description"
                        }

                        Foreach($control in $controls)
                        {
                             $AzSDKReportTable.Cell($x,1).Range.Text=$control.ControlId
                             $AzSDKReportTable.Cell($x,2).Range.Text=$control.Status
                             if($control | Get-Member -Name "ResourceGroupName")
                             {
                                $AzSDKReportTable.Cell($x,3).Range.Text=$control.ResourceGroupName
                                if(($control | Get-Member -Name "ChildResourceName") -and (-Not [string]::IsNullOrEmpty($control.ChildResourceName)))
                                {
                                    $AzSDKReportTable.Cell($x,4).Range.Text=$control.ResourceName + "/" + $control.ChildResourceName
                                }
                                else
                                {
                                    $AzSDKReportTable.Cell($x,4).Range.Text=$control.ResourceName
                                }
                             }
                             else
                             {
                                $isSubscriptionCore = $true
                                $AzSDKReportTable.Cell($x,3).Range.Text="Subscription"
                                $AzSDKReportTable.Cell($x,4).Range.Text="Subscription"
                             }
                             $AzSDKReportTable.Cell($x,5).Range.Text=$control.ControlSeverity
                             $AzSDKReportTable.Cell($x,6).Range.Text=$control.Description
                             $AzSDKReportTable.Cell($x,6).Range.Font.Size = 9

                             if($isAttestedResult -and ($control.AttestedSubStatus))
                             {
                                #$AzSDKReportTable.Cell($x,7).Range.Text=$control.ActualStatus
                                $attstionDescription = "Attested Status: " + $control.AttestedSubStatus + "`vAttested By: " + $control.AttestedBy + "`vJustification: " + $control.AttesterJustification
                                $AzSDKReportTable.Cell($x,7).Range.Text = $attstionDescription
                                $AzSDKReportTable.Cell($x,7).Range.Font.Size = 9
                             }
                             $x++

                             #if(($control | Get-Member -Name "AttestedSubStatus") -and ($control.AttestedSubStatus))
                             #{
                                #$AzSDKReportTable.Cell($x,2).Range.Text= "Actual Status : " + $control.ActualStatus

                                #$attstionDescription = "Attestation Description`vAttested Status: " + $control.AttestedSubStatus + "`vAttested By: " + $control.AttestedBy + "`vJustification: " + $control.AttesterJustification
                                #$AzSDKReportTable.Cell($x,6).Range.Text = $attstionDescription
                                #$AzSDKReportTable.Cell($x,6).Range.Font.Size = 9
                                #$x++;
                             # }
                        }

                        $AzSDKReportTable.Style = 'Grid Table 4 - Accent 1'
                        $AzSDKReportTable.Columns.Autofit()
                        $selection = $Word.Selection
                        $selection.WholeStory
                        $selection.Style = "No Spacing"
                        $wdStory = 6
                        $wdMove = 0

                        $ret = $selection.EndKey($wdStory, $wdMove)
                        $selection.TypeParagraph()
                        $selection.InsertBreak(7)
                    }
                

                    #end region

                    #region -> Adding PowerShell output

                    Get-ChildItem -Path $reportFolderPath -Directory | Where-Object {($_.Name -eq "etc")} | %{
                        $rootfolder = $_
                        [AzSDKPDFExtension]::WriteText($selection, 'PowerShell Output','Heading 1', $false, $true, $false)

                        Get-ChildItem -Path $rootfolder.FullName -Recurse -Filter "PowerShellOutput.log" | %{
                            $logfilepath = $_
                            $log = Get-Content $logfilepath.FullName | Out-String
                            [AzSDKPDFExtension]::WriteText($selection, $log,'No Spacing', $false, $true, $false)
                            $selection.TypeText("#################################################################");
                            $selection.TypeParagraph()
                        }
                    }

                    $selection.InsertBreak(7)

                    #end region -> Adding PowerShell output

                    #region -> Adding detailed logs

                    [AzSDKPDFExtension]::WriteText($selection, 'Detailed Output','Heading 1', $false, $true, $false)
                    $selection.InsertBreak(6)

                    Get-ChildItem -Path $reportFolderPath -Directory | Where-Object {-not ($_.Name -eq "etc")} | %{
                        $rootfolder = $_

                        if($isSubscriptionCore)
                        {
                            [AzSDKPDFExtension]::WriteText($selection, 'Subscription Name: '+ ($rootfolder.Name),'Heading 2', $false, $true, $false)
                        }
                        else
                        {
                            [AzSDKPDFExtension]::WriteText($selection, 'Resource Group Name: ' + ($rootfolder.Name),'Heading 2', $false, $true, $false)
                        }
                        Get-ChildItem -Path $rootfolder.FullName -Recurse -Filter "*.log" | %{
                            $logfilepath = $_
                            [AzSDKPDFExtension]::WriteText($selection, 'Resource Type: ' + ($logfilepath.BaseName),'Heading 3', $false, $true, $false)
                            $logs = Get-Content $logfilepath.FullName
                            ForEach($log in $logs)
                            {
                                [AzSDKPDFExtension]::WriteText($selection, ($log | Out-String),'No Spacing', $false, $false, $false)
                            }

                            $selection.TypeParagraph()
                            $selection.InsertBreak(7)
                        }
                    }

                    #end region

                    # Update table of content
                    $toc.Update()
                }
            }
            catch
            {
                throw $_.Exception
            }
            finally
            {
                $wdExportFormatPDF = 17
                $wdDoNotSaveChanges = 0
                $AzSDKReportDoc.ExportAsFixedFormat($pdfPath,$wdExportFormatPDF)
                $AzSDKReportDoc.close([ref]$wdDoNotSaveChanges)
                $Word.Quit()
                if (test-path variable:AzSDKReportDoc)
                {
                    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($AzSDKReportDoc) | Out-Null
                }
                if (test-path variable:word)
                {
                    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) | Out-Null
                }
                if (test-path variable:range)
                {
                    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($range) | Out-Null
                }
                if (test-path variable:ReportRange)
                {
                    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($ReportRange) | Out-Null
                }
                if (test-path variable:AzSDKReportTable)
                {
                    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($AzSDKReportTable) | Out-Null
                }
                if (test-path variable:TitleTableRange)
                {
                    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($TitleTableRange) | Out-Null
                }
                if (test-path variable:AzSDKTitleTable)
                {
                    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($AzSDKTitleTable) | Out-Null
                }

                Remove-Variable range
                [gc]::collect()
                [gc]::WaitForPendingFinalizers()
            }
        }
        else
        {
            throw ([SuppressedException]::new(("You must have Microsoft Word application installed on machine to generate PDF report."), [SuppressedExceptionType]::Generic))
        }
    }

    static [void] WriteText([PSObject] $selectionObj, [string] $textToWrite, [string] $style, [bool] $bold, [bool] $newParagraph, [bool] $newLine)
    {
        $selectionObj.TypeText($textToWrite);
        $selectionObj.Style = $style
        if($bold)
        {
            $selectionObj.Range.Font.Bold = 1
        }
        else
        {
            $selectionObj.Range.Font.Bold = 0
        }

        if($newParagraph)
        {
            $selectionObj.TypeParagraph()
        }
        if($newLine)
        {
            $selectionObj.TypeText("`v");
        }
        $selectionObj.WholeStory
        $selectionObj.Style = "No Spacing"
    }

    static [void] WriteHeaderTableCell([PSObject] $tableObj, [int] $row, [string] $title, [string] $value)
    {
        $tableObj.Cell($row,1).Range.Text = $title
        $tableObj.Cell($row,1).Range.Bold = 1
        $tableObj.Cell($row,2).Range.Text = $value
    }
}