<#	
	.NOTES
	===========================================================================
	 Created on:   	5/27/2015 3:24 PM
	 Created by:   	Brian Graf
	 Twitter:       @vBrianGraf
	 Blog: 			http://www.vtagion.com
	===========================================================================
#>

#Encoded Hardening Guide
$Global:Base64 = "[encoded data, 68668 characters]"

Function Import-Xls {
	
<# 
.SYNOPSIS 
Import an Excel file. 
 
.DESCRIPTION 
Import an excel file. Since Excel files can have multiple worksheets, you can specify the worksheet you want to import. You can specify it by number (1, 2, 3) or by name (Sheet1, Sheet2, Sheet3). Imports Worksheet 1 by default. 
 
.PARAMETER Path 
Specifies the path to the Excel file to import. You can also pipe a path to Import-Xls. 
 
.PARAMETER Worksheet 
Specifies the worksheet to import in the Excel file. You can specify it by name or by number. The default is 1. 
Note: Charts don't count as worksheets, so they don't affect the Worksheet numbers. 
 
.INPUTS 
System.String 
 
.OUTPUTS 
Object 
 
.EXAMPLE 
".\employees.xlsx" | Import-Xls -Worksheet 1 
Import Worksheet 1 from employees.xlsx 
 
.EXAMPLE 
".\employees.xlsx" | Import-Xls -Worksheet "Sheet2" 
Import Worksheet "Sheet2" from employees.xlsx 
 
.EXAMPLE 
".\deptA.xslx", ".\deptB.xlsx" | Import-Xls -Worksheet 3 
Import Worksheet 3 from deptA.xlsx and deptB.xlsx. 
Make sure that the worksheets have the same headers, or have some headers in common, or that it works the way you expect. 
 
.EXAMPLE 
Get-ChildItem *.xlsx | Import-Xls -Worksheet "Employees" 
Import Worksheet "Employees" from all .xlsx files in the current directory. 
Make sure that the worksheets have the same headers, or have some headers in common, or that it works the way you expect. 
 
.LINK 
Import-Xls 
http://gallery.technet.microsoft.com/scriptcenter/17bcabe7-322a-43d3-9a27-f3f96618c74b 
Export-Xls 
http://gallery.technet.microsoft.com/scriptcenter/d41565f1-37ef-43cb-9462-a08cd5a610e2 
Import-Csv 
Export-Csv 
 
.NOTES 
Author: Francis de la Cerna 
Created: 2011-03-27 
Modified: 2011-04-09 
#Requires –Version 2.0 

#>	
	
	[CmdletBinding(SupportsShouldProcess = $true)]
	Param (
		[parameter(
				   mandatory = $true,
				   position = 1,
				   ValueFromPipeline = $true,
				   ValueFromPipelineByPropertyName = $true)]
		[String[]]$Path,
		[parameter(mandatory = $false)]
		$Worksheet = 1,
		[parameter(mandatory = $false)]
		[switch]$Force
	)
	
	Begin {
		function GetTempFileName($extension) {
			$temp = [io.path]::GetTempFileName();
			$params = @{
				Path = $temp;
				Destination = $temp + $extension;
				Confirm = $false;
				Verbose = $VerbosePreference;
			}
			Move-Item @params;
			$temp += $extension;
			return $temp;
		}
		
		# since an extension like .xls can have multiple formats, this 
		# will need to be changed 
		# 
		$xlFileFormats = @{
			# single worksheet formats 
			'.csv' = 6;        # 6, 22, 23, 24 
			'.dbf' = 11;       # 7, 8, 11 
			'.dif' = 9;        #  
			'.prn' = 36;       #  
			'.slk' = 2;        # 2, 10 
			'.wk1' = 31;       # 5, 30, 31 
			'.wk3' = 32;       # 15, 32 
			'.wk4' = 38;       #  
			'.wks' = 4;        #  
			'.xlw' = 35;       #  
			
			# multiple worksheet formats 
			'.xls' = -4143;    # -4143, 1, 16, 18, 29, 33, 39, 43 
			'.xlsb' = 50;       # 
			'.xlsm' = 52;       # 
			'.xlsx' = 51;       # 
			'.xml' = 46;       # 
			'.ods' = 60;       # 
		}
		
		$xl = New-Object -ComObject Excel.Application;
		$xl.DisplayAlerts = $false;
		$xl.Visible = $false;
	}
	
	Process {
		$Path | ForEach-Object {
			
			if ($Force -or $psCmdlet.ShouldProcess($_)) {
				
				$fileExist = Test-Path $_
				
				if (-not $fileExist) {
					Write-Error "Error: $_ does not exist" -Category ResourceUnavailable;
				} else {
					# create temporary .csv file from excel file and import .csv 
					# 
					$_ = (Resolve-Path $_).toString();
					$wb = $xl.Workbooks.Add($_);
					if ($?) {
						$csvTemp = GetTempFileName(".csv");
						$ws = $wb.Worksheets.Item($Worksheet);
						$ws.SaveAs($csvTemp, $xlFileFormats[".csv"]);
						$wb.Close($false);
						Remove-Variable -Name ('ws', 'wb') -Confirm:$false;
						Import-Csv $csvTemp;
						Remove-Item $csvTemp -Confirm:$false -Verbose:$VerbosePreference;
					}
				}
			}
		}
	}
	
	End {
		$xl.Quit();
		Remove-Variable -name xl -Confirm:$false;
		[gc]::Collect();
	}
}
Function Show-HardeningGuide {
	$Global:XLS = Import-XLS $env:temp\HG.XLSX
	$ShowGuide = $XLS | Out-GridView
}
Function Assess-VM {
<#	
	.DESCRIPTION
		This cmdlet will allow you to assess the security of the VM's in your environment
	.EXAMPLE
		# Specify Virtual Machines to Assess
		$VM = Get-VM MGMT-AD, MGMT-VCO, WebCommander, Exchange01
		
		# Assess against Risk Profile 2
		Assess-VM -VM $VM -RiskProfile 2
	
	.EXAMPLE
		# Assess all VM's against specific ID's
		$VM = Get-VM
		Assess-VM -VM $VM -ID 9,10,12,22,33,49
		
	.EXAMPLE
		# Assess All VM's against All ID's
		Assess-VM -VM (Get-VM) 
#>
	[CmdletBinding(	   
		DefaultParameterSetName = ”ID”
	)]
	Param (
		#Object receiving the hardening
		[Parameter(
				   Position = 0,
				   ValueFromPipeline = $true,
				   ValueFromPipelineByPropertyName = $true,
				   HelpMessage = 'What object are you running this against?')]
		#[string]$VMs,
		[PSObject[]]
		$VM,
		
		#Hardening Guide Profile
		[Parameter(Mandatory = $false,
				   ValueFromPipeline = $false,
				   HelpMessage = "You must choose which Hardening Guide Risk Profile to use (1-3).",
				   ParameterSetName = 'RiskProfile')]
		#[ValidateRange(1,3)] 
		[int]$RiskProfile,
		
		#Hardening Guide Guideline ID
		[Parameter(Mandatory = $false,
				   ValueFromPipeline = $false,
				   ParameterSetName = 'ID')]
		[string[]]$ID,
		
		[parameter(ParameterSetName = "ID", 
				   ValueFromPipeline = $false)]
		$AllIDs = "1" 
	)
	
	BEGIN {
		# Validate VM Parameter
		# This ensures the object being passed is an object rather than a string
		[int]$Err = 0
		foreach ($object in $vm) { if (($object.GetType().FullName) -ne "VMware.VimAutomation.ViCore.Impl.V1.Inventory.VirtualMachineImpl") { $Err += 1 } }
		if ($Err -gt 0) {
			Write-Error "One or more objects specified in the `$VM parameter is not a VM object"
			Break
		}
		
		
		# Get the Date, used for folder creation and report
		$Date = (Get-Date -Format MM.dd.yy)
		
		# Create array of ID's
		if (-not $ID) {
			$IDs = $null
		} else {
			$IDs = $ID.Replace(' ', '').split(',')
		}
		
		# Manage Risk Profile Parameter value
		$RiskArray = @("1","2","3")

		
		### HTML CSS CODE ###
	$head = @' 
	<style> 
	BODY{font-family:Arial; background-color:#494a4d;} 
	TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse; width: 95.3%} 
	TH{color:#006990; font-size:1.3em; border-width: 1px;padding: 2px;border-style: solid;border-color: black;background-color:#bdbdbd} 
	TD{color:#006990; border-width: 1px;padding: 2px;border-style: solid;border-color: black;background-color:white} 
	h1 {color: #FFFFFF;}
	h2 {BORDER-RIGHT: #bbbbbb 1px solid;PADDING-RIGHT: 0px;BORDER-TOP: #bbbbbb 1px solid;DISPLAY: block;PADDING-LEFT: 0px;FONT-WEIGHT: bold;FONT-SIZE: 16pt;MARGIN-BOTTOM: -1px;MARGIN-LEFT: AUTO;BORDER-LEFT: #bbbbbb 1px solid;COLOR: #FFFFFF;MARGIN-RIGHT: AUTO;PADDING-TOP: 4px;BORDER-BOTTOM: #bbbbbb 1px solid;FONT-FAMILY: Tahoma;POSITION: relative;HEIGHT: 1.5em;WIDTH: 95%;TEXT-INDENT: 10px;BACKGROUND-COLOR: #387C2C;}
	h3 {BORDER-RIGHT: #bbbbbb 1px solid;PADDING-RIGHT: 0px;BORDER-TOP: #bbbbbb 1px solid;DISPLAY: block;PADDING-LEFT: 0px;FONT-WEIGHT: bold;FONT-SIZE: 12pt;MARGIN-BOTTOM: -1px;MARGIN-TOP: -1px;MARGIN-LEFT: AUTO;BORDER-LEFT: #bbbbbb 1px solid;COLOR: #FFFFFF;MARGIN-RIGHT: AUTO;PADDING-TOP: 4px;BORDER-BOTTOM: #bbbbbb 1px solid;FONT-FAMILY: Tahoma;POSITION: relative;HEIGHT: 1.5em;WIDTH: 95%;TEXT-INDENT: 10px;BACKGROUND-COLOR: #6DB33F;}
	h4 {color: #00FFFF; margin-bottom: 0cm; margin-top: 0cm;}
	br { line-height: 25%;}
	</style> 
'@
		#####################
		
		#C heck to see if HG exists in the $Env:Temp folder, if not, place it there
		if (!(Test-Path -Path "$env:Temp\HG.XLSX")) {
			
			# Decode Hardening Guide from script
			$Content = [System.Convert]::FromBase64String($Global:Base64)
			Set-Content -Path $env:temp\HG.XLSX -Value $Content -Encoding Byte
		}
		
		#Save Imported Hardening Guide to $XLS
		$Global:XLS = Import-XLS $env:temp\HG.XLSX
		
	}
	
	PROCESS {
		
		# If risk profile is provided
		if ($RiskArray -contains $RiskProfile) {
			
			$Guidelines = ($XLS | ?{ $_."Guideline ID" -like "VM*" -and $_."Risk Profile" -match $RiskProfile })
			foreach ($Guideline in $Guidelines) {
				
				$ID = $Guideline.ID
				$GuidelineID = $Guideline."Guideline ID"
				$Name = ($GuidelineID.Split("."))[1]
				$Assessment = $Guideline."PowerCLI Command Assessment"
				$Assessment = $Assessment -replace "Get-VM", "`$VM"
				$Description = $Guideline."Description"
				
				Write-Host "Processing: $ID - $Name" -ForegroundColor CYAN
				if ($assessment -ne "") {
					$run = iex ($Assessment)
					if ($run -eq $null) {
						$run = New-Object System.object
						$run | Add-Member -type NoteProperty -name Name -value "Clear"
						$run | Add-Member -type NoteProperty -name Description -value "NO SECURITY HARDENING NEEDED FOR THIS GUIDELINE"
					}
					$Task = $run | ConvertTo-Html -Fragment -PreContent "<Center><h2>$ID - $Name</h2><h3>$Description</h3></Center>" -PostContent "<br>" | Out-String
					$Tasks += $task
				}
			}
		} elseif ($AllIDs -eq "1" -and $ID -eq $null) {
		 
			$Guidelines = ($XLS | ?{ $_."Guideline ID" -like "VM*" })
			foreach ($Guideline in $Guidelines) {
				$ID = $Guideline.ID
				$GuidelineID = $Guideline."Guideline ID"
				$Name = ($GuidelineID.Split("."))[1]
				$Assessment = $Guideline."PowerCLI Command Assessment"
				$Assessment = $Assessment -replace "Get-VM", "`$VM"
				$Description = $Guideline."Description"
				Write-Host "Processing: $ID - $Name" -ForegroundColor CYAN
				if ($assessment -ne "") {
					$run = iex ($Assessment)
					if ($run -eq $null) {
						$run = New-Object System.object
						$run | Add-Member -type NoteProperty -name Name -value "Clear"
						$run | Add-Member -type NoteProperty -name Description -value "NO SECURITY HARDENING NEEDED FOR THIS GUIDELINE"
					}
					$Task = $run | ConvertTo-Html -Fragment -PreContent "<Center><h2>$ID - $Name</h2><br><h3>$Description</h3></Center>" | Out-String
					$Tasks += $task
				}
			}
			
		} else {
			# If Guideline IDs are provided	
			foreach ($line in $ID) {
				$Guideline = ($XLS | ?{ $_."Guideline ID" -like "VM*" -and $_."ID" -eq $Line })
				$GuidelineID = $Guideline."Guideline ID"
				if ($GuidelineID -eq $null) {
					Write-Host "$line is an invalid ID for this object... moving to next ID" -ForegroundColor 'Red'
					Continue
				}
				$Name = ($GuidelineID.Split("."))[1]
				
				$Description = $Guideline."Description"
				$Assessment = $Guideline."PowerCLI Command Assessment"
				$Assessment = $Assessment -replace "Get-VM", "`$VM"
				Write-Host "Processing: $line - $Name" -ForegroundColor CYAN
				if ($assessment -ne "") {
					$run = iex ($Assessment)
					if ($run -eq $null) {
					$run = New-Object System.object
					$run| Add-Member -type NoteProperty -name Name -value "Clear"
					$run | Add-Member -type NoteProperty -name Description -value "NO SECURITY HARDENING NEEDED FOR THIS GUIDELINE"
					}
					$Task = $run | ConvertTo-Html -Fragment -PreContent "<Center><h2>$line - $Name</h2><br><h3>$Description</h3></Center>" -PostContent "<br>" | Out-String
					$Tasks += $task
				}
			}
		}
	}
	
	END {
		# if no tasks were generated, end function and do NOT create empty report
		if ($tasks -eq $null) {Break }
		
		# Get's end time Hours/Minutes for creating the HTML report
		$time = (get-date -Format HH-mm)
		
		# Checks to see if a folder has been created for that date. If not, it will create one.
		if (!(Test-Path c:\Temp\$Date)) {
			Write-Host "Folder does not exist... Creating" -ForegroundColor 'Yellow'
			New-item "C:\Temp\$date" -type Directory
		}
		
		# HTML Report is then generated
		$HTML = ConvertTo-HTML -head $head -PostContent "<Center>$Tasks</Center>" -PreContent “<Center><h1>vSphere 6 VM Hardening Report</h1></Center>” | Out-File "c:\Temp\$Date\$Time-VMAssessment.html" -Force
		
		# Report is opened for user to see
		invoke-item "c:\Temp\$Date\$Time-VMAssessment.html"
	}
}

